@odoo/o-spreadsheet 19.1.20 → 19.1.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/o_spreadsheet.cjs.js +70 -27
- package/dist/o_spreadsheet.css +3 -3
- package/dist/o_spreadsheet.esm.js +70 -27
- package/dist/o_spreadsheet.iife.js +70 -27
- package/dist/o_spreadsheet.iife.min.js +202 -202
- package/dist/o_spreadsheet.xml +3 -3
- package/package.json +1 -1
|
@@ -7,9 +7,9 @@ Did you forget to inject your store instance?
|
|
|
7
7
|
const stores = useStoreProvider();
|
|
8
8
|
stores.inject(MyMetaStore, storeInstance);
|
|
9
9
|
`)}}return t}var ir=class{get;disposeCallbacks=[];constructor(e){this.get=e}onDispose(e){this.disposeCallbacks.push(e)}dispose(){this.disposeCallbacks.forEach(e=>e())}};function ar(){let e=(0,t.useEnv)();if(e.__spreadsheet_stores__ instanceof tr)return e.__spreadsheet_stores__;let n=new tr;return(0,t.useSubEnv)({__spreadsheet_stores__:n,getStore:e=>cr(n.get(e),()=>n.trigger(`store-updated`))}),(0,t.onWillUnmount)(()=>n.dispose()),n}function D(e){let n=lr((0,t.useEnv)());return sr(n,n.get(e))}function or(e,...n){let r=lr((0,t.useEnv)()),i=r.instantiate(e,...n);return(0,t.onWillUnmount)(()=>i.dispose()),sr(r,i)}function sr(e,n){let r=(0,t.useComponent)();return cr(n,()=>{(0,t.status)(r)===`mounted`&&e.trigger(`store-updated`)})}function cr(e,t){return new Proxy(e,{get(n,r,i){let a=n,o=Reflect.get(n,r,a);return e.mutators?.includes(r)?new Proxy(o,{apply(e,n,r){Reflect.apply(e,a,r)!==`noStateChange`&&t()}}):o}})}function lr(e){let t=e.__spreadsheet_stores__;if(!(t instanceof tr))throw Error(`No store provider found. Did you forget to call useStoreProvider()?`);return t}let ur=rr(`Model`),dr={Background:0,Highlights:1,Clipboard:2,Chart:4,Autofill:5,Selection:6,Headers:100},fr=Dt(()=>Object.keys(dr).sort((e,t)=>dr[e]-dr[t]));function pr(e,t){if(dr[e])throw Error(`Layer ${e} already exists`);dr[e]=t}var mr=class{mutators=[`register`,`unRegister`,`draw`,`startAnimation`,`stopAnimation`];renderers={};model;context=void 0;animationFrameId=null;registeredAnimations=new Set;constructor(e){this.model=e(ur)}register(e){if(e.renderingLayers.length)for(let t of e.renderingLayers)this.renderers[t]||(this.renderers[t]=[]),this.renderers[t].push(e)}unRegister(e){for(let t of Object.keys(this.renderers))this.renderers[t]=this.renderers[t].filter(t=>t!==e)}drawLayer(e,t,n){let r=this.renderers[t];if(r)for(let i of r)e.ctx.save(),i.drawLayer(e,t,n),e.ctx.restore();return`noStateChange`}draw(e,t){if(e||=this.context,!e)throw Error(`Rendering context is not defined`);this.context=e;for(let n of fr())this.model.drawLayer(e,n),this.drawLayer(e,n,t);return`noStateChange`}startAnimation(e){if(this.registeredAnimations.add(e),!this.animationFrameId){let e=t=>{this.animationFrameId=requestAnimationFrame(e),this.draw(void 0,t)};this.animationFrameId=requestAnimationFrame(e)}return`noStateChange`}stopAnimation(e){return this.registeredAnimations.delete(e),this.registeredAnimations.size===0&&this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),`noStateChange`}dispose(){this.animationFrameId&&=(cancelAnimationFrame(this.animationFrameId),null)}},hr=class extends ir{model=this.get(ur);getters=this.model.getters;renderer=this.get(mr);constructor(e){super(e),this.model.on(`command-dispatched`,this,this.handle),this.model.on(`command-finalized`,this,this.finalize),this.renderer.register(this),this.onDispose(()=>{this.model.off(`command-dispatched`,this),this.model.off(`command-finalized`,this),this.renderer.unRegister(this)})}get renderingLayers(){return[]}handle(e){}finalize(){}drawLayer(e,t,n){}};let gr={id:`void-composer`,get editionMode(){return`inactive`},startEdition:()=>{throw Error(`No composer is registered`)},stopEdition:()=>{throw Error(`No composer is registered`)},setCurrentContent:()=>{throw Error(`No composer is registered`)}};var _r=class extends hr{mutators=[`focusComposer`,`focusActiveComposer`];activeComposer=gr;_focusMode=`inactive`;get focusMode(){return this.activeComposer.editionMode===`inactive`?`inactive`:this._focusMode}focusComposer(e,t){if(this.activeComposer=e,this.getters.isReadonly())return`noStateChange`;this._focusMode=t.focusMode||`contentFocus`,this._focusMode!==`inactive`&&this.setComposerContent(t)}focusActiveComposer(e){if(this.getters.isReadonly())return`noStateChange`;if(!this.activeComposer)throw Error(`No composer is registered`);this._focusMode=e.focusMode||`contentFocus`,this._focusMode!==`inactive`&&this.setComposerContent(e)}setComposerContent({content:e,selection:t}){this.activeComposer.editionMode===`inactive`?this.activeComposer.startEdition(e,t):e&&this.activeComposer.setCurrentContent(e,t)}};let vr=/rgba?\(|\s+|\)/gi,yr=/^#([A-F\d]{2}){3,4}$/,br=/^light-dark\(\s*(rgba?\([0-9.,\s]+\)|#[a-f0-9]+)\s*,\s*(rgba?\([0-9.,\s]+\)|#[a-f0-9]+)\s*\)$/i,xr=[`#eb6d00`,`#0074d9`,`#ad8e00`,`#169ed4`,`#b10dc9`,`#00a82d`,`#00a3a3`,`#f012be`,`#3d9970`,`#62A300`,`#ff4136`,`#949494`,`#ff5c9d`];function Sr(e,t=1){let n=t===1?``:Math.round(t*255).toString(16).padStart(2,`0`);return wr(e.toString(16).padStart(6,`0`))+n}function Cr(e){return typeof e==`number`?e:Number.parseInt(wr(e).slice(1,7),16)}function wr(e){let t=e;if(e.startsWith(`light-dark`)){let t=e.match(br);if(!t)throw Error(`Invalid light-dark color: ${e}`);return`light-dark(${wr(t[1])}, ${wr(t[2])})`}if(e.startsWith(`rgb`)?t=Ar(e):(t=e.replace(`#`,``).toUpperCase(),(t.length===3||t.length===4)&&(t=t.split(``).reduce((e,t)=>e+t+t,``)),t=`#${t}`),!yr.test(t))throw Error(`invalid color input: ${e}`);return t}function Tr(e){try{return wr(e),!0}catch{return!1}}function Er(e){try{return Fr(e),!0}catch{return!1}}let Dr=e=>e>=0&&e<=255;function Or(e,t,n,r=1){if(!Dr(e)||!Dr(t)||!Dr(n)||r<0||r>1)throw Error(`Invalid RGBA values ${[e,t,n,r]}`);return{a:r,b:n,g:t,r:e}}function kr(e){let{r:t,g:n,b:r}=Mr(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 Ar(e){let t=e.replace(vr,``).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),`#`+pt(r.map(e=>e.toString(16).padStart(2,`0`))).toUpperCase()}function jr(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 Mr(e){e=wr(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 Nr(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 Pr(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 Fr(e){return jr(Nr(e))}function Ir(e){return Pr(Mr(e))}function Lr(e,t){let n=Mr(t),r=Mr(e),i=n.a+r.a*(1-n.a);return jr({r:Math.round((n.r*n.a+r.r*r.a*(1-n.a))/i),g:Math.round((n.g*n.a+r.g*r.a*(1-n.a))/i),b:Math.round((n.b*n.a+r.b*r.a*(1-n.a))/i),a:i})}function Rr(e){return Mr(typeof e==`number`?Sr(e):e)}function zr(e,t,n=0){if(!(Tr(e)&&Tr(t)))return!1;let r=Mr(e),i=Mr(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 Br(e,t){if(e.startsWith(`light-dark`)){let n=e.match(br);if(!n)throw Error(`Invalid light-dark color: ${e}`);return`light-dark(${Br(n[1],t)}, ${Br(n[2],t)})`}return t===1?wr(e).slice(0,7):jr({...Mr(e),a:t})}function Vr(e,t){let n=Ir(e);return t===1?`#fff`:(n.l=t*(100-n.l)+n.l,Fr(n))}function Hr(e,t){let n=Ir(e);return t===1?`#000`:(n.s=Math.min(100,t*n.s+n.s),n.l-=t*n.l,Fr(n))}function Ur(e){return kr(e)<.6?Vr(e,.9):Hr(e,.75)}let Wr=[`#4EA7F2`,`#EA6175`,`#43C5B1`,`#F4A261`,`#8481DD`,`#FFD86D`],Gr=[`#4EA7F2`,`#3188E6`,`#43C5B1`,`#00A78D`,`#EA6175`,`#CE4257`,`#F4A261`,`#F48935`,`#8481DD`,`#5752D1`,`#FFD86D`,`#FFBC2C`],Kr=[`#4EA7F2`,`#3188E6`,`#056BD9`,`#A76DBC`,`#7F4295`,`#6D2387`,`#EA6175`,`#CE4257`,`#982738`,`#43C5B1`,`#00A78D`,`#0E8270`,`#F4A261`,`#F48935`,`#BE5D10`,`#8481DD`,`#5752D1`,`#3A3580`,`#A4A8B6`,`#7E8290`,`#545B70`,`#FFD86D`,`#FFBC2C`,`#C08A16`],qr=`#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(`.`),Jr=[`#4EA7F2`,`#43C5B1`,`#EA6175`,`#F4A261`,`#8481DD`,`#FFD86D`,`#3188E6`,`#00A78D`,`#CE4257`,`#F48935`,`#5752D1`,`#FFBC2C`],Yr=[`#4EA7F2`,`#A76DBC`,`#EA6175`,`#43C5B1`,`#F4A261`,`#8481DD`,`#A4A8B6`,`#FFD86D`,`#3188E6`,`#7F4295`,`#CE4257`,`#00A78D`,`#F48935`,`#5752D1`,`#7E8290`,`#FFBC2C`,`#056BD9`,`#6D2387`,`#982738`,`#0E8270`,`#BE5D10`,`#3A3580`,`#545B70`,`#C08A16`],Xr=`#4EA7F2.#A76DBC.#EA6175.#43C5B1.#F4A261.#8481DD.#A4A8B6.#FFD86D.#3188E6.#7F4295.#CE4257.#00A78D.#F48935.#5752D1.#7E8290.#FFBC2C.#056BD9.#6D2387.#982738.#0E8270.#BE5D10.#3A3580.#545B70.#C08A16.#155193.#4F1565.#791B29.#105F53.#7D380D.#26235F.#3F4250.#936A12`.split(`.`);function Zr(e,t){return t[e%t.length]}function Qr(e){return e<=6?Wr:e<=12?Gr:e<=24?Kr:qr}function $r(e){return e<=6?Wr:e<=12?Jr:e<=24?Yr:Xr}var ei=class{preferredColors;currentColorIndex=0;palette;constructor(e,t=[]){this.preferredColors=t,this.palette=Qr(e).filter(e=>!t.includes(e))}next(){return this.preferredColors?.[this.currentColorIndex]?this.preferredColors[this.currentColorIndex++]:Zr(this.currentColorIndex++,this.palette)}},ti=class extends ei{constructor(e,t=[]){super(e,t),this.palette=$r(e).filter(e=>!t.includes(e))}},ni=class{availableColors;colors={};constructor(e=12){this.availableColors=new ti(e)}get(e){return this.colors[e]||(this.colors[e]=this.availableColors.next()),this.colors[e]}};let ri={greys:[`#ffffff`,`#808080`,`#000000`],blues:[`#f7fbff`,`#6aaed6`,`#08306b`],reds:[`#fff5f0`,`#fb694a`,`#67000d`],greens:[`#f7fcf5`,`#73c476`,`#00441b`],oranges:[`#fff5eb`,`#fd8c3b`,`#7f2704`],purples:[`#fcfbfd`,`#9e9ac8`,`#3f007d`],viridis:[`#440154`,`#21918c`,`#fde725`],cividis:[`#00224e`,`#7d7c78`,`#fee838`],rainbow:[`#B41DB4`,`#FFFF00`,`#00FFFF`]},ii=Object.keys(ri);function ai(e){if(e.length<2)throw Error(`Color scale must have at least 2 points`);let t=[...e.sort((e,t)=>e.value-t.value)],n=[];for(let e=1;e<t.length;e++){let r=Rr(t[e-1].color).a,i=Rr(t[e].color).a,a=Cr(t[e-1].color),o=Cr(t[e].color);n.push({min:t[e-1].value,max:t[e].value,minColor:a,maxColor:o,minColorAlpha:r,maxColorAlpha:i,colorDiff:oi(t[e-1].value,t[e].value,a,o)})}return e=>{if(e<n[0].min)return Sr(n[0].minColor,n[0].minColorAlpha);for(let t of n)if(e>=t.min&&e<=t.max)return Sr(si(e,t.min,t.minColor,t.colorDiff),t.maxColorAlpha);return Sr(n[n.length-1].maxColor,n[n.length-1].maxColorAlpha)}}function oi(e,t,n,r){let i=t-e,a=(n>>16)%256-(r>>16)%256,o=(n>>8)%256-(r>>8)%256,s=n%256-r%256;return[a/i,o/i,s/i]}function si(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}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 ci=new O(1899,11,30),li=1440*60*1e3,ui=2e3,di=O.now().getFullYear(),fi=O.now().getMonth(),pi=O.fromTimestamp(0).getTime()-ci.getTime(),mi=/^\d{1,2}(\/|-|\s)\d{1,2}((\/|-|\s)\d{1,4})?$/,hi=/^\d{3,4}(\/|-|\s)\d{1,2}(\/|-|\s)\d{1,2}$/,gi=wt.join(``),_i=RegExp(`\/|-|${wt.join(`|`)}`),vi=RegExp(`^(\\d{1,4})[\/${gi}\-](\\d{1,4})([\/${gi}\-](\\d{1,4}))?$`),yi=/((\d+(:\d+)?(:\d+)?\s*(AM|PM))|(\d+:\d+(:\d+)?))$/;function bi(e,t){switch(typeof e){case`number`:return e;case`string`:return xi(e,t)?Ci(e,t)?.value:!e||isNaN(Number(e))?void 0:Number(e);default:return}}function xi(e,t){return Ci(e,t)!==null}let Si=new Map;function Ci(e,t){return Si.has(t)||Si.set(t,new Map),Si.get(t).has(e)||Si.get(t).set(e,wi(e,t)),Si.get(t).get(e)}function wi(e,t){e=e.trim();let n=null,r=e.match(yi);if(r){if(n=Mi(r[0]),n===null)return null;e=e.replace(r[0],``).trim()}let i=null,a=Ti(e,t);if(a){let t=a.dateString.match(_i)[0];if(i=Di(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 Ti(e,t){let n=e.match(vi);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=Ei(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 Ei(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 Di(e,t){let{year:n,month:r,day:i}=e,a=Ai(r),o=ji(i),s=ki(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()-ci.getTime(),f=Oi(e,t,c,l);return{value:Math.round(d/li),format:f,jsDate:u}}function Oi(e,t,n,r){let i=e.year?r?`yyyy`:`yy`:void 0,a=e.month?n?`mm`:`m`:void 0,o=e.day?n?`dd`:`d`:void 0;switch(e.type){case`mdy`:return[a,o,i].filter(C).join(t);case`ymd`:return[i,a,o].filter(C).join(t);case`dmy`:return[o,a,i].filter(C).join(t)}}function ki(e){if(!e)return di;let t=Number(e);switch(e.length){case 1:return ui+t;case 2:return ui+(ui+t>di+10?-100:0)+t;case 3:case 4:return t}return null}function Ai(e){if(!e)return fi;let t=Number(e);return t>=1&&t<=12?t-1:null}function ji(e){if(!e)return 1;let t=Number(e);return t>=0&&t<=31?t:null}function Mi(e){if(e=e.trim(),yi.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 Ni(e){let t=Math.trunc(e),n=O.fromTimestamp(t*li-pi),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 Pi(e){return Math.round(Fi(e))}function Fi(e){return(e.getTime()-ci.getTime())/li}function Ii(e){return new O(e.getFullYear(),e.getMonth()+1,0).getDate()}function Li(e){return Ii(e)===e.getDate()}function Ri(e,t,n){let r=e.getFullYear(),i=e.getMonth(),a=e.getDate(),o=new O(r,i+t,1);return n&&a===Ii(e)||a>Ii(o)?o.setDate(Ii(o)):o.setDate(a),o}function zi(e){let t=Math.trunc(e);return t%4==0&&t%100!=0||t%400==0}function Bi(e,t,n){if(e===t)return 0;if(e>t){let n=t;t=e,e=n}let r=Ni(e),i=Ni(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===(zi(l)?29:28)&&(a=30,c===1&&o===(zi(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+=zi(n)?366:365;n=t/e}else r?zi(l)&&(n=366):(zi(l)&&s<2&&(n=366),zi(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 Vi(e,t){let n=(t.getFullYear()-e.getFullYear())*12+t.getMonth()-e.getMonth();return e.getDate()>t.getDate()?n-1:n}function Hi(e,t){let n=e.getTime(),r=t.getTime();return Math.floor((r-n)/li)}function Ui(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 Wi(e,t){return Bi(e,t,1)<1}function Gi(e,t){return Math.trunc(e)===Math.trunc(t)}function Ki(e,t,n){return t>n?Ki(e,n,t):(e=Math.trunc(e),t=Math.trunc(t),n=Math.trunc(n),e>=t&&e<=n)}function qi(e,t){return Math.trunc(e)<Math.trunc(t)}function Ji(e,t){return Math.trunc(e)<=Math.trunc(t)}function Yi(e,t){return Math.trunc(e)>Math.trunc(t)}function Xi(e,t){return Math.trunc(e)>=Math.trunc(t)}let Zi=Dt(function(e){return e=Ge(e),RegExp(`(?:^-?\\d+(?:${e}?\\d*(?:(E|e)(\\+|-)?\\d+)?)?|^-?${e}\\d+)(?!\\w|!)`)}),Qi=Dt(function(e){let t=Ge(e.decimalSeparator),n=`(?:\\d+(?:${Ge(e.thousandsSeparator||``)}\\d{3,})*(?:${t}\\d*)?)`,r=`(?:${t}\\d+)`,i=`(?:\\s*`+n+`|`+r+`)(?:(e|E)(?:\\+|-)?(?:[0-9]|[0-9][0-9]|[12][0-9]{2}|30[0-7]))?(?:\\s*%)?`,a=`(?:\\s*-)?`,o=`(?:\\s*[\\$€])?`,s=`^(?:(?:`+[a+o+i,a+i+o,o+a+i].join(`)|(?:`)+`))$`;return new RegExp(s,`i`)});function $i(e,t){return e?Qi(t).test(e.trim()):!1}let ea=Dt(function(e){return RegExp(`[\$€${Ge(e.thousandsSeparator||``)}]`,`g`)});function ta(e,t){e=e.replace(ea(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 na(e,t,n){let r=[...e].sort((e,t)=>e-t),i=(r.length+(n?-1:1))*t;if(n||i--,Number.isInteger(i))return r[i];let a=Math.ceil(i),o=Math.floor(i);return r[a]*(i-o)+r[o]*(a-i)}let ra=e=>e,ia=()=>!1,aa=ra,oa=ia;function sa(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 ca(e,t=()=>!0){aa=e,oa=t}function la(){aa===ra&&oa===ia&&(oa=()=>!0)}let k=function(e,...t){return oa()?sa(aa(e),...t):new ua(e,t)};var ua=class extends String{values;constructor(e,t){super(e),this.values=t}valueOf(){let e=super.valueOf();return oa()?sa(aa(e),...this.values):sa(e,...this.values)}toString(){return this.valueOf()}};let A={NotAvailable:`#N/A`,InvalidReference:`#REF`,BadExpression:`#BAD_EXPR`,CircularDependency:`#CYCLE`,UnknownFunction:`#NAME?`,DivisionByZero:`#DIV/0!`,InvalidNumber:`#NUM!`,SpilledBlocked:`#SPILL!`,GenericError:`#ERROR`,NullError:`#NULL!`},da=new Set(Object.values(A));var j=class{message;value;constructor(e=k(`Error`),t=A.GenericError){this.message=e,this.value=t,this.message=e.toString()}},fa=class extends j{constructor(e=k(`Invalid expression`)){super(e,A.BadExpression)}},pa=class extends j{constructor(e=k(`Circular reference`)){super(e,A.CircularDependency)}},ma=class extends j{constructor(e=k(`Invalid reference`)){super(e,A.InvalidReference)}},ha=class extends j{constructor(e=k(`Data not available`)){super(e,A.NotAvailable)}},ga=class extends j{constructor(e=k(`Unknown function`)){super(e,A.UnknownFunction)}},_a=class extends j{errorOriginPosition;constructor(e=k(`Spill range is not empty`),t){super(e,A.SpilledBlocked),this.errorOriginPosition=t}},va=class extends j{constructor(e=k(`Division by zero`)){super(e,A.DivisionByZero)}},ya=class extends j{constructor(e=k(`Number too large`)){super(e,A.InvalidNumber)}};let ba=[`thin`,`medium`,`thick`,`dashed`,`dotted`];function xa(e){return Array.isArray(e)&&Array.isArray(e[0])}let Sa=[`number`,`string`,`boolean`,`undefined`];function Ca(e){if(e!==void 0)return xa(e)?e[0][0]?.format:e.format}function M(e){return typeof e==`string`&&da.has(e)}function wa(e){return{value:A.NotAvailable,message:k(`Did not find value '%s' in [[FUNCTION_NAME]] evaluation.`,P(e))}}let Ta=e=>k(`The function [[FUNCTION_NAME]] expects a number value, but '%s' is a string, and cannot be coerced to a number.`,e),Ea=(e,t,n)=>k(`The function [[FUNCTION_NAME]] expects a number value between %s and %s inclusive, but receives %s.`,e.toString(),t.toString(),n.toString()),Da=(e,t)=>k(`The function [[FUNCTION_NAME]] has an argument with value '%s'. It should be one of: %s.`,t,e.map(e=>`'${e}'`).join(`, `));function N(e,t){let n=Ia(e);switch(typeof n){case`number`:return n;case`boolean`:return+!!n;case`string`:if($i(n,t)||n===``)return ta(n,t);let e=Ci(n,t);if(e)return e.value;throw new j(Ta(n));default:return 0}}function Oa(e,t){try{return N(e,t)}catch{return}}function ka(e,t){return L(e).map(e=>e.map(e=>{if(typeof e.value!=`number`){let n=``;throw typeof e==`object`?n=k(`Function [[FUNCTION_NAME]] expects number values for %s, but got an empty value.`,t):typeof e==`string`?n=k(`Function [[FUNCTION_NAME]] expects number values for %s, but got a string.`,t):typeof e==`boolean`&&(n=k(`Function [[FUNCTION_NAME]] expects number values for %s, but got a boolean.`,t)),new j(n)}return e.value}))}function Aa(e,t){let n=Ia(e);if(n===``)throw new j(Ta(n));return N(n,t)}function ja(e,t){return Math.trunc(N(e,t))}function Ma(e,t){return Math.trunc(Aa(e,t))}function P(e){let t=Ia(e);switch(typeof t){case`string`:return t;case`number`:return t.toString();case`boolean`:return t?`TRUE`:`FALSE`;default:return``}}let Na=Dt(function(e){return e.toLowerCase().normalize(`NFD`).replace(/[\u0300-\u036f]/g,``)}),Pa=e=>k(`The function [[FUNCTION_NAME]] expects a boolean value, but '%s' is a text, and cannot be coerced to a boolean.`,e);function F(e){let t=Ia(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 j(Pa(t))}else return!1;case`number`:return!!t;default:return!1}}function Fa(e){let t=Ia(e);if(t===``)throw new j(Pa(t));return F(t)}function I(e,t){return Ni(N(Ia(e),t))}function Ia(e){if(typeof e==`object`&&e&&`value`in e){if(M(e.value))throw e;return e.value}if(M(e))throw new j(``,e);return e}function La(e,t,n){for(let r of e)if(xa(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 Ra(e,t){La(e,e=>{if(M(e.value))throw e;t(e)},e=>{if(M(e?.value))throw e;t(e)})}function za(e,t,n){La(e,e=>{if(typeof e?.value==`number`&&t(e),M(e?.value))throw e},e=>{t({value:Aa(e,n),format:e?.format})})}function Ba(e,t,n,r,i=`rowFirst`){let a=r;for(let r of e)if(xa(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 Va(e,t,n,r=`rowFirst`){return Ba(e,t,t,n,r)}function Ha(e,t,n,r){return Ba(e,(e,n)=>{let r=n?.value;if(typeof r==`number`)return t(e,r);if(M(r))throw n;return e},(e,n)=>t(e,Aa(n,r)),n)}function Ua(e,t,n,r){return Ba(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,N(i,r));if(M(i))throw n;return t(e,0)}return e},(e,n)=>t(e,N(n,r)),n)}function Wa(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 Ga(e,t){return e.length===0?[]:Wa(e.length,e[0].length,(n,r)=>t(e[n][r]))}function Ka(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 qa(e){return e.length?Wa(e[0].length,e.length,(t,n)=>e[n][t]):[]}function Ja(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(xa(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 Wa(r,i,(t,n)=>{if(t>a-1||n>o-1)return new ha(k(`Array arguments to [[FUNCTION_NAME]] are of different size.`));let r=e(...c(t,n));return xa(r)?r[0][0]:r})}function Ya(e,t,n){for(let r of e)if(xa(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 Xa(e,t){return Ya(e,e=>{let n=e?.value;if(typeof n==`boolean`)return t(n);if(typeof n==`number`)return t(!!n);if(M(n))throw e;return!0},e=>e!==void 0&&e.value!==null?t(Fa(e)):!0)}function Za(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)),$i(r,t)||xi(r,t)?r=N(r,t):(r===`TRUE`||r===`FALSE`)&&(r=F(r)),{operator:n,operand:r}}let Qa=Dt(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 $a(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`&&($i(e,n)||xi(e,n))?N(e,n)===i:e===i;if(r===`<>`||r===`=`){let t;return t=typeof e==typeof i?e===``&&i===``?!0:typeof e==`string`&&typeof i==`string`?Qa(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 eo(e,t,n,r=!1){let i=e.length;if(i%2==1)throw new j(k(`Function [[FUNCTION_NAME]] expects criteria_range and criterion to be in pairs.`));let a=L(e[0]),o=a.length,s=a[0].length,c=[];for(let t=0;t<i-1;t+=2){let i=L(e[t]);if(i.length!==o||i[0].length!==s)throw new j(k(`Function [[FUNCTION_NAME]] expects criteria_range to have the same dimension`));let a=Za(P(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=L(e[t])[r][a].value,s=c[t/2];if(o=$a(i??void 0,s,n),!o)break}o&&t(r,a)}}function to(e,t,n,r,i,a){if(t===void 0||t.value===null)return-1;if(M(t.value))throw t;let o=io(t.value),s=typeof o,c,l,u=0,d=i-1,f,p,m,h,g=r===`desc`?t=>io(a(e,i-t-1)):t=>io(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 no(e,t,n,r,i,a,o=!1){if(t===void 0||t.value===null)return-1;if(M(t.value))throw t;let s=io(t.value),c=o?(e,t)=>io(i(e,r-t-1)):(e,t)=>io(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`||n===`wildcard`)return-1}let u=ro(e,s,n,r,c);return o&&u!==-1?r-u-1:u}function ro(e,t,n,r,i){let a=n=>i(e,n)===t;if(n===`wildcard`&&typeof t==`string`&&(t.includes(`*`)||t.includes(`?`))){let n=Qa(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&&ao(t,r)>=0||ao(t,r)>=0&&ao(r,o)>0)&&(o=r,s=n),r===t}),n===`nextGreater`&&(a=n=>{let r=i(e,n);return(!o&&ao(t,r)<=0||ao(t,r)<=0&&ao(r,o)<0)&&(o=r,s=n),r===t});for(let e=0;e<r;e++)if(a(e))return e;return s}function io(e){return typeof e==`string`?Na(e):e}function ao(e,t){let n=Sa.indexOf(typeof e)-Sa.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 L(e){return e===void 0?[[]]:xa(e)?e:[[e]]}function oo(e,t){return Va(e,(e,n)=>(e.push(t(n)),e),[],`rowFirst`)}function so(e){if(e===void 0)return!1;let{value:t}=e;return!(t===null||t===``)}let co=k(`[[FUNCTION_NAME]] has no valid input data.`);function lo(e){return k(`[[FUNCTION_NAME]] expects the provided values of %(argName)s to be a non-empty matrix.`,{argName:e})}let uo=[{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:`;`}],R=uo[0];function fo(e){let t=new It(e),n=[],r=[];for(n.push(r);!t.isOver();){if(t.current===`;`){r=[],n.push(r),t.shift();continue}let e=xo(t)||po(t)||ho(t)||go(t)||vo(t)||yo(t)||bo(t)||Co(t)||_o(t)||wo(t);if(!e)throw Error(`Unknown token at `+t.remaining());r.push(e)}return n}function po(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 mo=new Set(`$+-/():!^&~{}<>= `);function ho(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 mo.has(e.current)?{type:`CHAR`,value:e.shift()}:null}function go(e){return e.current===`,`?(e.shift(),{type:`THOUSANDS_SEPARATOR`,value:`,`}):null}function _o(e){return e.current===`@`?(e.shift(),{type:`TEXT_PLACEHOLDER`,value:`@`}):null}function vo(e){return e.current===`.`?(e.shift(),{type:`DECIMAL_POINT`,value:`.`}):null}function yo(e){return e.current===`%`?(e.shift(),{type:`PERCENT`,value:`%`}):null}function bo(e){return e.current===`e`?(e.shift(),{type:`SCIENTIFIC`,value:`e`}):null}function xo(e){if(e.current===`0`||e.current===`#`){let t=e.current;return e.shift(),{type:`DIGIT`,value:t}}return null}let So=new Set(`dmqyhsa`);function Co(e){if(!So.has(e.current))return null;let t=e.current,n=``;for(;e.current===t;)n+=e.shift();return{type:`DATE_PART`,value:n}}function wo(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 To={};function Eo(e){let t=To[e];return t===void 0&&(t=Do(e),To[e]=t),t}function Do(e){let t=fo(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=Mo(t[0])||jo(t[0])||No(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=Mo(t[1])||jo(t[1]);if(t[1]?.length&&!r)throw Error(`Invalid second format part of: `+e);let i=Mo(t[2])||jo(t[2]);if(t[2]?.length&&!i)throw Error(`Invalid third format part of: `+e);let a=No(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 Oo(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 ko(e){return e.every(e=>e.type===`DIGIT`||e.type===`DECIMAL_POINT`||e.type===`THOUSANDS_SEPARATOR`||e.type===`PERCENT`||e.type===`SCIENTIFIC`||e.type===`STRING`||e.type===`CHAR`||e.type===`REPEATED_CHAR`)}function Ao(e){return e.every(e=>e.type===`STRING`||e.type===`TEXT_PLACEHOLDER`||e.type===`CHAR`||e.type===`REPEATED_CHAR`)}function jo(e){if(!e||!ko(e))return;let t=[],n,r=t,i=0,a=!1,o=0,s=e.findLastIndex(e=>e.type===`DIGIT`),c=!1,l=0;for(let u=0;u<e.length;u++){let d=e[u];switch(d.type){case`DIGIT`:r===t?r.push(d):l<20&&(r.push(d),l++);break;case`DECIMAL_POINT`:if(r===t)n=[],r=n;else throw Error(`Multiple decimal points in a number format`);break;case`SCIENTIFIC`:a=!0;break;case`REPEATED_CHAR`:case`CHAR`:case`STRING`:r.push(d);break;case`PERCENT`:i++,r.push(d);break;case`THOUSANDS_SEPARATOR`:u-1===s?(o+=1,s++,r.push(d)):e[u+1]?.type===`DIGIT`&&e[u-1]?.type===`DIGIT`?(r===t&&(c=!0),r.push(d)):r.push({type:`CHAR`,value:`,`});break}}return{type:`number`,integerPart:t,decimalPart:n,percentSymbols:i,scientific:a,thousandsSeparator:c,magnitude:o}}function Mo(e){let t=e&&Oo(e)?{type:`date`,tokens:e}:void 0;if(!(!t||!e?.some(e=>e.type===`DATE_PART`))){if(t.tokens.length&&t.tokens.every(e=>e.type===`DATE_PART`&&e.value===`a`))throw Error(`Invalid date format`);return{type:`date`,tokens:Po(t.tokens.map(e=>e.type===`THOUSANDS_SEPARATOR`||e.type===`DECIMAL_POINT`?{type:`CHAR`,value:e.value}:e))}}}function No(e){return e&&Ao(e)?{type:`text`,tokens:e}:void 0}function Po(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 Fo(e){return[Io(e.positive),Io(e.negative),Io(e.zero),Io(e.text)].filter(C).join(`;`)}function Io(e){if(!e)return;let t=``,n=e.type===`number`?Lo(e):e.tokens;for(let e of n)switch(e.type){case`STRING`:t+=`[$${e.value}]`;break;case`CHAR`:t+=Ro(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 Lo(e){let t=[...e.integerPart];return e.decimalPart&&(t.push({type:`DECIMAL_POINT`,value:`.`}),t.push(...e.decimalPart)),e.scientific&&t.push({type:`SCIENTIFIC`,value:`e`}),t}function Ro(e){return!mo.has(e)}let zo=`REPEATED_CHAR_PLACEHOLDER_`,Bo={0:k(`January`),1:k(`February`),2:k(`March`),3:k(`April`),4:k(`May`),5:k(`June`),6:k(`July`),7:k(`August`),8:k(`September`),9:k(`October`),10:k(`November`),11:k(`December`)},Vo={0:k(`Sunday`),1:k(`Monday`),2:k(`Tuesday`),3:k(`Wednesday`),4:k(`Thursday`),5:k(`Friday`),6:k(`Saturday`)};function Ho(e,t,n,r=!1){return r?hs({value:e,format:t},n):z(e,{format:t,locale:n})}function z(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=Eo(t),i=Uo(e,n).format;return!i||i.type!==`text`?e:Wo(e,i,r)}case`number`:t||=os(e);let i=Eo(t),{format:a,isNegativeFormat:o}=Uo(e,i);if(!a)return e.toString();if(a.type===`text`)return Wo(e.toString(),a,r);if(o&&(e=Math.abs(e)),a.type===`date`)return Go(rs(e,a),r);let s=e<0,c=Go(Ko(Math.abs(e),a,n),r);return s?`-`+c:c;case`object`:return``}}function Uo(e,t){let n,r=!1;switch(typeof e){case`number`:e<0&&t.negative?(n=t.negative,r=!0):n=e===0&&t.zero?t.zero:t.positive;break;case`string`:let i=t.text||t.positive;i.type===`text`&&(n=i);break}return{format:n,isNegativeFormat:r}}function Wo(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+=zo+n.value;break}return Go(r,n)}function Go(e,t){let n=e.indexOf(zo);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 Ko(e,t,n){if(!t.integerPart.length&&!t.decimalPart?.length)return``;if(e===1/0)return`∞`+(t.percentSymbols?`%`:``);let r=Math.floor(Math.log10(Math.abs(e)));r===-1/0&&(r=0),t.scientific&&(e/=10**r);let i=t.percentSymbols*2-t.magnitude*3;e*=10**i;let a=0;t.decimalPart!==void 0&&(a=t.decimalPart.filter(e=>e.type===`DIGIT`).length);let{integerDigits:o,decimalDigits:s}=Xo(Math.abs(e),a),c=!!t.decimalPart?.some(e=>e.type===`DIGIT`),l=qo(o,t,t.thousandsSeparator?n.thousandsSeparator:void 0,c);if(t.decimalPart!==void 0&&(l+=n.decimalSeparator+Jo(s||``,t)),t.scientific){let e=Math.abs(r).toString().padStart(2,`0`);l+=`e`+(r>=0?`+`:`-`)+e}return l}function qo(e,t,n,r){let i=t.integerPart;r&&!i.some(e=>e.type===`DIGIT`)&&(i=[...i,{type:`DIGIT`,value:`#`}]),e===`0`&&(e=``);let a=``,o=i.findIndex(e=>e.type===`DIGIT`),s=e.length-1;function c(t,r){if(r===`0`&&(t||=`0`),!t)return;let i=e.length-1-s;a=n&&i>0&&i%3==0?t+n+a:t+a}for(let t=i.length-1;t>=0;t--){let n=i[t];switch(n.type){case`DIGIT`:let r=e[s];if(c(r,n.value),s--,o===t)for(;s>=0;)c(e[s],`0`),s--;break;case`THOUSANDS_SEPARATOR`:break;case`REPEATED_CHAR`:a=zo+n.value+a;break;default:a=n.value+a;break}}return a}function Jo(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+=zo+i.value;break;default:n+=i.value;break}return n}let Yo=[];function Xo(e,t=20){let n=e.toString();if(n.includes(`e`))return es(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}=$o(a,t);a=n,e!==`0`&&(i=(Number(i)+Number(e)).toString())}return{integerDigits:i,decimalDigits:Zo(a||``)}}function Zo(e){let t=e.length-1;for(;t>=0&&e[t]===`0`;)t--;return e.slice(0,t+1)||void 0}let Qo=/^0+/;function $o(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(Qo)?.[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 es(e,t=20){let n=Yo[t];n||(n=new Intl.NumberFormat(`en-US`,{maximumFractionDigits:t,useGrouping:!1}),Yo[t]=n);let[r,i]=n.format(e).split(`.`);return{integerDigits:r,decimalDigits:i}}function ts(e,t){let{integerDigits:n,decimalDigits:r}=Xo(e,20);return r?n+t+r:n}let ns=Dt(function(e){if(!e)return!1;try{return Eo(e).positive.type===`date`}catch{return!1}});function rs(e,t){let n=Ni(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+=is(n,e.value,r);break;case`REPEATED_CHAR`:i+=zo+e.value;break;default:i+=e.value;break}return i}function is(e,t,n){switch(t){case`d`:return e.getDate();case`dd`:return e.getDate().toString().padStart(2,`0`);case`ddd`:return Vo[e.getDay()].slice(0,3);case`dddd`:return Vo[e.getDay()].toString();case`m`:return e.getMonth()+1;case`mm`:return String(e.getMonth()+1).padStart(2,`0`);case`mmm`:return Bo[e.getMonth()].slice(0,3);case`mmmm`:return Bo[e.getMonth()].toString();case`mmmmm`:return Bo[e.getMonth()].slice(0,1);case`qq`:return k(`Q%(quarter)s`,{quarter:e.getQuarter()}).toString();case`qqqq`:return k(`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()-ci.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 as=Dt(function(e){return RegExp(`[0-9]+${Ge(e.decimalSeparator)}[0-9]`)});function os(e){let{integerDigits:t,decimalDigits:n}=Xo(e);if(!n)return`0`;let r=t.replace(`-`,``).length;if(r+2>11)return`0`;let i=11-r-1;return{decimalDigits:n}=Xo(e,Math.min(i,n.length)),n?`0.`+`0`.repeat(n.length):`0`}function ss(e,t){if(xi(e,t))return Ci(e,t).format}function cs(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 ls(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),fs(o,n,a)}function us(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),[ds(o,n,` ${a} `),ds(o,n,`(${a})`),ds(o,n,` - `)].join(`;`)}function ds(e,t,n){let r=`[$${e}]`;return t===`before`?r+`* `+n:n+`* `+r}function fs(e,t,n){let r=`[$${e}]`;return t===`before`?r+n:n+r}function ps(e){let t=Eo(e);return Fo({positive:ms(t.positive),negative:t.negative?ms(t.negative):void 0,zero:t.zero?ms(t.zero):void 0,text:t.text})}function ms(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 hs({value:e,format:t},n){let r=Oa(e,n);if(r===void 0)return``;let i=t;if(Math.abs(r)<1e3){let e=r%1!=0;i=!t&&e?`0.####`:t}else i=gs({value:e,format:t},void 0,n);return z(e,{format:i,locale:n})}function gs(e,t,n){let r=0;try{r=Math.abs(N(e?.value,n))}catch{return``}let i=e?.format;if(t!==void 0)switch(t?.value){case`k`:return _s(i,1,`k`,n);case`m`:return _s(i,2,`m`,n);case`b`:return _s(i,3,`b`,n);default:throw new j(k(`The formatting unit should be 'k', 'm' or 'b'.`))}return r<1e5?_s(i,0,``,n):r<1e8?_s(i,1,`k`,n):r<1e11?_s(i,2,`m`,n):_s(i,3,`b`,n)}function _s(e,t,n,r){let i=Eo(e||`#,##0`);return Fo({positive:vs(i.positive,t,n),negative:i.negative?vs(i.negative,t,n):void 0,zero:i.zero?vs(i.zero,t,n):void 0,text:i.text})}function vs(e,t,n){if(e.type!==`number`||e.scientific)return e;let r=ms(e),i={type:`STRING`,value:n},a=[...r.integerPart],o=a.findLastIndex(e=>e.type===`DIGIT`);if(o===-1)return e;for(;a[o+1]?.type===`THOUSANDS_SEPARATOR`;)a=Ot(a,[o+1]);let s=a[o+1];a=s?.type===`STRING`&&[`m`,`k`,`b`].includes(s.value)?At(a,i,o+1):kt(a,[i],o+1),t>0&&(a=kt(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 ys(e,t){let n=Eo(e);return Fo(Eo(Fo({positive:bs(n.positive,t),negative:n.negative?bs(n.negative,t):void 0,zero:n.zero?bs(n.zero,t):void 0,text:n.text})))}function bs(e,t){return e.type===`number`?t>0?Ss(e,t):xs(e,Math.abs(t)):e}function xs(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=Ot(n,r),n.some(e=>e.type===`DIGIT`)?{...e,decimalPart:n}:{...e,decimalPart:void 0,integerPart:[...e.integerPart,...n]}}function Ss(e,t){let n=e.integerPart,r=e.decimalPart;if(!r){let e=n.findLastIndex(e=>e.type===`DIGIT`);r=n.slice(e+1),n=n.slice(0,e+1)}let i=S(0,t).map(()=>({type:`DIGIT`,value:`0`})),a=r.findLastIndex(e=>e.type===`DIGIT`);return r=a===-1?[...i,...r]:kt(r,i,a+1),{...e,decimalPart:r,integerPart:n}}function Cs(e){let t=Eo(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 ws(e){if(!e)return!1;try{return Eo(e).positive.type===`text`}catch{return!1}}function Ts(e,t){if(!t)return!1;try{let{format:n}=Uo(e,Eo(t));if(n?.type===`text`||n?.type===`date`)return n.tokens.some(e=>e.type===`REPEATED_CHAR`);if(n?.type===`number`)return n.integerPart.some(e=>e.type===`REPEATED_CHAR`)||(n.decimalPart?n.decimalPart.some(e=>e.type===`REPEATED_CHAR`):!1)}catch{}return!1}function Es(e){try{return z(0,{format:e,locale:R}),!0}catch{return!1}}function Ds(e){return fo(e).length}var B=class{content={};add(e,t){if(e in this.content)throw Error(`${e} is already present in this registry!`);return this.replace(e,t)}replace(e,t){return this.content[e]=t,this}get(e){let t=this.content[e];if(!t&&!(e in this.content))throw Error(`Cannot find ${e} in this registry!`);return t}contains(e){return e in this.content}getAll(){return Object.values(this.content)}getKeys(){return Object.keys(this.content)}remove(e){delete this.content[e]}};function Os(e){return`sheetId`in e}function ks(e){return`dimension`in e&&`sheetId`in e&&`elements`in e}function As(e){return`target`in e&&`sheetId`in e}function js(e){return`ranges`in e}function Ms(e){return`col`in e&&`row`in e&&`sheetId`in e}function Ns(e){return`sheetId`in e&&`zone`in e}let Ps=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`]),Fs=new Set([`EVALUATE_CELLS`,`EVALUATE_CHARTS`,`UPDATE_CELL`,`UNHIDE_COLUMNS_ROWS`,`HIDE_COLUMNS_ROWS`,`GROUP_HEADERS`,`SET_FORMATTING`,`CLEAR_FORMATTING`,`UNGROUP_HEADERS`,`FOLD_ALL_HEADER_GROUPS`,`FOLD_HEADER_GROUP`,`FOLD_HEADER_GROUPS_IN_ZONE`,`UNFOLD_ALL_HEADER_GROUPS`,`UNFOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUPS_IN_ZONE`,`UPDATE_TABLE`,`UPDATE_FILTER`,`UNDO`,`REDO`]),Is=new Set([`MOVE_RANGES`]),Ls=new Set([`EVALUATE_CELLS`,`ADD_CONDITIONAL_FORMAT`,`REMOVE_CONDITIONAL_FORMAT`,`CHANGE_CONDITIONAL_FORMAT_PRIORITY`]),Rs=new Set([`AUTOFILL_CELL`,`SET_BORDER`,`SET_ZONE_BORDERS`,`SET_BORDERS_ON_TARGET`]),zs=new Set([`UNHIDE_COLUMNS_ROWS`,`HIDE_COLUMNS_ROWS`,`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_ALL_HEADER_GROUPS`,`FOLD_HEADER_GROUP`,`FOLD_HEADER_GROUPS_IN_ZONE`,`UNFOLD_ALL_HEADER_GROUPS`,`UNFOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUPS_IN_ZONE`,`UPDATE_TABLE`,`UPDATE_FILTER`]),Bs=new Set([`START`,`ACTIVATE_SHEET`,`COPY`,`RESIZE_SHEETVIEW`,`SET_VIEWPORT_OFFSET`,`SET_ZOOM`,`EVALUATE_CELLS`,`EVALUATE_CHARTS`,`SET_FORMULA_VISIBILITY`,`UPDATE_FILTER`,`UPDATE_CHART`,`UPDATE_CAROUSEL_ACTIVE_ITEM`,`UPDATE_PIVOT`]),Vs=new Set(`UPDATE_CELL.UPDATE_CELL_POSITION.CLEAR_CELL.CLEAR_CELLS.DELETE_CONTENT.ADD_COLUMNS_ROWS.REMOVE_COLUMNS_ROWS.RESIZE_COLUMNS_ROWS.HIDE_COLUMNS_ROWS.UNHIDE_COLUMNS_ROWS.SET_GRID_LINES_VISIBILITY.UNFREEZE_COLUMNS.UNFREEZE_ROWS.FREEZE_COLUMNS.FREEZE_ROWS.UNFREEZE_COLUMNS_ROWS.ADD_MERGE.REMOVE_MERGE.CREATE_SHEET.DELETE_SHEET.DUPLICATE_SHEET.MOVE_SHEET.RENAME_SHEET.COLOR_SHEET.HIDE_SHEET.SHOW_SHEET.MOVE_RANGES.ADD_CONDITIONAL_FORMAT.REMOVE_CONDITIONAL_FORMAT.CHANGE_CONDITIONAL_FORMAT_PRIORITY.CREATE_FIGURE.DELETE_FIGURE.UPDATE_FIGURE.CREATE_CAROUSEL.UPDATE_CAROUSEL.SET_FORMATTING.CLEAR_FORMATTING.SET_BORDER.SET_ZONE_BORDERS.SET_BORDERS_ON_TARGET.CREATE_CHART.UPDATE_CHART.DELETE_CHART.CREATE_TABLE.REMOVE_TABLE.UPDATE_TABLE.CREATE_TABLE_STYLE.REMOVE_TABLE_STYLE.CREATE_IMAGE.GROUP_HEADERS.UNGROUP_HEADERS.UNFOLD_HEADER_GROUP.FOLD_HEADER_GROUP.FOLD_ALL_HEADER_GROUPS.UNFOLD_ALL_HEADER_GROUPS.UNFOLD_HEADER_GROUPS_IN_ZONE.FOLD_HEADER_GROUPS_IN_ZONE.ADD_DATA_VALIDATION_RULE.REMOVE_DATA_VALIDATION_RULE.UPDATE_LOCALE.ADD_PIVOT.UPDATE_PIVOT.INSERT_PIVOT.RENAME_PIVOT.REMOVE_PIVOT.DUPLICATE_PIVOT`.split(`.`));function Hs(e){return Vs.has(e.type)}function Us(e){return Bs.has(e.type)}var Ws=class{reasons;constructor(e=[]){Array.isArray(e)||(e=[e]),e=[...new Set(e)],this.reasons=e.filter(e=>e!==`Success`)}static get Success(){return Gs}get isSuccessful(){return this.reasons.length===0}isCancelledBecause(e){return this.reasons.includes(e)}};let Gs=new Ws,Ks=function(e){return e.Success=`Success`,e.CancelledForUnknownReason=`CancelledForUnknownReason`,e.WillRemoveExistingMerge=`WillRemoveExistingMerge`,e.CannotMoveTableHeader=`CannotMoveTableHeader`,e.MergeIsDestructive=`MergeIsDestructive`,e.CellIsMerged=`CellIsMerged`,e.InvalidTarget=`InvalidTarget`,e.EmptyUndoStack=`EmptyUndoStack`,e.EmptyRedoStack=`EmptyRedoStack`,e.NotEnoughElements=`NotEnoughElements`,e.NotEnoughSheets=`NotEnoughSheets`,e.MissingSheetName=`MissingSheetName`,e.UnchangedSheetName=`UnchangedSheetName`,e.DuplicatedSheetName=`DuplicatedSheetName`,e.DuplicatedSheetId=`DuplicatedSheetId`,e.ForbiddenCharactersInSheetName=`ForbiddenCharactersInSheetName`,e.WrongSheetMove=`WrongSheetMove`,e.WrongSheetPosition=`WrongSheetPosition`,e.InvalidAnchorZone=`InvalidAnchorZone`,e.SelectionOutOfBound=`SelectionOutOfBound`,e.TargetOutOfSheet=`TargetOutOfSheet`,e.WrongCutSelection=`WrongCutSelection`,e.WrongPasteSelection=`WrongPasteSelection`,e.WrongPasteOption=`WrongPasteOption`,e.WrongFigurePasteOption=`WrongFigurePasteOption`,e.EmptyClipboard=`EmptyClipboard`,e.EmptyRange=`EmptyRange`,e.InvalidRange=`InvalidRange`,e.InvalidZones=`InvalidZones`,e.InvalidSheetId=`InvalidSheetId`,e.InvalidCellId=`InvalidCellId`,e.InvalidFigureId=`InvalidFigureId`,e.InputAlreadyFocused=`InputAlreadyFocused`,e.MaximumRangesReached=`MaximumRangesReached`,e.MinimumRangesReached=`MinimumRangesReached`,e.InvalidChartDefinition=`InvalidChartDefinition`,e.InvalidDataSet=`InvalidDataSet`,e.InvalidLabelRange=`InvalidLabelRange`,e.InvalidScorecardKeyValue=`InvalidScorecardKeyValue`,e.InvalidScorecardBaseline=`InvalidScorecardBaseline`,e.InvalidGaugeDataRange=`InvalidGaugeDataRange`,e.EmptyGaugeRangeMin=`EmptyGaugeRangeMin`,e.GaugeRangeMinNaN=`GaugeRangeMinNaN`,e.EmptyGaugeRangeMax=`EmptyGaugeRangeMax`,e.GaugeRangeMaxNaN=`GaugeRangeMaxNaN`,e.GaugeLowerInflectionPointNaN=`GaugeLowerInflectionPointNaN`,e.GaugeUpperInflectionPointNaN=`GaugeUpperInflectionPointNaN`,e.InvalidAutofillSelection=`InvalidAutofillSelection`,e.MinBiggerThanMax=`MinBiggerThanMax`,e.LowerBiggerThanUpper=`LowerBiggerThanUpper`,e.MidBiggerThanMax=`MidBiggerThanMax`,e.MinBiggerThanMid=`MinBiggerThanMid`,e.FirstArgMissing=`FirstArgMissing`,e.SecondArgMissing=`SecondArgMissing`,e.MinNaN=`MinNaN`,e.MidNaN=`MidNaN`,e.MaxNaN=`MaxNaN`,e.ValueUpperInflectionNaN=`ValueUpperInflectionNaN`,e.ValueLowerInflectionNaN=`ValueLowerInflectionNaN`,e.MinInvalidFormula=`MinInvalidFormula`,e.MidInvalidFormula=`MidInvalidFormula`,e.MaxInvalidFormula=`MaxInvalidFormula`,e.ValueUpperInvalidFormula=`ValueUpperInvalidFormula`,e.ValueLowerInvalidFormula=`ValueLowerInvalidFormula`,e.InvalidSortAnchor=`InvalidSortAnchor`,e.InvalidSortZone=`InvalidSortZone`,e.SortZoneWithArrayFormulas=`SortZoneWithArrayFormulas`,e.WaitingSessionConfirmation=`WaitingSessionConfirmation`,e.MergeOverlap=`MergeOverlap`,e.TooManyHiddenElements=`TooManyHiddenElements`,e.Readonly=`Readonly`,e.InvalidViewportSize=`InvalidViewportSize`,e.InvalidScrollingDirection=`InvalidScrollingDirection`,e.ViewportScrollLimitsReached=`ViewportScrollLimitsReached`,e.FigureDoesNotExist=`FigureDoesNotExist`,e.InvalidConditionalFormatId=`InvalidConditionalFormatId`,e.InvalidConditionalFormatType=`InvalidConditionalFormatType`,e.InvalidCellPopover=`InvalidCellPopover`,e.EmptyTarget=`EmptyTarget`,e.InvalidFreezeQuantity=`InvalidFreezeQuantity`,e.FrozenPaneOverlap=`FrozenPaneOverlap`,e.ValuesNotChanged=`ValuesNotChanged`,e.InvalidFilterZone=`InvalidFilterZone`,e.TableNotFound=`TableNotFound`,e.TableOverlap=`TableOverlap`,e.InvalidTableConfig=`InvalidTableConfig`,e.InvalidTableStyle=`InvalidTableStyle`,e.FilterNotFound=`FilterNotFound`,e.MergeInTable=`MergeInTable`,e.NonContinuousTargets=`NonContinuousTargets`,e.DuplicatedFigureId=`DuplicatedFigureId`,e.InvalidSelectionStep=`InvalidSelectionStep`,e.DuplicatedChartId=`DuplicatedChartId`,e.ChartDoesNotExist=`ChartDoesNotExist`,e.InvalidHeaderIndex=`InvalidHeaderIndex`,e.InvalidQuantity=`InvalidQuantity`,e.MoreThanOneColumnSelected=`MoreThanOneColumnSelected`,e.EmptySplitSeparator=`EmptySplitSeparator`,e.SplitWillOverwriteContent=`SplitWillOverwriteContent`,e.NoSplitSeparatorInSelection=`NoSplitSeparatorInSelection`,e.NoActiveSheet=`NoActiveSheet`,e.InvalidLocale=`InvalidLocale`,e.MoreThanOneRangeSelected=`MoreThanOneRangeSelected`,e.NoColumnsProvided=`NoColumnsProvided`,e.ColumnsNotIncludedInZone=`ColumnsNotIncludedInZone`,e.DuplicatesColumnsSelected=`DuplicatesColumnsSelected`,e.InvalidHeaderGroupStartEnd=`InvalidHeaderGroupStartEnd`,e.HeaderGroupAlreadyExists=`HeaderGroupAlreadyExists`,e.UnknownHeaderGroup=`UnknownHeaderGroup`,e.UnknownDataValidationRule=`UnknownDataValidationRule`,e.UnknownDataValidationCriterionType=`UnknownDataValidationCriterionType`,e.InvalidDataValidationCriterionValue=`InvalidDataValidationCriterionValue`,e.InvalidNumberOfCriterionValues=`InvalidNumberOfCriterionValues`,e.InvalidCopyPasteSelection=`InvalidCopyPasteSelection`,e.NoChanges=`NoChanges`,e.InvalidInputId=`InvalidInputId`,e.SheetIsHidden=`SheetIsHidden`,e.InvalidTableResize=`InvalidTableResize`,e.PivotIdNotFound=`PivotIdNotFound`,e.PivotIdTaken=`PivotIdTaken`,e.PivotInError=`PivotInError`,e.EmptyName=`EmptyName`,e.ValueCellIsInvalidFormula=`ValueCellIsInvalidFormula`,e.InvalidDefinition=`InvalidDefinition`,e.InvalidColor=`InvalidColor`,e.InvalidPivotDataSet=`InvalidPivotDataSet`,e.InvalidPivotCustomField=`InvalidPivotCustomField`,e.MissingFigureArguments=`MissingFigureArguments`,e.InvalidCarouselItem=`InvalidCarouselItem`,e}({});function qs(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}let Js=new B;function Ys(e,t){return e=qs(e),{url:e,label:t||e,isExternal:!0,isUrlEditable:!0}}Js.add(`sheet_URL`,{match:e=>st(e),createLink:(e,t)=>({label:t,url:e,isExternal:!1,isUrlEditable:!1}),urlRepresentation(e,t){let n=lt(e);return t.tryGetSheetName(n)||k(`Invalid sheet`)},open(e,t){let n=lt(e);t.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:t.model.getters.getActiveSheetId(),sheetIdTo:n}).isCancelledBecause(`SheetIsHidden`)&&t.notifyUser({type:`warning`,sticky:!1,text:k(`Cannot open the link because the linked sheet is hidden.`)})},sequence:0});let Xs={createLink:Ys,match:e=>rt(e),open:e=>window.open(e,`_blank`),urlRepresentation:e=>e,sequence:0};function Zs(e){return Js.getAll().sort((e,t)=>e.sequence-t.sequence).find(t=>t.match(e))||Xs}function Qs(e,t){return Zs(e.url).urlRepresentation(e.url,t)}function $s(e,t,n){Zs(e.url).open(e.url,t,n)}function ec(e){if(typeof e==`string`){if(nt(e)){let{label:t,url:n}=at(e);return Zs(n).createLink(n,t)}else if(rt(e))return Ys(e)}}function tc(e,t,n){return rc({value:ws(t.format)&&e.parsedValue!==null?e.content:e.parsedValue,format:t.format,origin:n},t.locale)}function nc(e,t){if(e.startsWith(`=`))throw Error(`Cannot parse "${e}" because it's not a literal value. It's a formula`);if(e.startsWith(`'`))return e.slice(1);if(e===``)return null;if(e.includes(`
|
|
10
|
-
`))return e;if($i(e,R))return ta(e,R);let n=Ci(e,t);return n?n.value:$e(e)?e.toUpperCase()===`TRUE`:e}function rc(e,t=R,n,r){let i=ec(e.value);if(!i)return dc(ic(e,t,n),e.origin??r);let a=nc(i.label,t);return dc({...ic({value:a,format:e.format||(typeof a==`number`?ss(i.label,t)||cs(i.label):void 0)},t,n),link:i},e.origin??r)}function ic(e,t,n){let{value:r,format:i,message:a,errorOriginPosition:o}=e;i=n?.format||i;let s=z(r,{format:i,locale:t});return M(r)?uc(r,a,o):r===null?sc(i):ws(i)?ac(P(r),i,s):typeof r==`number`?ns(i||``)?cc(r,i,s):oc(r,i,s):typeof r==`boolean`?lc(r,i,s):ac(r,i,s)}function ac(e,t,n){return{value:e,format:t,formattedValue:n,type:`text`,isAutoSummable:!0,defaultAlign:`left`}}function oc(e,t,n){return{value:e||0,format:t,formattedValue:n,type:`number`,isAutoSummable:!0,defaultAlign:`right`}}let sc=Dt(function(e){return{value:null,format:e,formattedValue:``,type:`empty`,isAutoSummable:!0,defaultAlign:`left`}});function cc(e,t,n){return{value:e,format:t,formattedValue:n,type:`number`,isAutoSummable:!1,defaultAlign:`right`}}function lc(e,t,n){return{value:e,format:t,formattedValue:n,type:`boolean`,isAutoSummable:!1,defaultAlign:`center`}}function uc(e,t,n){return{value:e,formattedValue:e,message:t,type:`error`,isAutoSummable:!1,defaultAlign:`center`,errorOriginPosition:n}}function dc(e,t){return e.value===null||`origin`in e||(e.origin=t),e}function fc(e){let t=O.now();switch(e){case`today`:return Math.floor(Fi(t));case`yesterday`:return t.setDate(t.getDate()-1),Math.floor(Fi(t));case`tomorrow`:return t.setDate(t.getDate()+1),Math.floor(Fi(t));case`lastWeek`:return t.setDate(t.getDate()-6),Math.floor(Fi(t));case`lastMonth`:{let e=t.getMonth()===0?11:t.getMonth()-1,n=new O(t.getFullYear(),e,1);return t.getDate()>Ii(n)?t.setDate(1):(t.setDate(t.getDate()+1),t.setMonth(t.getMonth()-1)),Math.floor(Fi(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(Fi(t))}}function pc(e,t){return`dateValue`in e&&e.dateValue!==`exactDate`?[fc(e.dateValue)]:e.values.map(e=>bi(e,t))}function mc(e,t){return e.map(e=>{if(e.startsWith(`=`))return e;let n=nc(e,t);return typeof n==`number`?z(n,{format:t.dateFormat,locale:t}):``})}let hc=new WeakMap,gc=new WeakMap;function _c(e,t){hc.has(t)||(hc.set(t,new Map),gc.set(t,0));let n=hc.get(t),r=bc(e);if(n.has(r)){let i=n.get(r);return t[i]=e,i}let i=gc.get(t)+1;return n.set(r,i),gc.set(t,i),t[i]=e,i}function vc(e){let t={};for(let n in e){let r=Qt(e[n].map(E));for(let e of r)t[hn(e)]=Number(n)}return t}function*yc(e,t){for(let n in t){let r=un(n),i=t[n];for(let t=r.top;t<=r.bottom;t++)for(let n=r.left;n<=r.right;n++)yield[{sheetId:e,col:n,row:t},i]}}function bc(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+=bc(e[r]);return n+`]`}let t=Object.keys(e).sort(),n=`{`;for(let r of t)e[r]!==void 0&&(n+=`"${r}":${bc(e[r])},`);return n+=`}`,n}function xc(e){return 20+120*Math.exp(-.035*(e-1))}let Sc=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,`i`),Cc=new RegExp(/^\$?([A-Z]{1,3})\$?([0-9]{1,7})$/,`i`),wc=new RegExp(/^\$?([A-Z]{1,3})+$/,`i`),Tc=new RegExp(/^\$?([0-9]{1,7})+$/,`i`),Ec=new RegExp(/^\s*('.+'!|[^']+!)?\$?([A-Z]{1,3})$/,`i`),Dc=new RegExp(/^\s*('.+'!|[^']+!)?\$?([0-9]{1,7})$/,`i`),Oc=RegExp(`^\\s*('.+'!|[^']+!)?(`+[Sc.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 kc(e){return Ec.test(e)}function Ac(e){return Dc.test(e)}function jc(e){return wc.test(e)}function Mc(e){return Tc.test(e)}function Nc(e){return Cc.test(e)}function Pc(e){if(!e.includes(`!`))return{xc:e};let t=e.split(`!`),n=t.pop();return{sheetName:qe(t.join(`!`))||void 0,xc:n}}function Fc(e,t){return e===void 0?t:`${Ye(e)}!${t}`}function Ic(e){if(e.type!==`REFERENCE`)return e;let{xc:t,sheetName:n}=Pc(e.value),[r,i]=t.split(`:`),a=Lc(r),o=i?`:${Lc(i)}`:``;return{...e,value:Fc(n,a+o)}}function Lc(e){switch(Bc(e)){case`none`:e=Rc(e,`colrow`);break;case`colrow`:e=Rc(e,`row`);break;case`row`:e=Rc(e,`col`);break;case`col`:e=Rc(e,`none`);break}return e}function Rc(e,t){let n;({sheetName:n,xc:e}=Pc(e)),n=n?Ye(n)+`!`:``,e=e.replace(/\$/g,``);let r=e.indexOf(`:`);return r>=0?`${n}${zc(e.slice(0,r),t)}:${zc(e.slice(r+1),t)}`:n+zc(e,t)}function zc(e,t){let n=e.search(/[0-9]/),r=n!==0,i=n>=0;switch(t){case`col`:return r?`$`+e:e;case`row`:return i?e.slice(0,n)+`$`+e.slice(n):e;case`colrow`:return!i||!r?`$`+e:`$`+e.slice(0,n)+`$`+e.slice(n);case`none`:return e}}function Bc(e){return Uc(e)?`colrow`:Vc(e)?`col`:Hc(e)?`row`:`none`}function Vc(e){return e.startsWith(`$`)}function Hc(e){return e.includes(`$`,1)}function Uc(e){return e.startsWith(`$`)&&e.length>1&&e.slice(1).includes(`$`)}function Wc(e,t){let n=e.zone,r=Wn(n,t(e.sheetId)),i=e.parts;return e.parts.length===1&&Vn(r)>1?i=[e.parts[0],e.parts[0]]:e.parts.length===2&&Vn(r)===1&&(i=[e.parts[0]]),{unboundedZone:n,zone:r,parts:i,prefixSheet:e.prefixSheet,invalidSheetName:e.invalidSheetName,sheetId:e.sheetId}}function Gc(e,t){let n=e.xc,{xc:r,sheetName:i}=Pc(n),a=ln(r);return Wc({zone:a,parts:$c(r,a),sheetId:e.sheetId,prefixSheet:!!i,invalidSheetName:e.invalidSheetName},t)}function Kc(e){let t={left:-1,top:-1,right:-1,bottom:-1};return{sheetId:``,zone:t,unboundedZone:t,parts:[],invalidXc:e,prefixSheet:!1}}function qc(e){return Bn(e.unboundedZone)}function Jc(e){return zn(e.unboundedZone)}function Yc(e,t,n,r={useBoundedReference:!1,useFixedReference:!1}){if(e.invalidXc)return e.invalidXc;if(e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0||e.zone.left<0||e.zone.top<0)return A.InvalidReference;let i=e.sheetId!==t||e.invalidSheetName||e.prefixSheet,a=``;if(i&&(a=e.invalidSheetName?Ye(e.invalidSheetName):Ye(n(e.sheetId))),i&&!a)return A.InvalidReference;let o=ul(e,0,r);return e.parts&&e.parts.length===2&&(e.zone.top!==e.zone.bottom||e.zone.left!==e.zone.right||e.parts[0].rowFixed||e.parts[0].colFixed||e.parts[1].rowFixed||e.parts[1].colFixed)&&(o+=`:`,o+=ul(e,1,r)),`${i?a+`!`:``}${o}`}function Xc(e,t,n){let r=n.sheetId===e?t:n.sheetId;return{...n,sheetId:r}}function Zc(e,t,n){if(!n)return;let r=e.getRangeFromSheetXC(t,n);return r.invalidSheetName||r.invalidXc?void 0:r}function Qc(e){let t=[];for(let n of e)for(let e of jn(n.zone))t.push({...e,sheetId:n.sheetId});return t}function $c(e,t){let n=e.split(`:`).map(e=>{let t=Ac(e);return{colFixed:t?!1:e.startsWith(`$`),rowFixed:t?e.startsWith(`$`):e.includes(`$`,1)}}),r=t.bottom===void 0,i=t.right===void 0;return r&&(n[0].rowFixed=n[0].rowFixed||n[1].rowFixed,n[1].rowFixed=n[0].rowFixed||n[1].rowFixed),i&&(n[0].colFixed=n[0].colFixed||n[1].colFixed,n[1].colFixed=n[0].colFixed||n[1].colFixed),n}function el(e){let t={left:e.col,top:e.row,right:e.col,bottom:e.row};return{sheetId:e.sheetId,zone:t}}function tl(e){if(mn(e.zone))return e;let t={...e.unboundedZone},n={...e.zone},r=e.parts;if(t.right!==void 0&&t.right<t.left){let e=t.right;t.right=t.left,t.left=e,n.right=n.left,n.left=e,r=[{colFixed:r[1]?.colFixed||!1,rowFixed:r[0]?.rowFixed||!1},{colFixed:r[0]?.colFixed||!1,rowFixed:r[1]?.rowFixed||!1}]}if(t.bottom!==void 0&&t.bottom<t.top){let e=t.bottom;t.bottom=t.top,t.top=e,n.bottom=n.top,n.top=e,r=[{colFixed:r[0]?.colFixed||!1,rowFixed:r[1]?.rowFixed||!1},{colFixed:r[1]?.colFixed||!1,rowFixed:r[0]?.rowFixed||!1}]}return{unboundedZone:t,zone:n,parts:r,invalidXc:e.invalidXc,prefixSheet:e.prefixSheet,invalidSheetName:e.invalidSheetName,sheetId:e.sheetId}}function nl(e){return rl.get(e.type)?.(e)}let rl=new class extends B{add(e,t){return super.add(e,t),this}get(e){return this.content[e]}};rl.add(`REMOVE_COLUMNS_ROWS`,e=>({applyChange:il(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add(`ADD_COLUMNS_ROWS`,e=>({applyChange:al(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add(`DELETE_SHEET`,e=>({applyChange:ol(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add(`RENAME_SHEET`,e=>({applyChange:sl(e),sheetId:e.sheetId,sheetName:{old:e.oldName,current:e.newName}})).add(`MOVE_RANGES`,e=>({applyChange:cl(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}}));function il(e){let t=e.dimension===`COL`?`left`:`top`,n=e.dimension===`COL`?`right`:`bottom`,r=e.dimension===`COL`?`columns`:`rows`,i=[...e.elements];i.sort((e,t)=>t-e);let a=Ze(i);return i=>{if(i.sheetId!==e.sheetId)return{changeType:`NONE`,range:i};let o=i,s=`NONE`;for(let e of a){let a=Ft(e),c=Pt(e);if(i.zone[t]<=a&&a<=i.zone[n]){let e=Math.min(i.zone[n],c)-a+1;s=`RESIZE`,o=ll(o,r,s,-e)}else if(i.zone[t]>=a&&i.zone[n]<=c)s=`REMOVE`,o=Kc(A.InvalidReference);else if(i.zone[t]<=c&&i.zone[n]>=c){let e=c-i.zone[t]+1;s=`RESIZE`,o=ll(o,r,s,-e),o=ll(o,r,`MOVE`,-(i.zone[t]-a))}else a<i.zone[t]&&(s=`MOVE`,o=ll(o,r,s,-(c-a+1)))}return{changeType:s,range:o}}}function al(e){let t=e.dimension===`COL`?`left`:`top`,n=e.dimension===`COL`?`right`:`bottom`,r=e.dimension===`COL`?`columns`:`rows`;return i=>{if(i.sheetId!==e.sheetId)return{changeType:`NONE`,range:i};if(e.position===`after`){if(i.zone[t]<=e.base&&e.base<i.zone[n])return{changeType:`RESIZE`,range:ll(i,r,`RESIZE`,e.quantity)};if(e.base<i.zone[t])return{changeType:`MOVE`,range:ll(i,r,`MOVE`,e.quantity)}}else{if(i.zone[t]<e.base&&e.base<=i.zone[n])return{changeType:`RESIZE`,range:ll(i,r,`RESIZE`,e.quantity)};if(e.base<=i.zone[t])return{changeType:`MOVE`,range:ll(i,r,`MOVE`,e.quantity)}}return{changeType:`NONE`,range:i}}}function ol(e){return t=>{if(t.sheetId!==e.sheetId&&t.invalidSheetName!==e.sheetName)return{changeType:`NONE`,range:t};let n=e.sheetName;return t={...Kc(A.InvalidReference),invalidSheetName:n},{changeType:`REMOVE`,range:t}}}function sl(e){return t=>{if(t.sheetId===e.sheetId)return{changeType:`CHANGE`,range:t};if(e.newName&&t.invalidSheetName===e.newName){let n=e.sheetId;return{changeType:`CHANGE`,range:{...t,sheetId:n,invalidSheetName:void 0}}}if(e.oldName&&t.invalidSheetName===e.oldName){let n=e.sheetId;return{changeType:`CHANGE`,range:{...t,sheetId:n,invalidSheetName:void 0}}}return{changeType:`NONE`,range:t}}}function cl(e){let t=e.target[0];return n=>{if(n.sheetId!==e.sheetId||!Dn(n.zone,t))return{changeType:`NONE`,range:n};let r=e.targetSheetId,i=ll(n,`both`,`MOVE`,[e.col-t.left,e.row-t.top]),a=e.sheetId===r?i.prefixSheet:!0;return{changeType:`MOVE`,range:{...i,sheetId:r,prefixSheet:a}}}}function ll(e,t,n,r){return{...e,unboundedZone:Pn(e.unboundedZone,t,n,r),zone:Pn(e.zone,t,n,r)}}function ul(e,t,n={useBoundedReference:!1,useFixedReference:!1}){let r=e.parts[t]?.colFixed||n.useFixedReference?`$`:``,i=Ht(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=Bn(e.unboundedZone)&&!n.useBoundedReference?t===0&&e.unboundedZone.hasHeader?r+i+a+o:r+i:zn(e.unboundedZone)&&!n.useBoundedReference?t===0&&e.unboundedZone.hasHeader?r+i+a+o:a+o:r+i+a+o,s}function dl(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 fl(e,t,n){let r=[];return t.forEach(t=>{let i=dl(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 pl(e){let t=[];for(let n=0;n<e;n++)t.push({cells:{}});return t}function ml(e,t,n){return n.map(n=>n>=e?n+t:n)}function hl(e,t){return e=[...e].sort((e,t)=>t-e),t.map(t=>{for(let n of e)if(t>n)t--;else if(t===n)return;return t}).filter(C)}function gl(e,t=`Sheet`){let n=1,r=`${t}${n}`;for(;e.includes(r);)r=`${t}${n}`,n++;return r}function _l(e,t){let n=1,r=k(`Copy of %s`,e),i=r.toString();for(;t.includes(i);)i=`${r} (${n})`,n++;return i}let vl=Dt(function(e){return qe(e.trim().toUpperCase())});function yl(e,t){return e===void 0||t===void 0?!1:vl(e)===vl(t)}function bl(e){if(typeof e==`string`)return{};if(typeof e==`number`)return[];throw Error(`Cannot create new node`)}function xl(e,t=1){return t*(e+4)-4}function Sl(e=100,t=100){return new OffscreenCanvas(e,t).getContext(`2d`)}function Cl(e,t,n,r,i){if(!t||!t.isFormula&&!t.content)return 23;let a=``;try{if(!t.isFormula){let e={format:t.format,locale:r};a=z(nc(t.content,r),e)}}catch{a=A.GenericError}return wl(e,a,n,i)}function wl(e,t,n,r){return El(e,Il(e,t,n,n?.wrapping===`wrap`?r-8:void 0),n).height+6}function Tl(e,t=!1,n=!1){return`${n?`italic`:``} ${t?`bold`:``} ${e}px ${we}`}function El(e,t,n={},r=`pt`){if(!t.length)return{width:0,height:0};let i=Nl(n,r),a=t.map(t=>jl(e,t,i)),o=xl(a[0].height,t.length),s=Math.max(...a.map(e=>e.width));if(!n.rotation)return{height:o,width:s};let c=Math.abs(Math.cos(n.rotation)),l=Math.abs(Math.sin(n.rotation));return{width:s*c+o*l,height:l*s+c*o}}function Dl(e,t,n={},r=`pt`){return Ol(e,t,Nl(n,r),n.rotation)}function Ol(e,t,n,r){let i=jl(e,t,n);if(!r)return i.width;let a=Math.abs(Math.cos(r)),o=Math.abs(Math.sin(r));return i.width*a+i.height*o}let kl={};function Al(e,t,n,r=`pt`){let i=jl(e,t,Nl(n,r));if(!n.rotation)return i;let a=Math.abs(Math.cos(n.rotation)),o=Math.abs(Math.sin(n.rotation));return{width:i.width*a+i.height*o,height:i.height*a+i.width*o}}function jl(e,t,n){if(kl[n]||(kl[n]={}),kl[n][t]===void 0){e.save(),e.font=n;let r=e.measureText(t);e.restore();let i=r.width,a=r.fontBoundingBoxAscent+r.fontBoundingBoxDescent;kl[n][t]={width:i,height:a}}return kl[n][t]}function Ml(e){return Math.round(e*96/72)}function Nl(e,t=`pt`){return`${e.italic?`italic `:``}${e.bold?`bold`:`400`} ${(t===`pt`?Pl(e):e.fontSize)??Ce}px ${we}`}function Pl(e){return Ml(e?.fontSize||Ce)}function Fl(e,t,n,r){if(Dl(e,t,r)<=n)return[t];let i=[],a=``;for(let o of t)Dl(e,a+o,r)>n?(i.push(a),a=o):a+=o;return i.push(a),i}function Il(e,t,n,r){n||={},nt(t)&&(t=at(t).label);let i=[],a=t.includes(`
|
|
10
|
+
`))return e;if($i(e,R))return ta(e,R);let n=Ci(e,t);return n?n.value:$e(e)?e.toUpperCase()===`TRUE`:e}function rc(e,t=R,n,r){let i=ec(e.value);if(!i)return dc(ic(e,t,n),e.origin??r);let a=nc(i.label,t);return dc({...ic({value:a,format:e.format||(typeof a==`number`?ss(i.label,t)||cs(i.label):void 0)},t,n),link:i},e.origin??r)}function ic(e,t,n){let{value:r,format:i,message:a,errorOriginPosition:o}=e;i=n?.format||i;let s=z(r,{format:i,locale:t});return M(r)?uc(r,a,o):r===null?sc(i):ws(i)?ac(P(r),i,s):typeof r==`number`?ns(i||``)?cc(r,i,s):oc(r,i,s):typeof r==`boolean`?lc(r,i,s):ac(r,i,s)}function ac(e,t,n){return{value:e,format:t,formattedValue:n,type:`text`,isAutoSummable:!0,defaultAlign:`left`}}function oc(e,t,n){return{value:e||0,format:t,formattedValue:n,type:`number`,isAutoSummable:!0,defaultAlign:`right`}}let sc=Dt(function(e){return{value:null,format:e,formattedValue:``,type:`empty`,isAutoSummable:!0,defaultAlign:`left`}});function cc(e,t,n){return{value:e,format:t,formattedValue:n,type:`number`,isAutoSummable:!1,defaultAlign:`right`}}function lc(e,t,n){return{value:e,format:t,formattedValue:n,type:`boolean`,isAutoSummable:!1,defaultAlign:`center`}}function uc(e,t,n){return{value:e,formattedValue:e,message:t,type:`error`,isAutoSummable:!1,defaultAlign:`center`,errorOriginPosition:n}}function dc(e,t){return e.value===null||`origin`in e||(e.origin=t),e}function fc(e){let t=O.now();switch(e){case`today`:return Math.floor(Fi(t));case`yesterday`:return t.setDate(t.getDate()-1),Math.floor(Fi(t));case`tomorrow`:return t.setDate(t.getDate()+1),Math.floor(Fi(t));case`lastWeek`:return t.setDate(t.getDate()-6),Math.floor(Fi(t));case`lastMonth`:{let e=t.getMonth()===0?11:t.getMonth()-1,n=new O(t.getFullYear(),e,1);return t.getDate()>Ii(n)?t.setDate(1):(t.setDate(t.getDate()+1),t.setMonth(t.getMonth()-1)),Math.floor(Fi(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(Fi(t))}}function pc(e,t){return`dateValue`in e&&e.dateValue!==`exactDate`?[fc(e.dateValue)]:e.values.map(e=>bi(e,t))}function mc(e,t){return e.map(e=>{if(e.startsWith(`=`))return e;let n=nc(e,t);return typeof n==`number`?z(n,{format:t.dateFormat,locale:t}):``})}let hc=new WeakMap,gc=new WeakMap;function _c(e,t){hc.has(t)||(hc.set(t,new Map),gc.set(t,0));let n=hc.get(t),r=bc(e);if(n.has(r)){let i=n.get(r);return t[i]=e,i}let i=gc.get(t)+1;return n.set(r,i),gc.set(t,i),t[i]=e,i}function vc(e){let t={};for(let n in e){let r=Qt(e[n].map(E));for(let e of r)t[hn(e)]=Number(n)}return t}function*yc(e,t){for(let n in t){let r=un(n),i=t[n];for(let t=r.top;t<=r.bottom;t++)for(let n=r.left;n<=r.right;n++)yield[{sheetId:e,col:n,row:t},i]}}function bc(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+=bc(e[r]);return n+`]`}let t=Object.keys(e).sort(),n=`{`;for(let r of t)e[r]!==void 0&&(n+=`"${r}":${bc(e[r])},`);return n+=`}`,n}function xc(e){return 20+120*Math.exp(-.035*(e-1))}let Sc=new RegExp(/\$?([A-Z]{1,3})\$?([0-9]{1,7})/,`i`),Cc=new RegExp(/^\$?([A-Z]{1,3})\$?([0-9]{1,7})$/,`i`),wc=new RegExp(/^\$?([A-Z]{1,3})+$/,`i`),Tc=new RegExp(/^\$?([0-9]{1,7})+$/,`i`),Ec=new RegExp(/^\s*('.+'!|[^']+!)?\$?([A-Z]{1,3})$/,`i`),Dc=new RegExp(/^\s*('.+'!|[^']+!)?\$?([0-9]{1,7})$/,`i`),Oc=RegExp(`^\\s*('.+'!|[^']+!)?(`+[Sc.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 kc(e){return Ec.test(e)}function Ac(e){return Dc.test(e)}function jc(e){return wc.test(e)}function Mc(e){return Tc.test(e)}function Nc(e){return Cc.test(e)}function Pc(e){if(!e.includes(`!`))return{xc:e};let t=e.split(`!`),n=t.pop();return{sheetName:qe(t.join(`!`))||void 0,xc:n}}function Fc(e,t){return e===void 0?t:`${Ye(e)}!${t}`}function Ic(e){if(e.type!==`REFERENCE`)return e;let{xc:t,sheetName:n}=Pc(e.value),[r,i]=t.split(`:`),a=Lc(r),o=i?`:${Lc(i)}`:``;return{...e,value:Fc(n,a+o)}}function Lc(e){switch(Bc(e)){case`none`:e=Rc(e,`colrow`);break;case`colrow`:e=Rc(e,`row`);break;case`row`:e=Rc(e,`col`);break;case`col`:e=Rc(e,`none`);break}return e}function Rc(e,t){let n;({sheetName:n,xc:e}=Pc(e)),n=n?Ye(n)+`!`:``,e=e.replace(/\$/g,``);let r=e.indexOf(`:`);return r>=0?`${n}${zc(e.slice(0,r),t)}:${zc(e.slice(r+1),t)}`:n+zc(e,t)}function zc(e,t){let n=e.search(/[0-9]/),r=n!==0,i=n>=0;switch(t){case`col`:return r?`$`+e:e;case`row`:return i?e.slice(0,n)+`$`+e.slice(n):e;case`colrow`:return!i||!r?`$`+e:`$`+e.slice(0,n)+`$`+e.slice(n);case`none`:return e}}function Bc(e){return Uc(e)?`colrow`:Vc(e)?`col`:Hc(e)?`row`:`none`}function Vc(e){return e.startsWith(`$`)}function Hc(e){return e.includes(`$`,1)}function Uc(e){return e.startsWith(`$`)&&e.length>1&&e.slice(1).includes(`$`)}function Wc(e,t){let n=e.zone,r=Wn(n,t(e.sheetId)),i=e.parts;return e.parts.length===1&&Vn(r)>1?i=[e.parts[0],e.parts[0]]:e.parts.length===2&&Vn(r)===1&&(i=[e.parts[0]]),{unboundedZone:n,zone:r,parts:i,prefixSheet:e.prefixSheet,invalidSheetName:e.invalidSheetName,sheetId:e.sheetId}}function Gc(e,t){let n=e.xc,{xc:r,sheetName:i}=Pc(n),a=ln(r);return Wc({zone:a,parts:$c(r,a),sheetId:e.sheetId,prefixSheet:!!i,invalidSheetName:e.invalidSheetName},t)}function Kc(e){let t={left:-1,top:-1,right:-1,bottom:-1};return{sheetId:``,zone:t,unboundedZone:t,parts:[],invalidXc:e,prefixSheet:!1}}function qc(e){return Bn(e.unboundedZone)}function Jc(e){return zn(e.unboundedZone)}function Yc(e,t,n,r={useBoundedReference:!1,useFixedReference:!1}){if(e.invalidXc)return e.invalidXc;if(e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0||e.zone.left<0||e.zone.top<0)return A.InvalidReference;let i=e.sheetId!==t||e.invalidSheetName||e.prefixSheet,a=``;if(i&&(a=e.invalidSheetName?Ye(e.invalidSheetName):Ye(n(e.sheetId))),i&&!a)return A.InvalidReference;let o=ul(e,0,r);return e.parts&&e.parts.length===2&&(e.zone.top!==e.zone.bottom||e.zone.left!==e.zone.right||e.parts[0].rowFixed||e.parts[0].colFixed||e.parts[1].rowFixed||e.parts[1].colFixed)&&(o+=`:`,o+=ul(e,1,r)),`${i?a+`!`:``}${o}`}function Xc(e,t,n){let r=n.sheetId===e?t:n.sheetId;return{...n,sheetId:r}}function Zc(e,t,n){if(!n)return;let r=e.getRangeFromSheetXC(t,n);return r.invalidSheetName||r.invalidXc?void 0:r}function Qc(e){let t=[];for(let n of e)for(let e of jn(n.zone))t.push({...e,sheetId:n.sheetId});return t}function $c(e,t){let n=e.split(`:`).map(e=>{let t=Ac(e);return{colFixed:t?!1:e.startsWith(`$`),rowFixed:t?e.startsWith(`$`):e.includes(`$`,1)}}),r=t.bottom===void 0,i=t.right===void 0;return r&&(n[0].rowFixed=n[0].rowFixed||n[1].rowFixed,n[1].rowFixed=n[0].rowFixed||n[1].rowFixed),i&&(n[0].colFixed=n[0].colFixed||n[1].colFixed,n[1].colFixed=n[0].colFixed||n[1].colFixed),n}function el(e){let t={left:e.col,top:e.row,right:e.col,bottom:e.row};return{sheetId:e.sheetId,zone:t}}function tl(e){if(mn(e.zone))return e;let t={...e.unboundedZone},n={...e.zone},r=e.parts;if(t.right!==void 0&&t.right<t.left){let e=t.right;t.right=t.left,t.left=e,n.right=n.left,n.left=e,r=[{colFixed:r[1]?.colFixed||!1,rowFixed:r[0]?.rowFixed||!1},{colFixed:r[0]?.colFixed||!1,rowFixed:r[1]?.rowFixed||!1}]}if(t.bottom!==void 0&&t.bottom<t.top){let e=t.bottom;t.bottom=t.top,t.top=e,n.bottom=n.top,n.top=e,r=[{colFixed:r[0]?.colFixed||!1,rowFixed:r[1]?.rowFixed||!1},{colFixed:r[1]?.colFixed||!1,rowFixed:r[0]?.rowFixed||!1}]}return{unboundedZone:t,zone:n,parts:r,invalidXc:e.invalidXc,prefixSheet:e.prefixSheet,invalidSheetName:e.invalidSheetName,sheetId:e.sheetId}}function nl(e){return rl.get(e.type)?.(e)}let rl=new class extends B{add(e,t){return super.add(e,t),this}get(e){return this.content[e]}};rl.add(`REMOVE_COLUMNS_ROWS`,e=>({applyChange:il(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add(`ADD_COLUMNS_ROWS`,e=>({applyChange:al(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add(`DELETE_SHEET`,e=>({applyChange:ol(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}})).add(`RENAME_SHEET`,e=>({applyChange:sl(e),sheetId:e.sheetId,sheetName:{old:e.oldName,current:e.newName}})).add(`MOVE_RANGES`,e=>({applyChange:cl(e),sheetId:e.sheetId,sheetName:{old:e.sheetName,current:e.sheetName}}));function il(e){let t=e.dimension===`COL`?`left`:`top`,n=e.dimension===`COL`?`right`:`bottom`,r=e.dimension===`COL`?`columns`:`rows`,i=[...e.elements];i.sort((e,t)=>t-e);let a=Ze(i);return i=>{if(i.sheetId!==e.sheetId)return{changeType:`NONE`,range:i};let o=i,s=`NONE`;for(let e of a){let a=Ft(e),c=Pt(e);if(i.zone[t]<=a&&a<=i.zone[n]){let e=Math.min(i.zone[n],c)-a+1;s=`RESIZE`,o=ll(o,r,s,-e)}else if(i.zone[t]>=a&&i.zone[n]<=c)s=`REMOVE`,o=Kc(A.InvalidReference);else if(i.zone[t]<=c&&i.zone[n]>=c){let e=c-i.zone[t]+1;s=`RESIZE`,o=ll(o,r,s,-e),o=ll(o,r,`MOVE`,-(i.zone[t]-a))}else a<i.zone[t]&&(s=`MOVE`,o=ll(o,r,s,-(c-a+1)))}return{changeType:s,range:o}}}function al(e){let t=e.dimension===`COL`?`left`:`top`,n=e.dimension===`COL`?`right`:`bottom`,r=e.dimension===`COL`?`columns`:`rows`;return i=>{if(i.sheetId!==e.sheetId)return{changeType:`NONE`,range:i};let a=i.unboundedZone[n]===void 0;if(a&&!i.unboundedZone.hasHeader)return{changeType:`RESIZE`,range:ll(i,r,`RESIZE`,e.quantity)};if(e.position===`after`){if(i.zone[t]<=e.base&&(e.base<i.zone[n]||a))return{changeType:`RESIZE`,range:ll(i,r,`RESIZE`,e.quantity)};if(e.base<i.zone[t])return{changeType:`MOVE`,range:ll(i,r,`MOVE`,e.quantity)}}else{if(i.zone[t]<e.base&&e.base<=i.zone[n])return{changeType:`RESIZE`,range:ll(i,r,`RESIZE`,e.quantity)};if(e.base<=i.zone[t])return{changeType:`MOVE`,range:ll(i,r,`MOVE`,e.quantity)}}return{changeType:`NONE`,range:i}}}function ol(e){return t=>{if(t.sheetId!==e.sheetId&&t.invalidSheetName!==e.sheetName)return{changeType:`NONE`,range:t};let n=e.sheetName;return t={...Kc(A.InvalidReference),invalidSheetName:n},{changeType:`REMOVE`,range:t}}}function sl(e){return t=>{if(t.sheetId===e.sheetId)return{changeType:`CHANGE`,range:t};if(e.newName&&t.invalidSheetName===e.newName){let n=e.sheetId;return{changeType:`CHANGE`,range:{...t,sheetId:n,invalidSheetName:void 0}}}if(e.oldName&&t.invalidSheetName===e.oldName){let n=e.sheetId;return{changeType:`CHANGE`,range:{...t,sheetId:n,invalidSheetName:void 0}}}return{changeType:`NONE`,range:t}}}function cl(e){let t=e.target[0];return n=>{if(n.sheetId!==e.sheetId||!Dn(n.zone,t))return{changeType:`NONE`,range:n};let r=e.targetSheetId,i=ll(n,`both`,`MOVE`,[e.col-t.left,e.row-t.top]),a=e.sheetId===r?i.prefixSheet:!0;return{changeType:`MOVE`,range:{...i,sheetId:r,prefixSheet:a}}}}function ll(e,t,n,r){return{...e,unboundedZone:Pn(e.unboundedZone,t,n,r),zone:Pn(e.zone,t,n,r)}}function ul(e,t,n={useBoundedReference:!1,useFixedReference:!1}){let r=e.parts[t]?.colFixed||n.useFixedReference?`$`:``,i=Ht(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=Bn(e.unboundedZone)&&!n.useBoundedReference?t===0&&e.unboundedZone.hasHeader?r+i+a+o:r+i:zn(e.unboundedZone)&&!n.useBoundedReference?t===0&&e.unboundedZone.hasHeader?r+i+a+o:a+o:r+i+a+o,s}function dl(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 fl(e,t,n){let r=[];return t.forEach(t=>{let i=dl(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 pl(e){let t=[];for(let n=0;n<e;n++)t.push({cells:{}});return t}function ml(e,t,n){return n.map(n=>n>=e?n+t:n)}function hl(e,t){return e=[...e].sort((e,t)=>t-e),t.map(t=>{for(let n of e)if(t>n)t--;else if(t===n)return;return t}).filter(C)}function gl(e,t=`Sheet`){let n=1,r=`${t}${n}`;for(;e.includes(r);)r=`${t}${n}`,n++;return r}function _l(e,t){let n=1,r=k(`Copy of %s`,e),i=r.toString();for(;t.includes(i);)i=`${r} (${n})`,n++;return i}let vl=Dt(function(e){return qe(e.trim().toUpperCase())});function yl(e,t){return e===void 0||t===void 0?!1:vl(e)===vl(t)}function bl(e){if(typeof e==`string`)return{};if(typeof e==`number`)return[];throw Error(`Cannot create new node`)}function xl(e,t=1){return t*(e+4)-4}function Sl(e=100,t=100){return new OffscreenCanvas(e,t).getContext(`2d`)}function Cl(e,t,n,r,i){if(!t||!t.isFormula&&!t.content)return 23;let a=``;try{if(!t.isFormula){let e={format:t.format,locale:r};a=z(nc(t.content,r),e)}}catch{a=A.GenericError}return wl(e,a,n,i)}function wl(e,t,n,r){return El(e,Il(e,t,n,n?.wrapping===`wrap`?r-8:void 0),n).height+6}function Tl(e,t=!1,n=!1){return`${n?`italic`:``} ${t?`bold`:``} ${e}px ${we}`}function El(e,t,n={},r=`pt`){if(!t.length)return{width:0,height:0};let i=Nl(n,r),a=t.map(t=>jl(e,t,i)),o=xl(a[0].height,t.length),s=Math.max(...a.map(e=>e.width));if(!n.rotation)return{height:o,width:s};let c=Math.abs(Math.cos(n.rotation)),l=Math.abs(Math.sin(n.rotation));return{width:s*c+o*l,height:l*s+c*o}}function Dl(e,t,n={},r=`pt`){return Ol(e,t,Nl(n,r),n.rotation)}function Ol(e,t,n,r){let i=jl(e,t,n);if(!r)return i.width;let a=Math.abs(Math.cos(r)),o=Math.abs(Math.sin(r));return i.width*a+i.height*o}let kl={};function Al(e,t,n,r=`pt`){let i=jl(e,t,Nl(n,r));if(!n.rotation)return i;let a=Math.abs(Math.cos(n.rotation)),o=Math.abs(Math.sin(n.rotation));return{width:i.width*a+i.height*o,height:i.height*a+i.width*o}}function jl(e,t,n){if(kl[n]||(kl[n]={}),kl[n][t]===void 0){e.save(),e.font=n;let r=e.measureText(t);e.restore();let i=r.width,a=r.fontBoundingBoxAscent+r.fontBoundingBoxDescent;kl[n][t]={width:i,height:a}}return kl[n][t]}function Ml(e){return Math.round(e*96/72)}function Nl(e,t=`pt`){return`${e.italic?`italic `:``}${e.bold?`bold`:`400`} ${(t===`pt`?Pl(e):e.fontSize)??Ce}px ${we}`}function Pl(e){return Ml(e?.fontSize||Ce)}function Fl(e,t,n,r){if(Dl(e,t,r)<=n)return[t];let i=[],a=``;for(let o of t)Dl(e,a+o,r)>n?(i.push(a),a=o):a+=o;return i.push(a),i}function Il(e,t,n,r){n||={},nt(t)&&(t=at(t).label);let i=[],a=t.includes(`
|
|
11
11
|
`)?t.split(`
|
|
12
|
-
`):[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=Fl(e,t,r,n),c=a.pop(),l=Dl(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=Dl(e,t,n);a<=s?(o+=t,s-=a):(i.push(o),o=c,s=r-l)}}o!==``&&i.push(o)}return i}function Ll(e,t,n,r=.25){let i=1;if(n(i)>e)return i;if(n(t)<e)return t;let a=(i+t)/2,o=n(a),s=0;for(;Math.abs(o-e)>r&&s<20;)o>=e?t=(i+t)/2:i=(i+t)/2,a=(i+t)/2,o=n(a),s++;return a}function Rl(e){return e?e.toLowerCase():``}let zl=/([0-9\.]*)px/;function Bl(e){return Number(e.match(zl)?.[1])}function Vl(e,t,n){let r=Ol(e,t,e.font);if(r<=n)return t;let i=Ol(e,`…`,e.font);if(r<=i)return t;let a=t.length;for(;r>=n-i&&a-- >0;)t=t.substring(0,a),r=Ol(e,t,e.font);return t+`…`}function Hl(e,t,n,r=!1,i=!1,a=Bl(e.font)/10){if(e.fillText(t,n.x,n.y),!r&&!i)return;let o=e.measureText(t),s=o.width,c=o.actualBoundingBoxAscent+o.actualBoundingBoxDescent,l=o.fontBoundingBoxAscent+o.fontBoundingBoxDescent,{x:u,y:d}=n,f=d,p=d;switch(e.textAlign){case`center`:u-=s/2;break;case`right`:u-=s;break}switch(e.textBaseline){case`top`:p+=l-2*a,f+=l/2-a;break;case`middle`:p+=l/2-a;break;case`alphabetic`:p+=2*a,f-=3*a;break;case`bottom`:p=d,f-=c/2-a/2;break}r&&(e.lineWidth=a,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,p),e.lineTo(u+s,p),e.stroke()),i&&(e.lineWidth=a,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,f),e.lineTo(u+s,f),e.stroke())}function Ul(e,t,n,r,i=`pt`){if(Dl(e,n,r,i)<=t)return n;let a=Dl(e,`...`,r,i);if(a>=t)return``;let o=1,s=n.length,c;for(;o<=s;){let l=Math.floor((o+s)/2);c=Dl(e,n.slice(0,l),r,i),c+a>t?s=l-1:o=l+1}let l=n.slice(0,Math.max(0,o-1));return l?l+`...`:``}function Wl(e,t){if(!t.rotation||t.rotation%(Math.PI*2)==0)return e;let{x:n,y:r}=e,i=Math.cos(-t.rotation),a=Math.sin(-t.rotation),o=e.textWidth-8,s=e.textHeight,c=t.align===`center`,l=t.align===`left`==a<0,u=a*s,d=Math.abs(a*o),f=i*s;return t.verticalAlign===`top`?c?(r+=d/2,n-=u/2):l?n-=u:r+=d:!t.verticalAlign||t.verticalAlign===`bottom`?(r+=s-f,c?(r-=d/2,n-=u/2):l&&(n-=u,r-=d)):c?(n-=u/2,r-=s/2,l?r+=u:r-=u):l?(n-=u,r-=d/2):r+=d/2+f/4,{x:i*n-a*r,y:i*r+a*n}}var Gl=class{getCrypto(){if(typeof globalThis<`u`&&globalThis.crypto)return globalThis.crypto}smallUuid(){let e=this.getCrypto();return e?`10000000-1000`.replace(/[01]/g,t=>{let n=Number(t);return(n^e.getRandomValues(new Uint8Array(1))[0]&15>>n/4).toString(16)}):`xxxxxxxx-xxxx`.replace(/[xy]/g,function(e){let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}uuidv4(){let e=this.getCrypto();return e?`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,t=>{let n=Number(t);return(n^e.getRandomValues(new Uint8Array(1))[0]&15>>n/4).toString(16)}):`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,function(e){let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}},Kl=class{content={};add(e,t){if(e in this.content)throw Error(`${e} is already present in this registry!`);return this.replace(e,t)}replace(e,t){return this.content[e]=t,this}get(e){let t=this.content[e];if(!t&&!(e in this.content))throw Error(`Cannot find ${e} in this registry!`);return t}contains(e){return e in this.content}getAll(){return Object.values(this.content)}getKeys(){return Object.keys(this.content)}remove(e){delete this.content[e]}};let ql=new Kl;function Jl(){return globalThis.Chart?!!globalThis.Chart.registry.plugins.get(`chartShowValuesPlugin`):!0}function Yl(){if(!(!globalThis.Chart||Jl()))for(let e of ql.getAll())e.register(globalThis.Chart)}function Xl(){if(globalThis.Chart)for(let e of ql.getAll())e.unregister(globalThis.Chart)}var Zl=class extends hr{mutators=[`disableAnimationForChart`,`enableAnimationForChart`];animationPlayed={};disableAnimationForChart(e,t){return this.animationPlayed[e]=t,`noStateChange`}enableAnimationForChart(e){return this.animationPlayed[e]=void 0,`noStateChange`}};function Ql(){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);return class extends globalThis.Chart.BarController{static id=`calendar`;static defaults={...globalThis.Chart?.BarController.defaults,dataElementType:`bar`,animations:{numbers:{type:`number`,properties:[]}}};updateElements(e,t,n,r){super.updateElements(e,t,n,r);let i=this.chart.config.options?.chartBackground||`#ffffff`;for(let a=t;a<t+n;a++)r===`reset`&&this.updateElement(e[a],a,{options:{backgroundColor:i}},r)}}}let $l={id:`chartColorScalePlugin`,afterDatasetsDraw(e,t,n){if(!n.position||n.position===`none`||!n.colorScale.length)return;let r=e.ctx;r.save(),r.textAlign=`center`,r.textBaseline=`middle`,r.miterLimit=1;let i=(e.chartArea.bottom-e.chartArea.top)/2,a=n.position===`left`?20:r.canvas.width-70,o=e.chartArea.top,s=r.createLinearGradient(0,o+i,0,o),c=1/(n.colorScale.length-1);n.colorScale.forEach((e,t)=>{s.addColorStop(t*c,e)}),r.fillStyle=s,r.fillRect(a,o,10,i),r.fillStyle=n.fontColor??`black`,r.font=Tl(12),r.textAlign=`left`;let l=Math.round(n.minValue*100)/100,u=Math.round(n.maxValue*100)/100;n.minValue===n.maxValue&&(--l,u+=1);let d=hs({value:u,format:void 0},n.locale),f=hs({value:l,format:void 0},n.locale);r.fillText(f,a+10+5,o+i-6),r.fillText(d,a+10+5,o+6),r.restore()}};function eu(){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);return class extends globalThis.Chart.BarController{static id=`funnel`;static defaults={...globalThis.Chart?.BarController.defaults,dataElementType:`funnel`,animation:{duration:e=>e.type===`data`?1e3*(e.raw[1]/Math.max(...e.dataset.data.map(e=>e[1]))):1e3}};updateElements(e,t,n,r){super.updateElements(e,t,n,r);for(let i=t;i<t+n;i++){let t=e[i];this.updateElement(t,i,{nextElement:e[i+1]},r)}}}}function tu(){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);return class extends globalThis.Chart.BarElement{static id=`funnel`;draw(e){e.save();let{x:t,y:n,height:r,nextElement:i,base:a,options:o}=this.getProps([`x`,`y`,`width`,`height`,`nextElement`,`base`,`options`]),s=nu(this),c=(s-(i?nu(i):0))/2,l=Math.min(t,a),u=n-r/2;e.fillStyle=o.backgroundColor,e.beginPath(),e.moveTo(l,u),e.lineTo(l+s,u),e.lineTo(l+s-c,u+r),e.lineTo(l+c,u+r),e.closePath(),e.fill(),o.borderWidth&&(e.strokeStyle=o.borderColor,e.lineWidth=o.borderWidth,e.stroke()),e.restore()}inRange(e,t){let{x:n,y:r,height:i,nextElement:a,base:o}=this.getProps([`x`,`y`,`width`,`height`,`nextElement`,`base`,`options`]),s=nu(this),c=a?nu(a):0,l=Math.min(n,o),u=r-i/2;if(t<u||t>u+i)return!1;let d=(s-c)/2,f=l+d*(t-u)/i,p=l+s-d*(t-u)/i;return!(e<f||e>p)}}}function nu(e){let{x:t,base:n}=e.getProps([`x`,`base`]);return Math.max(t,n)-Math.min(t,n)}let ru=function(e){if(!e.length)return{x:0,y:0};let{x:t,y:n,base:r,width:i,height:a}=e[0].element.getProps([`x`,`y`,`width`,`height`,`base`]),o=Math.min(t,r),s=n-a/2;return{x:o+i*2/3,y:s+a/2}},iu=`000000`,au={arrows:`3Arrows`,smiley:`3Symbols`,dots:`3TrafficLights1`},ou={styleSheet:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,sst:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,Relationships:`http://schemas.openxmlformats.org/package/2006/relationships`,Types:`http://schemas.openxmlformats.org/package/2006/content-types`,worksheet:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,workbook:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,drawing:`http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing`,table:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,revision:`http://schemas.microsoft.com/office/spreadsheetml/2014/revision`,revision3:`http://schemas.microsoft.com/office/spreadsheetml/2016/revision3`,markupCompatibility:`http://schemas.openxmlformats.org/markup-compatibility/2006`},su=`http://schemas.openxmlformats.org/drawingml/2006/main`,cu=`http://schemas.openxmlformats.org/drawingml/2006/chart`,lu={workbook:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml`,macroEnabledWorkbook:`application/vnd.ms-excel.sheet.macroEnabled.main+xml`,templateWorkbook:`application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml`,macroEnabledTemplateWorkbook:`application/vnd.ms-excel.template.macroEnabled.main+xml`,excelAddInWorkbook:`application/vnd.ms-excel.addin.macroEnabled.main+xml`,sheet:`application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml`,metadata:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml`,sharedStrings:`application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml`,styles:`application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml`,drawing:`application/vnd.openxmlformats-officedocument.drawing+xml`,chart:`application/vnd.openxmlformats-officedocument.drawingml.chart+xml`,themes:`application/vnd.openxmlformats-officedocument.theme+xml`,table:`application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml`,pivot:`application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml`,externalLink:`application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml`},uu={document:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument`,sheet:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet`,metadata:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/sheetMetadata`,sharedStrings:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings`,styles:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles`,drawing:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing`,chart:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart`,theme:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme`,table:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/table`,hyperlink:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink`,image:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/image`},du=`http://schemas.openxmlformats.org/officeDocument/2006/relationships`,fu=.75,pu=.143,mu=8.43,hu=12.75,gu={FLOOR:[{type:`NUMBER`,value:1}],CEILING:[{type:`NUMBER`,value:1}],ROUND:[{type:`NUMBER`,value:0}],ROUNDUP:[{type:`NUMBER`,value:0}],ROUNDDOWN:[{type:`NUMBER`,value:0}]},_u=`ACOT,ACOTH,AGGREGATE,ARABIC,BASE,BETA.DIST,BETA.INV,BINOM.DIST,BINOM.DIST.RANGE,BINOM.INV,BITAND,BITLSHIFT,BITOR,BITRSHIFT,BITXOR,BYCOL,BYROW,CEILING.MATH,CEILING.PRECISE,CHISQ.DIST,CHISQ.DIST.RT,CHISQ.INV,CHISQ.INV.RT,CHISQ.TEST,CHOOSECOLS,CHOOSEROWS,COMBINA,CONCAT,CONFIDENCE.NORM,CONFIDENCE.T,COT,COTH,COVARIANCE.P,COVARIANCE.S,CSC,CSCH,DAYS,DECIMAL,DROP,ERF.PRECISE,ERFC.PRECISE,EXPAND,EXPON.DIST,F.DIST,F.DIST.RT,F.INV,F.INV.RT,F.TEST,FIELDVALUE,FILTERXML,FLOOR.MATH,FLOOR.PRECISE,FORECAST.ETS,FORECAST.ETS.CONFINT,FORECAST.ETS.SEASONALITY,FORECAST.ETS.STAT,FORECAST.LINEAR,FORMULATEXT,GAMMA,GAMMA.DIST,GAMMA.INV,GAMMALN.PRECISE,GAUSS,HSTACK,HYPGEOM.DIST,IFNA,IFS,IMCOSH,IMCOT,IMCSC,IMCSCH,IMSEC,IMSECH,IMSINH,IMTAN,ISFORMULA,ISOMITTED,ISOWEEKNUM,LAMBDA,LET,LOGNORM.DIST,LOGNORM.INV,MAKEARRAY,MAP,MAXIFS,MINIFS,MODE.MULT,MODE.SNGL,MUNIT,NEGBINOM.DIST,NORM.DIST,NORM.INV,NORM.S.DIST,NORM.S.INV,NUMBERVALUE,PDURATION,PERCENTILE.EXC,PERCENTILE.INC,PERCENTRANK.EXC,PERCENTRANK.INC,PERMUTATIONA,PHI,POISSON.DIST,PQSOURCE,PYTHON_STR,PYTHON_TYPE,PYTHON_TYPENAME,QUARTILE.EXC,QUARTILE.INC,QUERYSTRING,RANDARRAY,RANK.AVG,RANK.EQ,REDUCE,RRI,SCAN,SEC,SECH,SEQUENCE,SHEET,SHEETS,SKEW.P,SORTBY,STDEV.P,STDEV.S,SWITCH,T.DIST,T.DIST.2T,T.DIST.RT,T.INV,T.INV.2T,T.TEST,TAKE,TEXTAFTER,TEXTBEFORE,TEXTJOIN,TEXTSPLIT,TOCOL,TOROW,UNICHAR,UNICODE,UNIQUE,VAR.P,VAR.S,VSTACK,WEBSERVICE,WEIBULL.DIST,WRAPCOLS,WRAPROWS,XLOOKUP,XOR,Z.TEST`.split(`,`),vu=[`%`],yu=`+,-,*,/,:,=,<>,>=,>,<=,<,^,&`.split(`,`).concat(vu);function bu(e,t=R){e=Tt(e);let n=new It(e),r=[],i=St.test(e)?Fu:Iu;for(;!n.isOver();){let e=Lu(n)||i(n)||Du(n,t)||Eu(n,t)||Tu(n)||Cu(n)||Ou(n)||ju(n)||xu(n)||Ru(n)||Au(n,t)||Pu(n);e||={type:`UNKNOWN`,value:n.shift()},r.push(e)}return r}function xu(e){return e.current===`?`?(e.shift(),{type:`DEBUGGER`,value:`?`}):null}let Su={"(":{type:`LEFT_PAREN`,value:`(`},")":{type:`RIGHT_PAREN`,value:`)`}};function Cu(e){return e.current===`(`||e.current===`)`?Su[e.shift()]:null}let wu={"{":{type:`LEFT_BRACE`,value:`{`},"}":{type:`RIGHT_BRACE`,value:`}`}};function Tu(e){return e.current===`{`||e.current===`}`?wu[e.shift()]:null}function Eu(e,t){return e.current===t.formulaArgSeparator?{type:`ARG_SEPARATOR`,value:e.shift()}:null}function Du(e,t){let n=t.formulaArgSeparator===`;`?`\\`:`;`;return n&&e.current===n?(e.shift(),{type:`ARRAY_ROW_SEPARATOR`,value:n}):null}function Ou(e){for(let t of yu)if(e.currentStartsWith(t))return e.advanceBy(t.length),{type:`OPERATOR`,value:t};return null}let ku=new Set(`0123456789`);function Au(e,t){if(!ku.has(e.current)&&e.current!==t.decimalSeparator)return null;let n=e.remaining().match(Zi(t.decimalSeparator));return n?(e.advanceBy(n[0].length),{type:`NUMBER`,value:n[0]}):null}function ju(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 Mu=/\p{L}|\p{N}|_|\.|!|\$/u,Nu=new Set(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.!$`);function Pu(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&&(Nu.has(e.current)||e.current.match(Mu));)t+=e.shift();if(t.length){let e=t;return Oc.test(e)?{type:`REFERENCE`,value:e}:{type:`SYMBOL`,value:e}}return null}function Fu(e){let t=``;for(;e.current===` `||e.current&&e.current.match(St);)t+=e.shift();return t?{type:`SPACE`,value:t}:null}function Iu(e){let t=``;for(;e.current===` `;)t+=e.shift();return t?{type:`SPACE`,value:t}:null}function Lu(e){let t=0;for(;e.current===`
|
|
12
|
+
`):[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=Fl(e,t,r,n),c=a.pop(),l=Dl(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=Dl(e,t,n);a<=s?(o+=t,s-=a):(i.push(o),o=c,s=r-l)}}o!==``&&i.push(o)}return i}function Ll(e,t,n,r=.25){let i=1;if(n(i)>e)return i;if(n(t)<e)return t;let a=(i+t)/2,o=n(a),s=0;for(;Math.abs(o-e)>r&&s<20;)o>=e?t=(i+t)/2:i=(i+t)/2,a=(i+t)/2,o=n(a),s++;return a}function Rl(e){return e?e.toLowerCase():``}let zl=/([0-9\.]*)px/;function Bl(e){return Number(e.match(zl)?.[1])}function Vl(e,t,n){let r=Ol(e,t,e.font);if(r<=n)return t;let i=Ol(e,`…`,e.font);if(r<=i)return t;let a=t.length;for(;r>=n-i&&a-- >0;)t=t.substring(0,a),r=Ol(e,t,e.font);return t+`…`}function Hl(e,t,n,r=!1,i=!1,a=Bl(e.font)/10){if(e.fillText(t,n.x,n.y),!r&&!i)return;let o=e.measureText(t),s=o.width,c=o.actualBoundingBoxAscent+o.actualBoundingBoxDescent,l=o.fontBoundingBoxAscent+o.fontBoundingBoxDescent,{x:u,y:d}=n,f=d,p=d;switch(e.textAlign){case`center`:u-=s/2;break;case`right`:u-=s;break}switch(e.textBaseline){case`top`:p+=l-2*a,f+=l/2-a;break;case`middle`:p+=l/2-a;break;case`alphabetic`:p+=2*a,f-=3*a;break;case`bottom`:p=d,f-=c/2-a/2;break}r&&(e.lineWidth=a,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,p),e.lineTo(u+s,p),e.stroke()),i&&(e.lineWidth=a,e.strokeStyle=e.fillStyle,e.beginPath(),e.moveTo(u,f),e.lineTo(u+s,f),e.stroke())}function Ul(e,t,n,r,i=`pt`){if(Dl(e,n,r,i)<=t)return n;let a=Dl(e,`...`,r,i);if(a>=t)return``;let o=1,s=n.length,c;for(;o<=s;){let l=Math.floor((o+s)/2);c=Dl(e,n.slice(0,l),r,i),c+a>t?s=l-1:o=l+1}let l=n.slice(0,Math.max(0,o-1));return l?l+`...`:``}function Wl(e,t){if(!t.rotation||t.rotation%(Math.PI*2)==0)return e;let{x:n,y:r}=e,i=Math.cos(-t.rotation),a=Math.sin(-t.rotation),o=e.textWidth-8,s=e.textHeight,c=t.align===`center`,l=t.align===`left`==a<0,u=a*s,d=Math.abs(a*o),f=i*s;return t.verticalAlign===`top`?c?(r+=d/2,n-=u/2):l?n-=u:r+=d:!t.verticalAlign||t.verticalAlign===`bottom`?(r+=s-f,c?(r-=d/2,n-=u/2):l&&(n-=u,r-=d)):c?(n-=u/2,r-=s/2,l?r+=u:r-=u):l?(n-=u,r-=d/2):r+=d/2+f/4,{x:i*n-a*r,y:i*r+a*n}}var Gl=class{getCrypto(){if(typeof globalThis<`u`&&globalThis.crypto)return globalThis.crypto}smallUuid(){let e=this.getCrypto();return e?`10000000-1000`.replace(/[01]/g,t=>{let n=Number(t);return(n^e.getRandomValues(new Uint8Array(1))[0]&15>>n/4).toString(16)}):`xxxxxxxx-xxxx`.replace(/[xy]/g,function(e){let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}uuidv4(){let e=this.getCrypto();return e?`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,t=>{let n=Number(t);return(n^e.getRandomValues(new Uint8Array(1))[0]&15>>n/4).toString(16)}):`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,function(e){let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}},Kl=class{content={};add(e,t){if(e in this.content)throw Error(`${e} is already present in this registry!`);return this.replace(e,t)}replace(e,t){return this.content[e]=t,this}get(e){let t=this.content[e];if(!t&&!(e in this.content))throw Error(`Cannot find ${e} in this registry!`);return t}contains(e){return e in this.content}getAll(){return Object.values(this.content)}getKeys(){return Object.keys(this.content)}remove(e){delete this.content[e]}};let ql=new Kl;function Jl(){return globalThis.Chart?!!globalThis.Chart.registry.plugins.get(`chartShowValuesPlugin`):!0}function Yl(){if(!(!globalThis.Chart||Jl()))for(let e of ql.getAll())e.register(globalThis.Chart)}function Xl(){if(globalThis.Chart)for(let e of ql.getAll())e.unregister(globalThis.Chart)}var Zl=class extends hr{mutators=[`disableAnimationForChart`,`enableAnimationForChart`];animationPlayed={};disableAnimationForChart(e,t){return this.animationPlayed[e]=t,`noStateChange`}enableAnimationForChart(e){return this.animationPlayed[e]=void 0,`noStateChange`}};function Ql(){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);return class extends globalThis.Chart.BarController{static id=`calendar`;static defaults={...globalThis.Chart?.BarController.defaults,dataElementType:`bar`,animations:{numbers:{type:`number`,properties:[]}}};updateElements(e,t,n,r){super.updateElements(e,t,n,r);let i=this.chart.config.options?.chartBackground||`#ffffff`;for(let a=t;a<t+n;a++)r===`reset`&&this.updateElement(e[a],a,{options:{backgroundColor:i}},r)}}}let $l={id:`chartColorScalePlugin`,afterDatasetsDraw(e,t,n){if(!n.position||n.position===`none`||!n.colorScale.length)return;let r=e.ctx;r.save(),r.textAlign=`center`,r.textBaseline=`middle`,r.miterLimit=1;let i=(e.chartArea.bottom-e.chartArea.top)/2,a=n.position===`left`?20:r.canvas.width-70,o=e.chartArea.top,s=r.createLinearGradient(0,o+i,0,o),c=1/(n.colorScale.length-1);n.colorScale.forEach((e,t)=>{s.addColorStop(t*c,e)}),r.fillStyle=s,r.fillRect(a,o,10,i),r.fillStyle=n.fontColor??`black`,r.font=Tl(12),r.textAlign=`left`;let l=Math.round(n.minValue*100)/100,u=Math.round(n.maxValue*100)/100;n.minValue===n.maxValue&&(--l,u+=1);let d=hs({value:u,format:void 0},n.locale),f=hs({value:l,format:void 0},n.locale);r.fillText(f,a+10+5,o+i-6),r.fillText(d,a+10+5,o+6),r.restore()}};function eu(){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);return class extends globalThis.Chart.BarController{static id=`funnel`;static defaults={...globalThis.Chart?.BarController.defaults,dataElementType:`funnel`,animation:{duration:e=>e.type===`data`?1e3*(e.raw[1]/Math.max(...e.dataset.data.map(e=>e[1]))):1e3}};updateElements(e,t,n,r){super.updateElements(e,t,n,r);for(let i=t;i<t+n;i++){let t=e[i];this.updateElement(t,i,{nextElement:e[i+1]},r)}}}}function tu(){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);return class extends globalThis.Chart.BarElement{static id=`funnel`;draw(e){e.save();let{x:t,y:n,height:r,nextElement:i,base:a,options:o}=this.getProps([`x`,`y`,`width`,`height`,`nextElement`,`base`,`options`]),s=nu(this),c=(s-(i?nu(i):0))/2,l=Math.min(t,a),u=n-r/2;e.fillStyle=o.backgroundColor,e.beginPath(),e.moveTo(l,u),e.lineTo(l+s,u),e.lineTo(l+s-c,u+r),e.lineTo(l+c,u+r),e.closePath(),e.fill(),o.borderWidth&&(e.strokeStyle=o.borderColor,e.lineWidth=o.borderWidth,e.stroke()),e.restore()}inRange(e,t){let{x:n,y:r,height:i,nextElement:a,base:o}=this.getProps([`x`,`y`,`width`,`height`,`nextElement`,`base`,`options`]),s=nu(this),c=a?nu(a):0,l=Math.min(n,o),u=r-i/2;if(t<u||t>u+i)return!1;let d=(s-c)/2,f=l+d*(t-u)/i,p=l+s-d*(t-u)/i;return!(e<f||e>p)}}}function nu(e){let{x:t,base:n}=e.getProps([`x`,`base`]);return Math.max(t,n)-Math.min(t,n)}let ru=function(e){if(!e.length)return{x:0,y:0};let{x:t,y:n,base:r,width:i,height:a}=e[0].element.getProps([`x`,`y`,`width`,`height`,`base`]),o=Math.min(t,r),s=n-a/2;return{x:o+i*2/3,y:s+a/2}},iu=`000000`,au={arrows:`3Arrows`,smiley:`3Symbols`,dots:`3TrafficLights1`},ou={styleSheet:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,sst:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,Relationships:`http://schemas.openxmlformats.org/package/2006/relationships`,Types:`http://schemas.openxmlformats.org/package/2006/content-types`,worksheet:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,workbook:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,drawing:`http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing`,table:`http://schemas.openxmlformats.org/spreadsheetml/2006/main`,revision:`http://schemas.microsoft.com/office/spreadsheetml/2014/revision`,revision3:`http://schemas.microsoft.com/office/spreadsheetml/2016/revision3`,markupCompatibility:`http://schemas.openxmlformats.org/markup-compatibility/2006`},su=`http://schemas.openxmlformats.org/drawingml/2006/main`,cu=`http://schemas.openxmlformats.org/drawingml/2006/chart`,lu={workbook:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml`,macroEnabledWorkbook:`application/vnd.ms-excel.sheet.macroEnabled.main+xml`,templateWorkbook:`application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml`,macroEnabledTemplateWorkbook:`application/vnd.ms-excel.template.macroEnabled.main+xml`,excelAddInWorkbook:`application/vnd.ms-excel.addin.macroEnabled.main+xml`,sheet:`application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml`,metadata:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml`,sharedStrings:`application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml`,styles:`application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml`,drawing:`application/vnd.openxmlformats-officedocument.drawing+xml`,chart:`application/vnd.openxmlformats-officedocument.drawingml.chart+xml`,themes:`application/vnd.openxmlformats-officedocument.theme+xml`,table:`application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml`,pivot:`application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml`,externalLink:`application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml`},uu={document:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument`,sheet:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet`,metadata:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/sheetMetadata`,sharedStrings:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings`,styles:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles`,drawing:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing`,chart:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart`,theme:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme`,table:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/table`,hyperlink:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink`,image:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/image`},du=`http://schemas.openxmlformats.org/officeDocument/2006/relationships`,fu=.75,pu=.143,mu=8.43,hu=12.75,gu={FLOOR:[{type:`NUMBER`,value:1}],CEILING:[{type:`NUMBER`,value:1}],ROUND:[{type:`NUMBER`,value:0}],ROUNDUP:[{type:`NUMBER`,value:0}],ROUNDDOWN:[{type:`NUMBER`,value:0}],IFERROR:[{type:`NUMBER`,value:0}]},_u=`ACOT,ACOTH,AGGREGATE,ARABIC,BASE,BETA.DIST,BETA.INV,BINOM.DIST,BINOM.DIST.RANGE,BINOM.INV,BITAND,BITLSHIFT,BITOR,BITRSHIFT,BITXOR,BYCOL,BYROW,CEILING.MATH,CEILING.PRECISE,CHISQ.DIST,CHISQ.DIST.RT,CHISQ.INV,CHISQ.INV.RT,CHISQ.TEST,CHOOSECOLS,CHOOSEROWS,COMBINA,CONCAT,CONFIDENCE.NORM,CONFIDENCE.T,COT,COTH,COVARIANCE.P,COVARIANCE.S,CSC,CSCH,DAYS,DECIMAL,DROP,ERF.PRECISE,ERFC.PRECISE,EXPAND,EXPON.DIST,F.DIST,F.DIST.RT,F.INV,F.INV.RT,F.TEST,FIELDVALUE,FILTERXML,FLOOR.MATH,FLOOR.PRECISE,FORECAST.ETS,FORECAST.ETS.CONFINT,FORECAST.ETS.SEASONALITY,FORECAST.ETS.STAT,FORECAST.LINEAR,FORMULATEXT,GAMMA,GAMMA.DIST,GAMMA.INV,GAMMALN.PRECISE,GAUSS,HSTACK,HYPGEOM.DIST,IFNA,IFS,IMCOSH,IMCOT,IMCSC,IMCSCH,IMSEC,IMSECH,IMSINH,IMTAN,ISFORMULA,ISOMITTED,ISOWEEKNUM,LAMBDA,LET,LOGNORM.DIST,LOGNORM.INV,MAKEARRAY,MAP,MAXIFS,MINIFS,MODE.MULT,MODE.SNGL,MUNIT,NEGBINOM.DIST,NORM.DIST,NORM.INV,NORM.S.DIST,NORM.S.INV,NUMBERVALUE,PDURATION,PERCENTILE.EXC,PERCENTILE.INC,PERCENTRANK.EXC,PERCENTRANK.INC,PERMUTATIONA,PHI,POISSON.DIST,PQSOURCE,PYTHON_STR,PYTHON_TYPE,PYTHON_TYPENAME,QUARTILE.EXC,QUARTILE.INC,QUERYSTRING,RANDARRAY,RANK.AVG,RANK.EQ,REDUCE,RRI,SCAN,SEC,SECH,SEQUENCE,SHEET,SHEETS,SKEW.P,SORTBY,STDEV.P,STDEV.S,SWITCH,T.DIST,T.DIST.2T,T.DIST.RT,T.INV,T.INV.2T,T.TEST,TAKE,TEXTAFTER,TEXTBEFORE,TEXTJOIN,TEXTSPLIT,TOCOL,TOROW,UNICHAR,UNICODE,UNIQUE,VAR.P,VAR.S,VSTACK,WEBSERVICE,WEIBULL.DIST,WRAPCOLS,WRAPROWS,XLOOKUP,XOR,Z.TEST`.split(`,`),vu=[`%`],yu=`+,-,*,/,:,=,<>,>=,>,<=,<,^,&`.split(`,`).concat(vu);function bu(e,t=R){e=Tt(e);let n=new It(e),r=[],i=St.test(e)?Fu:Iu;for(;!n.isOver();){let e=Lu(n)||i(n)||Du(n,t)||Eu(n,t)||Tu(n)||Cu(n)||Ou(n)||ju(n)||xu(n)||Ru(n)||Au(n,t)||Pu(n);e||={type:`UNKNOWN`,value:n.shift()},r.push(e)}return r}function xu(e){return e.current===`?`?(e.shift(),{type:`DEBUGGER`,value:`?`}):null}let Su={"(":{type:`LEFT_PAREN`,value:`(`},")":{type:`RIGHT_PAREN`,value:`)`}};function Cu(e){return e.current===`(`||e.current===`)`?Su[e.shift()]:null}let wu={"{":{type:`LEFT_BRACE`,value:`{`},"}":{type:`RIGHT_BRACE`,value:`}`}};function Tu(e){return e.current===`{`||e.current===`}`?wu[e.shift()]:null}function Eu(e,t){return e.current===t.formulaArgSeparator?{type:`ARG_SEPARATOR`,value:e.shift()}:null}function Du(e,t){let n=t.formulaArgSeparator===`;`?`\\`:`;`;return n&&e.current===n?(e.shift(),{type:`ARRAY_ROW_SEPARATOR`,value:n}):null}function Ou(e){for(let t of yu)if(e.currentStartsWith(t))return e.advanceBy(t.length),{type:`OPERATOR`,value:t};return null}let ku=new Set(`0123456789`);function Au(e,t){if(!ku.has(e.current)&&e.current!==t.decimalSeparator)return null;let n=e.remaining().match(Zi(t.decimalSeparator));return n?(e.advanceBy(n[0].length),{type:`NUMBER`,value:n[0]}):null}function ju(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 Mu=/\p{L}|\p{N}|_|\.|!|\$/u,Nu=new Set(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.!$`);function Pu(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&&(Nu.has(e.current)||e.current.match(Mu));)t+=e.shift();if(t.length){let e=t;return Oc.test(e)?{type:`REFERENCE`,value:e}:{type:`SYMBOL`,value:e}}return null}function Fu(e){let t=``;for(;e.current===` `||e.current&&e.current.match(St);)t+=e.shift();return t?{type:`SPACE`,value:t}:null}function Iu(e){let t=``;for(;e.current===` `;)t+=e.shift();return t?{type:`SPACE`,value:t}:null}function Lu(e){let t=0;for(;e.current===`
|
|
13
13
|
`;)t++,e.shift();return t?{type:`SPACE`,value:`
|
|
14
14
|
`.repeat(t)}:null}function Ru(e){return e.currentStartsWith(A.InvalidReference)?(e.advanceBy(A.InvalidReference.length),{type:`INVALID_REFERENCE`,value:A.InvalidReference}):null}let zu=(e,t=()=>!0)=>[{goTo:e,guard:t}],Bu=(e,t=()=>!0)=>({goTo:e,guard:t}),Vu={0:{REFERENCE:zu(2),NUMBER:zu(4),SYMBOL:[Bu(3,e=>kc(e.value)),Bu(4,e=>Ac(e.value))]},3:{SPACE:zu(3),OPERATOR:zu(5,e=>e.value===`:`)},4:{SPACE:zu(4),OPERATOR:zu(6,e=>e.value===`:`)},2:{SPACE:zu(2),OPERATOR:zu(1,e=>e.value===`:`)},1:{SPACE:zu(1),NUMBER:zu(7),REFERENCE:zu(7,e=>Nc(e.value)),SYMBOL:zu(7,e=>jc(e.value)||Mc(e.value))},5:{SPACE:zu(5),SYMBOL:zu(7,e=>jc(e.value)),REFERENCE:zu(7,e=>Nc(e.value))},6:{SPACE:zu(6),NUMBER:zu(7),REFERENCE:zu(7,e=>Nc(e.value)),SYMBOL:zu(7,e=>Mc(e.value))},7:{}};function Hu(e){let t=0,n=Vu[0],r=``;for(;n!==void 0;){let i=e[t++];if(!i)return null;let a=n[i.type]?.find(e=>e.guard(i)),o=a?a.goTo:void 0;switch(o){case void 0:return null;case 7:return r+=i.value,e.splice(0,t),{type:`REFERENCE`,value:r};default:n=Vu[o],r+=i.value;break}}return null}function Uu(e,t=R){let n=bu(e,t),r=[];for(;n.length;)r.push(Hu(n)||n.shift());return r}function Wu(e,t,n){if(!t.startsWith(`=`))return t;let r=Uu(t);for(let t=1;t<r.length;t++){if(r[t].type!==`REFERENCE`)continue;let i=r[t].value,a=Gu(e,i,n).range;i!==a&&(r[t]={value:a,type:`REFERENCE`})}return pt(r.map(e=>e.value))}function Gu(e,t,n){let r=Pc(t).sheetName;if(r?!yl(r,n.sheetName.old):e!==n.sheetId)return{changeType:`NONE`,range:t};let i=Ju(t,r?n.sheetId:e);if(i.invalidXc)return{changeType:`NONE`,range:t};let a=n.applyChange(i);if(a.changeType===`NONE`||a.changeType===`REMOVE`)return{changeType:a.changeType,range:t};let o=Yc(a.range,e,Ku(n));return o===A.InvalidReference?{changeType:`REMOVE`,range:o}:{changeType:a.changeType,range:o}}function Ku(e){return t=>t===e.sheetId?e.sheetName.current:``}function qu(e){return{numberOfRows:2**53-1,numberOfCols:2**53-1}}function Ju(e,t){return Oc.test(e)?Gc({xc:e,sheetId:t},qu):Kc(e)}let Yu=`xMovingAverage`,Xu={exponential:`exp`,logarithmic:`log`,polynomial:`poly`,trailingMovingAverage:`movingAvg`};function Zu(e,t,n,r){let i=!1,a=[];for(let r in n){let o=n[r];if(o.labelCell){let e=ed(o.labelCell,t);o.labelCell!==e&&(i=!0,o={...o,labelCell:e})}let s=ed(o.dataRange,t);s===void 0||e.getRangeString(s,s.sheetId)===A.InvalidReference?(i=!0,o=void 0):s!==o.dataRange&&(i=!0,o={...o,dataRange:s}),a[r]=o}let o=r,s=ed(o,t);s!==o&&(i=!0,o=s);let c=a.filter(C);return{isStale:i,dataSets:c,labelRange:o}}function Qu(e,t,n){return n.map(n=>({dataRange:Xc(e,t,n.dataRange),labelCell:n.labelCell?Xc(e,t,n.labelCell):void 0}))}function $u(e,t,n){return n?Xc(e,t,n):void 0}function ed(e,t){if(!e)return;let n=t(e);switch(n.changeType){case`REMOVE`:return;default:return n.range}}function td(e,t,n,r){let i=[];for(let a of t){let{unboundedZone:t,sheetId:o,invalidSheetName:s,invalidXc:c}=e.getRangeFromSheetXC(n,a.dataRange);if(!(s||c))if(t.left!==t.right&&t.top!==t.bottom){if(t.right===void 0)continue;for(let n=t.left;n<=t.right;n++){let s={...t,left:n,right:n};i.push({...nd(e,o,s,r?{top:s.top,bottom:s.top,left:s.left,right:s.left}:void 0),backgroundColor:a.backgroundColor,rightYAxis:a.yAxisId===`y1`,customLabel:a.label,trend:a.trend})}}else i.push({...nd(e,o,t,r?{top:t.top,bottom:t.top,left:t.left,right:t.left}:void 0),backgroundColor:a.backgroundColor,rightYAxis:a.yAxisId===`y1`,customLabel:a.label,trend:a.trend})}return i}function nd(e,t,n,r){if(n.left!==n.right&&n.top!==n.bottom)throw Error(`Zone should be a single column or row: ${hn(n)}`);if(r){let i=hn(n),a=hn(r);return{labelCell:e.getRangeFromSheetXC(t,a),dataRange:e.getRangeFromSheetXC(t,i)}}else return{labelCell:void 0,dataRange:e.getRangeFromSheetXC(t,hn(n))}}function rd(e,t){let n=t.labelCell?.zone,r=t.dataRange.zone;if(n){let{numberOfRows:e,numberOfCols:t}=On(r);e===1?r={...r,left:r.left+1}:t===1&&(r={...r,top:r.top+1})}let i=Wc({...t.dataRange,zone:r},e.getSheetSize),a={};t.customLabel?a={text:t.customLabel}:t.labelCell&&(a={reference:e.getRangeString(t.labelCell,`forceSheetReference`,{useBoundedReference:!0})});let o;return t.trend?.type&&(o={type:t.trend.type===`polynomial`&&t.trend.order===1?`linear`:Xu[t.trend.type],color:t.trend.color,order:t.trend.order?Math.min(t.trend.order,6):void 0,window:t.trend.window||2}),{label:a,range:e.getRangeString(i,`forceSheetReference`,{useBoundedReference:!0}),backgroundColor:t.backgroundColor,rightYAxis:t.rightYAxis,trend:o}}function id(e,t,n){if(!t)return;let r={...t.zone};n&&t.zone.bottom>t.zone.top&&(r.top+=1);let i=Wc({...t,zone:r},e.getSheetSize);return e.getRangeString(i,`forceSheetReference`,{useBoundedReference:!0})}function ad(e,t,n){let r;if(t.labelRange){let{changeType:i,range:a}=Gu(e,t.labelRange,n);i!==`REMOVE`&&(r=a)}let i=[];for(let r of t.dataSets){let t={...r},{changeType:a,range:o}=Gu(e,r.dataRange,n);a!==`REMOVE`&&(t.dataRange=o,i.push(t))}return{...t,dataSets:i,labelRange:r}}function od(e){return e&&kr(e)<.3?`#FFFFFF`:`#000000`}function sd(e){return e&&kr(e)<.3?`#C8C8C8`:`#666666`}function cd(e){return e.dataSets&&(e.dataSets.find(e=>!Oc.test(e.dataRange))!==void 0||e.dataSets.map(e=>ln(e.dataRange)).some(e=>e.top!==e.bottom&&zn(e)))?`InvalidDataSet`:`Success`}function ld(e){return e.labelRange&&!Oc.test(e.labelRange||``)?`InvalidLabelRange`:`Success`}function ud(e,t,n){if(!n||!e)return!1;if(!t)return!0;let r=Vn(t.dataRange.zone);return!(Vn(e.zone)<r)}function dd(e,t){let{x:n,y:r}=e.getMainViewportCoordinates(),{scrollX:i,scrollY:a}=e.getActiveSheetScrollInfo(),{width:o,height:s}=e.getVisibleRect(e.getActiveMainViewport());return{x:n+i+Math.max(0,(o-t.width)/2),y:r+a+Math.max(0,(s-t.height)/2)}}function fd(e){let t=!1,n=!1;if(`horizontal`in e&&e.horizontal)return{useLeftAxis:!0,useRightAxis:!1};for(let r of e.dataSets||[])r.yAxisId===`y1`?n=!0:t=!0;return t||=!n,{useLeftAxis:t,useRightAxis:n}}function pd(e,t,n=!1){return(r,i)=>{let a=e?.[i];return md({format:a,locale:t},n)(r)}}function md(e,t=!1){return n=>{if(n=Number(n),isNaN(n))return n;let{locale:r,format:i}=e;return _d(t?hs({value:n,format:i},r):z(n,{locale:r,format:!i&&Math.abs(n)>=1e3?`#,##`:i}))}}let hd=[{value:`left`,label:k(`Left`)},{value:`right`,label:k(`Right`)}];function gd(e,t){let n=[],r=Pt(t.map(e=>e.data.length));for(let t=0;t<=r;t++)n.push(e.next());return n}function _d(e,t=20){return e?e.length>t?e.substring(0,t)+`…`:e:``}function vd(e){return e===`x1`||e===`xMovingAverage`}let yd={id:`chartShowValuesPlugin`,afterDatasetsDraw(e,t,n){if(!n.showValues||!e._metasets?.[0]?.data)return;let r=e.ctx;switch(r.save(),r.textAlign=`center`,r.textBaseline=`middle`,r.miterLimit=1,n.type){case`pie`:wd(e,n,r);break;case`line`:case`scatter`:case`combo`:case`waterfall`:case`radar`:xd(e,n,r);break;case`bar`:n.horizontal?Cd(e,n,r):xd(e,n,r);break;case`pyramid`:Cd(e,n,r);break;case`calendar`:Sd(e,n,r);break;case`funnel`:Cd(e,n,r);break}r.restore()}};function bd(e,t,n,r){r.lineWidth=3,r.strokeText(e,t,n),r.lineWidth=1,r.fillText(e,t,n)}function xd(e,t,n){let r={};for(let i of e._metasets){if(vd(i.xAxisID)||i.hidden)continue;let a=e.scales[i.yAxisID];for(let o=0;o<i._parsed.length;o++){let s=i._parsed[o],c=Number(e.config.type===`radar`?s.r:s.y);if(isNaN(c))continue;let l=i.data[o],u=l.x,d=0;if(e.config.type===`line`||e.config.type===`radar`)d=c<0?l.y+10:l.y-10;else{let e=a.getPixelForValue(0),t=Math.abs(e-l.y),n=globalThis.Chart?.defaults.font.size??12;d=t<n?c<0?e+n/2:e-n/2:c<0?l.y-l.height/2:l.y+l.height/2}r[u]||(r[u]=[]);for(let e of r[u]||[])Math.abs(e-d)<13&&(d=c<0?e+13:e-13);r[u].push(d),n.fillStyle=l.options.backgroundColor,n.strokeStyle=t.background(Number(c),i,o)||`#ffffff`,bd(t.callback(Number(c),i,o),u,d,n)}}}function Sd(e,t,n){let r=e.chartArea.bottom,i=e.chartArea.top;for(let a of e._metasets){if(vd(a.xAxisID)||a.hidden)continue;let o=e.scales[a.yAxisID];for(let s=0;s<a._parsed.length;s++){let c=a._parsed[s],l=Number(e.config.type===`radar`?c.r:c.y);if(isNaN(l))continue;let u=a.data[s],d=u.x,f=0,p=o.getPixelForValue(0),m=Math.abs(p-u.y),h=globalThis.Chart?.defaults.font.size??12;f=m<h?l<0?p+h/2:p-h/2:l<0?u.y-u.height/2:u.y+u.height/2,f=Math.min(f,r),f=Math.max(f,i),n.strokeStyle=u.options.backgroundColor,n.fillStyle=t.background(Number(l),a,s)||`#ffffff`;let g=t.callback(Number(l),a,s),_=n.measureText(g);_.actualBoundingBoxAscent+_.actualBoundingBoxDescent+2>Math.abs(u.height)-2||bd(g,d,f,n)}}}function Cd(e,t,n){let r={};for(let i of e._metasets){if(vd(i.xAxisID))return;let a=e.scales[i.xAxisID].getPixelForValue(0);for(let e=0;e<i._parsed.length;e++){let o=Number(i._parsed[e].x);if(isNaN(o))continue;let s=t.callback(o,i,e),c=i.data[e],l=c.y,u=Dl(n,s,{fontSize:globalThis.Chart?.defaults.font.size??12},`px`),d=Math.abs(c.x-a),f;f=d<u?o<0?a-u/2-3:a+u/2+3:o<0?c.x+c.width/2:c.x-c.width/2,r[l]||(r[l]=[]);for(let e of r[l])Math.abs(e-f)<u&&(f=o<0?e-u-3:e+u+3);r[l].push(f),n.strokeStyle=c.options.backgroundColor,n.fillStyle=t.background(Number(o),i,e)||`#ffffff`,bd(s,f,l,n)}}}function wd(e,t,n){for(let r of e._metasets)for(let e=0;e<r._parsed.length;e++){let i=Number(r._parsed[e]);if(isNaN(i)||i===0)continue;let a=r.data[e],{startAngle:o,endAngle:s,innerRadius:c,outerRadius:l}=a,u=(o+s)/2,d=(c+l)/2,f=a.x+d*Math.cos(u),p=a.y+d*Math.sin(u),m=t.callback(i,r,e),h=globalThis.Chart?.defaults.font.size??12,g=Dl(n,m,{fontSize:h},`px`),_=l-c;if(g>=_||_<h)continue;let v=s-o,y=2*d*Math.tan(v/2);if(v<Math.PI/2&&(g>=y||y<h))continue;let ee=t.background(Number(i),r,e);n.fillStyle=od(ee),n.strokeStyle=ee||`#ffffff`,bd(m,f,p,n)}}let Td={showHeaders:!0,headerDesign:{align:`center`,fillColor:`#808080`,bold:!0,fontSize:15},showValues:!0,showLabels:!0,valuesDesign:{align:`left`,verticalAlign:`bottom`,fontSize:12},coloringOptions:{type:`categoryColor`,colors:[],useValueBasedGradient:!0}},Ed={second:1e3,minute:1e3*60,hour:1e3*3600,day:1e3*3600*24,month:1e3*3600*24*30,year:1e3*3600*24*365},Dd={inSeconds:function(e){return Math.floor(e/Ed.second)},inMinutes:function(e){return Math.floor(e/Ed.minute)},inHours:function(e){return Math.floor(e/Ed.hour)},inDays:function(e){return Math.floor(e/Ed.day)},inMonths:function(e){return Math.floor(e/Ed.month)},inYears:function(e){return Math.floor(e/Ed.year)}},Od=/^((d|dd|m|mm|yyyy|yy|hh|h|ss|a)(-|:|\s|\/))*(d|dd|m|mm|yyyy|yy|hh|h|ss|a)$/i;function kd(e,t,n){let r=Ad(t),i=Md(e,r,n),a={};return i&&(a[i]=r),{parser:r,displayFormats:a,unit:i??!1,tooltipFormat:r}}function Ad(e){let t=e.indexOf(`h`);return e=t>=0?e.slice(0,t).replace(/m/g,`M`)+e.slice(t):e.replace(/m/g,`M`),e.includes(`a`)||(e=e.replace(/h/g,`H`)),e}function jd(e){return e.includes(`s`)?`second`:e.includes(`m`)?`minute`:e.includes(`h`)||e.includes(`H`)?`hour`:e.includes(`d`)?`day`:e.includes(`M`)?`month`:`year`}function Md(e,t,n){let r=e.map(e=>Ci(e,n)?.jsDate);if(r.some(e=>e===void 0)||e.length<2)return;let i=r.map(e=>e.getTime()),a=Pt(i)-Ft(i),o=jd(t);return Ed.second>=Ed[o]&&Dd.inSeconds(a)<180?`second`:Ed.minute>=Ed[o]&&Dd.inMinutes(a)<180?`minute`:Ed.hour>=Ed[o]&&Dd.inHours(a)<96?`hour`:Ed.day>=Ed[o]&&Dd.inDays(a)<90?`day`:Ed.month>=Ed[o]&&Dd.inMonths(a)<36?`month`:`year`}function Nd(e,t){let n={},{trendDataSetsValues:r,locale:i,axisFormats:a}=t,o={stacked:e.stacked,locale:i};if(e.horizontal)n.x=Gd(e,`bottom`,`values`,{...o,format:a?.x}),n.y=Gd(e,`left`,`labels`,o);else{n.x=Gd(e,`bottom`,`labels`,o);let t={...o,format:a?.y};n.y=Gd(e,`left`,`values`,t);let r={...o,format:a?.y1};n.y1=Gd(e,`right`,`values`,r)}if(n=bt(n),r&&r.length&&r.some(C)){let e=Math.max(...r.map(e=>e?.length||0));n.x1={...n.x,labels:Array(e).fill(``),offset:!1,display:!1},n[Yu]={...n.x,offset:!0,display:!1}}return n}function Pd(e,t){let n=t.map(e=>e.label||``),r=od(e.background);return{y:{title:Wd(e.axesDesign?.y),stacked:!0,min:0,max:n.length,ticks:{stepSize:.5,color:r,callback:function(e,t,r){if(t%2!=0)return n[Math.floor((t-1)/2)]}},grid:{display:!1},border:{display:!1}},x:{title:Wd(e.axesDesign?.x),stacked:!0,grid:{display:!1},position:`top`,ticks:{color:r},border:{display:!1}}}}function Fd(e,t){let{dataSetsValues:n}=t;if(!n.length||e.legendPosition===`none`)return;let r=n.flatMap(e=>e.data).filter(C),i=Math.min(...r),a=Math.max(...r),o=[];return o=typeof e.colorScale==`object`?[e.colorScale.minColor,e.colorScale.midColor,e.colorScale.maxColor].filter(C):[...ri[e.colorScale??`oranges`]],{position:e.legendPosition===`right`?`right`:`left`,colorScale:o,fontColor:od(e.background),minValue:i,maxValue:a,locale:t.locale}}function Id(e,t){let{locale:n,axisType:r,trendDataSetsValues:i,labels:a,axisFormats:o}=t,s=o?.x,c=e.stacked,l={x:Gd(e,`bottom`,`labels`,{locale:n}),y:Gd(e,`left`,`values`,{locale:n,stacked:c,format:o?.y}),y1:Gd(e,`right`,`values`,{locale:n,stacked:c,format:o?.y1})};if(l=bt(l),r===`time`&&a&&s){let e={type:`time`,time:kd(a,s,n)};Object.assign(l.x,e),l.x.ticks.maxTicksLimit=15,delete l?.x?.ticks?.callback}else r===`linear`&&(l.x.type=`linear`,l.x.ticks.callback=e.humanize?e=>hs({value:e,format:s},n):e=>z(e,{format:s,locale:n}));if(i&&i.length&&i.some(C)&&(l.x1={...l.x,display:!1},l[Yu]={...l.x,display:!1},r===`category`||r===`time`)){let e=Math.max(...i.map(e=>e?.length||0));l.x1.type=`category`,l.x1.labels=S(0,e).map(e=>e.toString()),l.x1.offset=!1,l[Yu].type=`category`,l[Yu].offset=!1}return l}function Ld(e,t){let n=Id(e,t);return{...n,x:{...n.x,grid:{display:!0}}}}function Rd(e,t){let{locale:n,axisFormats:r}=t,i=r?.y||r?.y1;e.dataSets;let a={x:{...Gd(e,`bottom`,`labels`,{locale:n}),grid:{display:!1}},y:{position:e.verticalAxisPosition,ticks:{color:od(e.background),callback:md({locale:n,format:i},e.humanize)},grid:{lineWidth:e=>e.tick.value===0?2:1},title:Wd(e.axesDesign?.y)}},o=a?.y||a?.y1;return o&&(o.grid={lineWidth:e=>e.tick.value===0?2:1}),a}function zd(e,t){let{dataSetsValues:n}=t,r=Nd(e,t),i=r.x.ticks.callback;r.x.ticks.callback=e=>i(Math.abs(e));let a=Math.max(...n.map(e=>Math.max(...e.data.map(Math.abs))));return r.x.suggestedMin=-a,r.x.suggestedMax=a,r}function Bd(e,t){let{locale:n,axisFormats:r,dataSetsValues:i}=t,a=Math.min(...i.map(e=>Math.min(...e.data.filter(e=>!isNaN(e)))));return{r:{beginAtZero:!0,ticks:{callback:md({format:r?.r,locale:n},e.humanize),backdropColor:e.background||`#FFFFFF`},pointLabels:{color:od(e.background),callback:e=>_d(e)},suggestedMin:a<0?a-1:0}}}function Vd(e,t){let{locale:n,axisFormats:r,availableRegions:i}=t,a=Jd(e.legendPosition),o=e.region?i.find(t=>t.id===e.region):i[0],s=r?.y||r?.y1;return{projection:{projection:Ud(o?.defaultProjection||`mercator`),axis:`x`},color:{axis:`x`,display:e.legendPosition!==`none`,border:{color:fe},grid:{color:fe},ticks:{color:od(e.background),callback:md({locale:n,format:s},e.humanize)},legend:{position:a,align:a.includes(`right`)?`left`:`right`,margin:qd(e)},interpolate:Kd(e.colorScale??he),missing:e.missingValueColor||`#ffffff`}}}function Hd(e,t){let n=t.dataSetsValues[0];return{x:{display:!1},y:{grid:{offset:!1},ticks:{callback:function(e){return _d(this.getLabelForValue(e))}},border:{display:!1}},percentages:{position:`right`,border:{display:!1},ticks:{callback:function(e,r,i){let a=n.data?.[r],o=n.data?.[0];return!o||a===void 0?``:z(a/o,{format:`0%`,locale:t.locale})}},grid:{display:!1}}}}function Ud(e){return e===`conicConformal`?globalThis.ChartGeo.geoConicConformal().rotate([100,0]):e}function Wd(e){if(e?.title?.text){let{text:t,color:n,align:r,italic:i,bold:a}=e.title;return{display:!0,text:t,color:n,font:{style:i?`italic`:`normal`,weight:a?`bold`:`normal`,size:e.title.fontSize??12},align:r===`left`?`start`:r===`right`?`end`:`center`}}}function Gd(e,t,n,r){let{useLeftAxis:i,useRightAxis:a}=fd(e);if(t===`left`&&!i||t===`right`&&!a)return;let o=od(e.background),s;if(s=t===`bottom`?e.axesDesign?.x:t===`left`?e.axesDesign?.y:e.axesDesign?.y1,n===`values`){let n=!(t===`right`&&i);return{position:t,title:Wd(s),grid:{display:n},beginAtZero:!0,stacked:r?.stacked,ticks:{color:o,callback:md(r,e.humanize)}}}else return{ticks:{padding:5,color:o,callback:function(e,t,n){return _d(this.getLabelForValue(e))}},grid:{display:!1},stacked:r?.stacked,title:Wd(s)}}function Kd(e,t=0,n=1){if(t===n){let t=e.midColor??e.minColor;return e=>t}let r=[{value:t,color:e.minColor}];return e.midColor&&r.push({value:(t+n)/2,color:e.midColor}),r.push({value:n,color:e.maxColor}),ai(r)}function qd(e){switch(e.legendPosition){case`top`:case`right`:return{top:e.title.text?45:15,left:20,right:20};case`bottom`:case`left`:case`none`:return{left:20,right:20,bottom:10}}}function Jd(e){switch(e){case`top`:return`top-left`;case`right`:return`top-right`;case`bottom`:return`bottom-right`;case`left`:return`bottom-left`;case`none`:return`bottom-left`}}let Yd=`nullValue`;function Xd(e,t){let{dataSetsValues:n}=t,r=[],i=_f(e,n.length),a=[];for(let o in n){let{label:s,data:c,hidden:l}=n[o];s=e.dataSets?.[o].label||s;let u=i.next(),d={label:s,data:c,hidden:l,borderColor:e.background||`#FFFFFF`,borderWidth:+!!e.stacked,backgroundColor:u,yAxisID:e.horizontal?`y`:e.dataSets?.[o].yAxisId||`y`,xAxisID:`x`,barPercentage:.9,categoryPercentage:n.length>1?.8:1,borderRadius:2};r.push(d);let f=e.dataSets?.[o].trend,p=t.trendDataSetsValues?.[o];!f?.display||e.horizontal||!p||a.push(hf(d,f,p))}return r.push(...a),r}function Zd(e,t){let{labels:n,dataSetsValues:r}=t,i=r.map(e=>e.data).flat().filter(C),a=Math.max(...i),o=Math.min(...i),s=Kd(e.colorScale??he,o,a),c=[];for(let t of r)c.push({label:t.label,data:t.data.map(e=>1),backgroundColor:t.data.map(t=>t===void 0?e.missingValueColor||`#00000000`:s(t)),borderColor:e.background||`#FFFFFF`,borderSkipped:!1,borderWidth:1,barPercentage:1,categoryPercentage:1,values:t.data});return{labels:n,datasets:c}}function Qd(e,t){let{dataSetsValues:n,labels:r}=t,i=e.negativeValuesColor||`#EA6175`,a=e.positiveValuesColor||`#4EA7F2`,o=e.subTotalValuesColor||`#AAAAAA`,s=[],c=[],l={label:``,data:c,backgroundColor:s},u=[],d=0;for(let t of n)if(!t.hidden){for(let l=0;l<t.data.length;l++){let f=t.data[l];if(u.push(r[l]),isNaN(Number(f))){c.push([d,d]),s.push(``);continue}c.push([d,f+d]);let p=f>=0?a:i;l===0&&t===n[0]&&e.firstValueAsSubtotal&&(p=o),s.push(p),d+=f}e.showSubTotals&&(u.push(k(`Subtotal`)),c.push([0,d]),s.push(o))}return{datasets:[l],labels:u}}function $d(e,t){let{dataSetsValues:n,axisType:r,labels:i}=t,a=[],o=!!e.fillArea,s=!!e.stacked,c=[],l=_f(e,n.length);for(let u=0;u<n.length;u++){let{label:d,data:f,hidden:p}=n[u];d=e.dataSets?.[u].label||d;let m=l.next();r&&[`linear`,`time`].includes(r)&&(f=f.map((e,t)=>({x:i[t]||void 0,y:e})));let h={label:d,data:f,hidden:p,tension:0,borderColor:m,backgroundColor:o?Br(m,Ae):m,pointBackgroundColor:m,fill:o?gf(u,s):!1,pointRadius:e.hideDataMarkers?0:3,yAxisID:e.dataSets?.[u].yAxisId||`y`};a.push(h);let g=e.dataSets?.[u].trend,_=t.trendDataSetsValues?.[u];!g?.display||!_||c.push(hf(h,g,_))}return a.push(...c),a}function ef(e,t){let n=$d(e,t);for(let e of n)vd(e.xAxisID)||(e.showLine=!1);return n}function tf(e,t){let{dataSetsValues:n}=t,r=[],i=gd(new ei(Math.max(0,...n.map(e=>e?.data?.length??0))),n);for(let{label:t,data:a,hidden:o}of n){if(o)continue;let n={label:t,data:a,borderColor:e.background||`#FFFFFF`,backgroundColor:i,hoverOffset:10};r.push(n)}return r}function nf(e,t){let{dataSetsValues:n}=t,r=[],i=_f(e,n.length),a=[],o=n.filter((t,n)=>(e.dataSets?.[n].type??`line`)===`bar`);for(let s=0;s<n.length;s++){let{label:c,data:l,hidden:u}=n[s];c=e.dataSets?.[s].label||c;let d=e.dataSets?.[s],f=i.next(),p=d?.type??`line`,m={label:c,data:l,hidden:u,borderColor:f,backgroundColor:f,yAxisID:e.dataSets?.[s].yAxisId||`y`,xAxisID:`x`,type:p,order:p===`bar`?n.length+s:s,pointRadius:e.hideDataMarkers?0:3};m.type===`bar`&&(m.barPercentage=.9,m.categoryPercentage=o.length>1?.8:1,m.borderRadius=2),r.push(m);let h=e.dataSets?.[s].trend,g=t.trendDataSetsValues?.[s];!h?.display||!g||a.push(hf(m,h,g))}return r.push(...a),r}function rf(e,t){let{dataSetsValues:n}=t,r=[],i=e.fillArea??!1,a=_f(e,n.length);for(let t=0;t<n.length;t++){let{label:o,data:s,hidden:c}=n[t];e.dataSets?.[t]?.label&&(o=e.dataSets[t].label);let l=a.next(),u={label:o,data:s,hidden:c,borderColor:l,backgroundColor:l,pointRadius:e.hideDataMarkers?0:3};i&&(u.backgroundColor=Br(l,Ae),u.fill=`start`),r.push(u)}return r}function af(e,t){let{availableRegions:n,dataSetsValues:r,labels:i}=t,a=e.region||n[0]?.id,o=a?t.getGeoJsonFeatures(a):void 0,s={outline:o,showOutline:!!o,data:[]};if(o&&a){let e={};if(r[0])for(let n=0;n<r[0].data.length;n++){if(!i[n]||r[0].data[n]===void 0)continue;let o=t.geoFeatureNameToId(a,i[n]);o&&(e[o]={value:r[0].data[n],label:i[n]})}for(let t of o)t.id&&s.data.push({feature:{...t,properties:{name:e[t.id]?.label}},value:e[t.id]?.value})}return[s]}function of(e,t){let n=t.dataSetsValues[0],r=t.labels;if(!n)return[];let{label:i,data:a}=n;return i=e.dataSets?.[0].label||i,[{label:i,data:a.map(e=>e<=0?[0,0]:[-e,e]),backgroundColor:sf(r,e.funnelColors),yAxisID:`y`,xAxisID:`x`,barPercentage:1,categoryPercentage:1,borderColor:e.background||`#FFFFFF`,borderWidth:3}]}function sf(e,t){let n=new ei(e.length,t);return e.map(()=>n.next())}function cf(e,t){let{dataSetsValues:n,labels:r}=t,i=ff(uf(n,r)),a=i[0]||[],o=new ei(a.length,e.groupColors||[]),s=a.map(e=>({label:e.label,color:o.next()})),c=[];for(let t=i.length-1;t>=0;t--){let n={groupColors:s,parsing:{key:`value`},data:i[t],borderColor:t=>{let n=t.type===`data`?t.raw:void 0;return!n||n.label===`nullValue`?ue:e.background||`#FFFFFF`},backgroundColor:e=>{let t=e.type===`data`?e.raw:void 0;if(!t||t.label===`nullValue`)return ue;let n=t.groups[0];return s.find(e=>e.label===n)?.color},hoverOffset:10};c.push(n)}return c}function lf(e,t){let n=[],r=Math.max(...e.map(e=>e.data.length));for(let i=0;i<r;i++){n[i]={};for(let t=0;t<e.length;t++){let r=e[t].data[i]===null?Yd:String(e[t].data[i]);n[i][t]=r}n[i].value=Number(t[i])}return n}function uf(e,t){return df(lf(e,t),0,e.length,[])}function df(e,t,n,r){if(t>=n)return[];let i=Object.groupBy(e,e=>e[t]);return Object.keys(i).map(e=>{let a=i[e]?.reduce((e,t)=>e+Number(t.value),0)||0,o=[...r,e];return{label:e,value:a,children:df(i[e]||[],t+1,n,[...r,e]),groups:o,depth:t}}).sort((e,t)=>t.value-e.value)}function ff(e){let t=[],n=[...e];for(;n.length>0;){let e=n.shift();e&&(t[e.depth]||(t[e.depth]=[]),t[e.depth].push(e),e.children&&n.push(...e.children))}return t}function pf(e,t){let{dataSetsValues:n,labels:r,locale:i,axisFormats:a}=t,o={locale:i,format:a?.y};if(n.length===0)return[];let s=uf(n,r).sort((e,t)=>t.value-e.value),c=vf(e,s),l=[],u=Math.max(...n.map(e=>e.data.length));for(let e=0;e<u;e++){l[e]={};for(let t=0;t<n.length;t++)l[e][t]=n[t].data[e]?String(n[t].data[e]):void 0;l[e].value=Number(r[e])}let d=e.showLabels??Td.showLabels,f=e.showValues??Td.showValues,p=e.coloringOptions||Td.coloringOptions,m;return p?.type===`colorScale`&&(m=yf(s,p)),[{data:[],tree:l,labels:{display:d||f,overflow:`hidden`,...mf(e.valuesDesign,Td.valuesDesign),formatter:e=>[d?e.raw.g:void 0,f?z(e.raw.v,o):void 0].filter(C)},captions:{display:e.showHeaders??Td.showHeaders,padding:6,...mf(e.headerDesign,Td.headerDesign)},key:`value`,groups:S(0,n.length).map(e=>String(e)),borderWidth:0,spacing:1,displayMode:`headerBoxes`,groupColors:c,backgroundColor:t=>{if(t.type!==`data`)return`transparent`;if(!t.raw.isLeaf)return e.headerDesign?.fillColor||Td.headerDesign?.fillColor;if(p.type===`colorScale`)return m?.(t.raw.v)||`#FF0000`;if(p.type===`categoryColor`)return bf(t,s,p,c);throw Error(`Unsupported coloring option type}`)}}]}function mf(e,t){let n=e=>{let t=e.element.options.backgroundColor;return kr(t)>.7?`#666666`:`#FFFFFF`};return{align:e?.align??t?.align,position:e?.verticalAlign??t?.verticalAlign,color:e?.color||n,hoverColor:e?.color||n,font:{weight:e?.bold??t?.bold?`bold`:`normal`,style:e?.italic??t?.italic?`italic`:`normal`,size:e?.fontSize??t?.fontSize}}}function hf(e,t,n){let r=Mr(e.backgroundColor);r.a=1;let i=t.color||Vr(jr(r),.5);return{type:`line`,xAxisID:t.type===`trailingMovingAverage`?Yu:`x1`,yAxisID:e.yAxisID,label:e.label?k(`Trend line for %s`,e.label):``,data:n,order:-1,showLine:!0,pointRadius:0,backgroundColor:i,borderColor:i,borderDash:[5,5],borderWidth:void 0,fill:!1,pointBackgroundColor:i}}function gf(e,t){return t?e===0?`origin`:`-1`:`origin`}function _f(e,t){return new ei(t,e.dataSets?.map(e=>e.backgroundColor)||[])}function vf(e,t){let n=e.coloringOptions?.type===`categoryColor`?e.coloringOptions.colors:[],r=new ei(t.length,n);return t.map(e=>({label:e.label,color:r.next()}))}function yf(e,t){if(e.length===0)return;let n=ff(e),r=n[n.length-1],i=Math.min(...r.map(e=>e.value)),a=Math.max(...r.map(e=>e.value));if(Number.isFinite(i)&&Number.isFinite(a)){let e=[{value:i,color:t.minColor}];if(t.midColor){let n=(i+a)/2;e.push({value:n,color:t.midColor})}return e.push({value:a,color:t.maxColor}),ai(e)}}function bf(e,t,n,r){let i=e.raw._data.children[0][0],a=r.find(e=>e.label===i)?.color;if(!a||!n.useValueBasedGradient)return a||`#FF0000`;let o=t.find(e=>e.label===i);if(!o||!o.children.length)return a;let s=ff(o.children),c=s[s.length-1],l=Math.max(...c.map(e=>e.value)),u=Math.min(...c.map(e=>e.value));return u===l||!isFinite(u)||!isFinite(l)?a:Vr(a,((Number(e.raw.v)||0)-l)/(u-l)*.5)}let xf={id:`sunburstHoverPlugin`,afterEvent(e,t,n){if(!n.enabled)return;let r=e.getActiveElements(),i=r.map(e=>({datasetIndex:e.datasetIndex,index:e.index}));for(let t of r){let n=e.data.datasets[t.datasetIndex].data[t.index];for(let t=0;t<e.data.datasets.length;t++){let r=e.data.datasets[t];for(let e=0;e<r.data.length;e++){let a=r.data[e];Sf(n.groups,a.groups)&&i.push({datasetIndex:t,index:e})}}}i=i.filter(t=>{let{datasetIndex:n,index:r}=t;return e.data.datasets[n].data[r].label!==Yd}),e.setActiveElements(i);for(let t of e.getSortedVisibleDatasetMetas())for(let e of t.data){let t=e.$context,{datasetIndex:n,index:r,dataset:a,raw:o}=t;if(o.label===`nullValue`)continue;let s=typeof a.backgroundColor==`function`?a.backgroundColor(t):a.backgroundColor;i.length&&!i.some(e=>e.datasetIndex===n&&e.index===r)?e.options.backgroundColor=Vr(s,.5):e.options.backgroundColor=s}}};function Sf(e,t){return t.length>e.length&&e.every((e,n)=>e===t[n])}let Cf={id:`sunburstLabelsPlugin`,afterDatasetsDraw(e,t,n){if(!n.showValues&&!n.showLabels||e.config.type!==`doughnut`)return;let r=e.ctx;wf(e,n,r)}};function wf(e,t,n){let r=t.style,i=r.fontSize||13,a=i+3;for(let o of e._metasets)for(let s=0;s<o._dataset.data.length;s++){let c=o._dataset.data[s];if(c.label===`nullValue`)continue;let l=[t.showLabels?c.label:void 0,t.showValues?t.callback(c.value,`y`):void 0].filter(C),u=o.data[s],{startAngle:d,endAngle:f,innerRadius:p,outerRadius:m,circumference:h}=u,g=u.options.offset/4,_=g*(1-Math.sin(Math.min(Math.PI,h||0)));p+=_,m+=_;let v=(d+f)/2,y=(p+m)/2,ee=(m-p)*.9,te=f-d;if((te>=Math.PI?m:Math.sin(te/2)*p*2)<l.length*a)continue;n.save();let ne={x:Math.cos(v)*g,y:Math.sin(v)*g},re=e.chartArea.left+e.chartArea.width/2+ne.x,ie=e.chartArea.top+e.chartArea.height/2+ne.y;n.translate(re,ie);let ae;v>Math.PI/2?(n.rotate(v-Math.PI),ae=-y):(ae=y,n.rotate(v));let oe=u.options.backgroundColor,se=kr(oe)>.7?`#666666`:`#FFFFFF`;n.fillStyle=r.textColor||se,n.textAlign=`center`,n.textBaseline=`middle`,n.font=Tl(i,r.bold,r.italic);let ce=-((l.length-1)*a)/2;for(let e=0;e<l.length;e++){let t=Ul(n,ee,l[e],r,`px`);n.fillText(t,ae,ce+e*a)}n.restore()}}let Tf={id:`waterfallLinesPlugin`,beforeDraw(e,t,n){if(!n.showConnectorLines)return;let r=e._metasets?.[0]?.data;if(!r)return;let i=e.ctx;i.save(),i.setLineDash([3,2]);for(let e=0;e<r.length;e++){let t=r[e];if(t.height===0)continue;let n=Df(r,e);if(!n)break;let a=Ef(t),o=Ef(n),s=t.$context.raw,c=s[1]-s[0],l=Math.round(c<0?a.bottom-1:a.top),u=Math.round(a.right),d=Math.round(o.left);i.strokeStyle=`#999`,i.beginPath(),i.moveTo(u+1,l+.5),i.lineTo(d,l+.5),i.stroke()}i.restore()}};function Ef(e){let t=e.base<e.y;return{left:e.x-e.width/2,right:e.x+e.width/2,bottom:t?e.base+e.height:e.y+e.height,top:t?e.base:e.y}}function Df(e,t){return e.find((e,n)=>n>t&&e.height!==0)}let Of={id:`zoomWindowPlugin`,afterDatasetsDraw:function(e,t,n){if(!n.getLowerBound||!n.getUpperBound)return;let{ctx:r,chartArea:{left:i,right:a,top:o,bottom:s}}=e,c=n.getLowerBound()??i,l=n.getUpperBound()??a;c>l&&([c,l]=[l,c]),c=Math.max(i,c),l=Math.min(a,l),c===i&&--c,l===a&&(l+=1),r.save(),r.fillStyle=`rgba(255,255,255,0.5)`,r.beginPath(),r.rect(i,s,c-i,o-s),r.rect(l,s,a-l,o-s),r.fill(),r.beginPath(),r.strokeStyle=`#bbb`,r.rect(c,s,l-c,o-s),r.stroke(),r.lineWidth=2,r.beginPath(),r.moveTo(c-3,(o+s)/2-7),r.lineTo(c-3,(o+s)/2+7),r.stroke(),r.beginPath(),r.moveTo(l+3,(o+s)/2-7),r.lineTo(l+3,(o+s)/2+7),r.stroke(),r.restore()}};ql.add(`chartShowValuesPlugin`,{register:e=>e.register(yd),unregister:e=>e.unregister(yd)}),ql.add(`waterfallLinesPlugin`,{register:e=>e.register(Tf),unregister:e=>e.unregister(Tf)}),ql.add(`funnelController`,{register:e=>e.register(eu()),unregister:e=>e.unregister(eu())}),ql.add(`funnelElement`,{register:e=>e.register(tu()),unregister:e=>e.unregister(tu())}),ql.add(`funnelTooltipPositioner`,{register:e=>e.Tooltip.positioners.funnelTooltipPositioner=ru,unregister:e=>e.Tooltip.positioners.funnelTooltipPositioner=void 0}),ql.add(`sunburstLabelsPlugin`,{register:e=>e.register(Cf),unregister:e=>e.unregister(Cf)}),ql.add(`sunburstHoverPlugin`,{register:e=>e.register(xf),unregister:e=>e.unregister(xf)}),ql.add(`chartColorScalePlugin`,{register:e=>e.register($l),unregister:e=>e.unregister($l)}),ql.add(`calendarController`,{register:e=>e.register(Ql()),unregister:e=>e.unregister(Ql())}),ql.add(`zoomWindowPlugin`,{register:e=>e.register(Of),unregister:e=>e.unregister(Of)});var kf=class extends t.Component{static template=`o-spreadsheet-ChartJsComponent`;static props={chartId:String,isFullScreen:{type:Boolean,optional:!0}};canvas=(0,t.useRef)(`graphContainer`);chart;currentRuntime;animationStore;currentDevicePixelRatio=window.devicePixelRatio;get background(){return this.chartRuntime.background}get canvasStyle(){return`background-color: ${this.background}`}get chartRuntime(){let e=this.env.model.getters.getChartRuntime(this.props.chartId);if(!(`chartJsConfig`in e))throw Error(`Unsupported chart runtime`);return e}setup(){this.shouldAnimate&&(this.animationStore=D(Zl)),(0,t.onMounted)(()=>{Yl();let e=this.chartRuntime;this.currentRuntime=e,this.createChart(b(e))}),(0,t.onWillUnmount)(this.unmount.bind(this)),(0,t.useEffect)(()=>{let e=this.chartRuntime;e===this.currentRuntime?this.currentDevicePixelRatio!==window.devicePixelRatio&&(this.currentDevicePixelRatio=window.devicePixelRatio,this.updateChartJs(b(this.currentRuntime))):(e.chartJsConfig.type===this.currentRuntime.chartJsConfig.type?this.updateChartJs(b(e)):(this.chart?.destroy(),this.createChart(b(e))),this.currentRuntime=e)})}unmount(){this.chart?.destroy()}get shouldAnimate(){return this.env.model.getters.isDashboard()}createChart(e){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);let t=e.chartJsConfig;if(this.shouldAnimate&&this.animationStore){let e=this.env.model.getters.getChart(this.props.chartId)?.type;e&&this.animationStore.animationPlayed[this.animationChartId]!==e&&(t=this.enableAnimationInChartData(t),this.animationStore.disableAnimationForChart(this.animationChartId,e))}let n=this.canvas.el.getContext(`2d`);this.chart=new globalThis.Chart(n,t)}updateChartJs(e){let t=e.chartJsConfig;if(this.shouldAnimate){let e=this.env.model.getters.getChart(this.props.chartId)?.type;e&&this.hasChartDataChanged()&&this.animationStore&&(t=this.enableAnimationInChartData(t),this.animationStore.disableAnimationForChart(this.animationChartId,e))}t.data&&t.data.datasets?(this.chart.data=t.data,t.options?.plugins?.title&&(this.chart.config.options.plugins.title=t.options.plugins.title)):this.chart.data.datasets=[],this.chart.config.options=t.options,this.chart.update()}hasChartDataChanged(){return!w(this.getChartDataInRuntime(this.currentRuntime),this.getChartDataInRuntime(this.chartRuntime))}enableAnimationInChartData(e){return{...e,options:{...e.options,animation:{animateRotate:!0}}}}getChartDataInRuntime(e){let t=e.chartJsConfig.data;return{labels:t.labels,dataset:t.datasets.map(e=>({data:e.data,label:e.label,tree:e.tree}))}}get animationChartId(){return this.props.isFullScreen?this.props.chartId+`-fullscreen`:this.props.chartId}},Af=class{sheetId;title;getters;humanize;constructor(e,t,n){this.title=e.title,this.sheetId=t,this.getters=n,this.humanize=e.humanize??!0}static validateChartDefinition(e,t){throw Error(`This method should be implemented by sub class`)}static transformDefinition(e,t,n){throw Error(`This method should be implemented by sub class`)}static getDefinitionFromContextCreation(e){throw Error(`This method should be implemented by sub class`)}getCommonDataSetAttributesForExcel(e,t,n){return{dataSets:t.map(e=>rd(this.getters,e)).filter(e=>e.range!==``&&e.range!==A.InvalidReference),labelRange:id(this.getters,e,n)}}};function jf(e,t,n,r,i){if(!e)return``;if(n===`text`||t?.type!==`number`||e.type!==`number`)return r?hs(e,i):e.formattedValue;let{value:a,format:o}=e;return n===`progress`?(a=t.value/a,o=`0.0%`):(a=Math.abs(t.value-a),n===`percentage`&&a!==0&&(a/=e.value),n===`percentage`&&(o=`0.0%`),o||(a=Math.round(a*100)/100)),r?hs({value:a,format:o},i):z(a,{format:o,locale:i})}function Mf(e,t,n){return e?t?hs(e,n):e.formattedValue??String(e.value??``):``}function Nf(e,t,n,r,i){if(t===`text`||t===`progress`||e?.type!==`number`||n?.type!==`number`)return;let a=n.value-e.value;if(a>0)return r;if(a<0)return i}function Pf(e,t,n){if(n===`text`||e?.type!==`number`||t?.type!==`number`)return`neutral`;let r=t.value-e.value;return r>0?`up`:r<0?`down`:`neutral`}function Ff(e){return e.keyValue&&!Oc.test(e.keyValue)?`InvalidScorecardKeyValue`:`Success`}function If(e){return e.baseline&&!Oc.test(e.baseline)?`InvalidScorecardBaseline`:`Success`}let Lf=globalThis.Path2D,Rf=Lf&&new Lf(`M8.6 4.8a.5.5 0 0 1 0 .75l-3.9 3.9a.5 .5 0 0 1 -.75 0l-3.8 -3.9a.5 .5 0 0 1 0 -.75l.4-.4a.5.5 0 0 1 .75 0l2.3 2.4v-5.7c0-.25.25-.5.5-.5h.6c.25 0 .5.25.5.5v5.8l2.3 -2.4a.5.5 0 0 1 .75 0z`),zf=Lf&&new Lf(`M8.7 5.5a.5.5 0 0 0 0-.75l-3.8-4a.5.5 0 0 0-.75 0l-3.8 4a.5.5 0 0 0 0 .75l.4.4a.5.5 0 0 0 .75 0l2.3-2.4v5.8c0 .25.25.5.5.5h.6c.25 0 .5-.25.5-.5v-5.8l2.2 2.4a.5.5 0 0 0 .75 0z`);var Bf=class e extends Af{keyValue;keyDescr;baseline;baselineMode;baselineDescr;progressBar=!1;background;baselineColorUp;baselineColorDown;fontColor;humanize;type=`scorecard`;constructor(e,t,n){super(e,t,n),this.keyValue=Zc(n,t,e.keyValue),this.keyDescr=e.keyDescr,this.baseline=Zc(n,t,e.baseline),this.baselineMode=e.baselineMode,this.baselineDescr=e.baselineDescr,this.background=e.background,this.baselineColorUp=e.baselineColorUp??`#43C5B1`,this.baselineColorDown=e.baselineColorDown??`#EA6175`,this.humanize=e.humanize??!0}static validateChartDefinition(e,t){return e.checkValidations(t,Ff,If)}static getDefinitionFromContextCreation(e){return{background:e.background,type:`scorecard`,keyValue:e.range?.[0]?.dataRange,title:e.title||{text:``},baselineMode:De,baselineColorUp:Oe,baselineColorDown:ke,baseline:e.auxiliaryRange||``,humanize:e.humanize}}static transformDefinition(e,t,n){let r,i;if(t.baseline){let{changeType:i,range:a}=Gu(e,t.baseline,n);i!==`REMOVE`&&(r=a)}if(t.keyValue){let{changeType:r,range:a}=Gu(e,t.keyValue,n);r!==`REMOVE`&&(i=a)}return{...t,baseline:r,keyValue:i}}duplicateInDuplicatedSheet(t){let n=$u(this.sheetId,t,this.baseline),r=$u(this.sheetId,t,this.keyValue);return new e(this.getDefinitionWithSpecificRanges(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificRanges(this.baseline,this.keyValue)}getContextCreation(){return{...this,range:this.keyValue?[{dataRange:this.getters.getRangeString(this.keyValue,this.sheetId)}]:void 0,auxiliaryRange:this.baseline?this.getters.getRangeString(this.baseline,this.sheetId):void 0}}getDefinitionWithSpecificRanges(e,t,n){return{baselineColorDown:this.baselineColorDown,baselineColorUp:this.baselineColorUp,baselineMode:this.baselineMode,title:this.title,type:`scorecard`,background:this.background,baseline:e?this.getters.getRangeString(e,n||this.sheetId):void 0,baselineDescr:this.baselineDescr,keyValue:t?this.getters.getRangeString(t,n||this.sheetId):void 0,keyDescr:this.keyDescr,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges({applyChange:t}){let n=ed(this.baseline,t),r=ed(this.keyValue,t);return this.baseline===n&&this.keyValue===r?this:new e(this.getDefinitionWithSpecificRanges(n,r),this.sheetId,this.getters)}};function Vf(e,t,n=1){let r=t.getContext(`2d`);if(!r)throw Error(`Unable to retrieve 2D context from canvas`);let i=typeof globalThis.devicePixelRatio==`number`?globalThis.devicePixelRatio:1;t.width=i*e.canvas.width*n,t.height=i*e.canvas.height*n,r.scale(i*n,i*n);let a=e.canvas.width-20;if(r.fillStyle=e.canvas.backgroundColor,r.fillRect(0,0,e.canvas.width,e.canvas.height),e.title){r.font=e.title.style.font,r.fillStyle=e.title.style.color;let t=r.textBaseline;r.textBaseline=`middle`,r.fillText(Vl(r,e.title.text,a-e.title.position.x),e.title.position.x,e.title.position.y),r.textBaseline=t}if(e.baseline&&(r.font=e.baseline.style.font,r.fillStyle=e.baseline.style.color,Hl(r,e.baseline.text,e.baseline.position,e.baseline.style.underline,e.baseline.style.strikethrough)),e.baselineArrow&&e.baselineArrow.style.size>0&&Lf){r.save(),r.fillStyle=e.baselineArrow.style.color,r.translate(e.baselineArrow.position.x,e.baselineArrow.position.y);let t=e.baselineArrow.style.size/10;switch(r.scale(t,t),e.baselineArrow.direction){case`down`:r.fill(Rf);break;case`up`:r.fill(zf);break}r.restore()}if(e.baselineDescr){let t=e.baselineDescr;r.font=t.style.font,r.fillStyle=t.style.color,r.fillText(Vl(r,t.text,a-t.position.x),t.position.x,t.position.y)}if(e.key&&(r.font=e.key.style.font,r.fillStyle=e.key.style.color,Hl(r,Vl(r,e.key.text,a-e.key.position.x),e.key.position,e.key.style.underline,e.key.style.strikethrough)),e.keyDescr){let t=e.keyDescr;r.font=e.keyDescr?.style.font??t.style.font,r.fillStyle=t.style.color,r.fillText(Vl(r,t.text,a-t.position.x),t.position.x,t.position.y)}if(e.progressBar){if(r.fillStyle=e.progressBar.style.backgroundColor,r.beginPath(),r.roundRect(e.progressBar.position.x,e.progressBar.position.y,e.progressBar.dimension.width,e.progressBar.dimension.height,e.progressBar.dimension.height/2),r.fill(),r.fillStyle=e.progressBar.style.color,r.beginPath(),e.progressBar.value>0)r.roundRect(e.progressBar.position.x,e.progressBar.position.y,e.progressBar.dimension.width*Math.max(0,Math.min(1,e.progressBar.value)),e.progressBar.dimension.height,e.progressBar.dimension.height/2);else{let t=e.progressBar.dimension.width*Math.max(0,Math.min(1,-e.progressBar.value));r.roundRect(e.progressBar.position.x+e.progressBar.dimension.width-t,e.progressBar.position.y,t,e.progressBar.dimension.height,e.progressBar.dimension.height/2)}r.fill()}}function Hf(e,t){let n=``,r,i=t.getLocale();if(e.keyValue){let a={sheetId:e.keyValue.sheetId,col:e.keyValue.zone.left,row:e.keyValue.zone.top};r=t.getEvaluatedCell(a),n=Mf(r,e.humanize??!0,i)}let a,o=e.baseline;if(o){let e={sheetId:o.sheetId,col:o.zone.left,row:o.zone.top};a=t.getEvaluatedCell(e)}let{background:s,fontColor:c}=t.getStyleOfSingleCellChart(e.background,e.keyValue),l=jf(a,r,e.baselineMode,e.humanize??!0,i),u=e.baselineMode===`progress`&&$i(l,i)?N(l,i):0;return{title:{...e.title,text:e.title.text?t.dynamicTranslate(e.title.text):``},keyValue:n,keyDescr:e.keyDescr?.text?t.dynamicTranslate(e.keyDescr.text):``,baselineDisplay:l,baselineArrow:Pf(a,r,e.baselineMode),baselineColor:Nf(a,e.baselineMode,r,e.baselineColorUp,e.baselineColorDown),baselineDescr:e.baselineMode!==`progress`&&e.baselineDescr?.text?t.dynamicTranslate(e.baselineDescr.text):``,fontColor:c,background:s,baselineStyle:{...e.baselineMode!==`percentage`&&e.baselineMode!==`progress`&&o?t.getCellComputedStyle({sheetId:o.sheetId,col:o.zone.left,row:o.zone.top}):void 0,fontSize:e.baselineDescr?.fontSize,align:e.baselineDescr?.align},baselineDescrStyle:{textColor:e.baselineDescr?.color,...e.baselineDescr},keyValueStyle:{...e.keyValue?t.getCellComputedStyle({sheetId:e.keyValue.sheetId,col:e.keyValue.zone.left,row:e.keyValue.zone.top}):void 0,fontSize:e.keyDescr?.fontSize,align:e.keyDescr?.align},keyValueDescrStyle:{textColor:e.keyDescr?.color,...e.keyDescr},progressBar:e.baselineMode===`progress`?{value:u,color:u>0?e.baselineColorUp:e.baselineColorDown}:void 0}}let Uf=.05;function Wf(e,t){let n=e||``;return t&&n?` `+n:n}function Gf({width:e,height:t},n){return new Kf({width:e,height:t},n).computeDesign()}var Kf=class{runtime;context;width;height;constructor({width:e,height:t},n){if(this.runtime=n,this.width=e,this.height=t,typeof OffscreenCanvas>`u`)throw Error(`OffscreenCanvas is not supported in this environment`);let r=new globalThis.OffscreenCanvas(e,t).getContext(`2d`);if(!r)throw Error(`Unable to create scorecard measurement context`);this.context=r}computeDesign(){let e={canvas:{width:this.width,height:this.height,backgroundColor:this.backgroundColor}},t=this.getTextStyles(),n=0;if(this.title){let r,i;switch({height:n,width:i}=this.getFullTextDimensions(this.title,t.title.font),this.runtime.title.align){case`center`:r=(this.width-i)/2;break;case`right`:r=this.width-i-20;break;default:r=20}e.title={text:this.title,style:t.title,position:{x:r,y:10+n/2}}}let r=t.baselineArrow?.size??0,{height:i,width:a}=this.getTextDimensions(this.baseline,t.baselineValue.font);this.baseline||(i=this.getTextDimensions(this.baselineDescr,t.baselineDescr.font).height);let o=this.getTextDimensions(this.baselineDescr,t.baselineDescr.font).width,s;switch(this.runtime.baselineStyle?.align){case`right`:s=this.width-20-o-a;break;case`left`:s=20+r;break;default:s=(this.width-a-o+r)/2}if(this.baseline&&(e.baseline={text:this.baseline,style:t.baselineValue,position:{x:s,y:this.keyValue?this.height*(1-Uf*(this.runtime.progressBar?1:2)):this.height-(this.height-n-i)/2-10}},t.baselineArrow&&!this.runtime.progressBar&&(e.baselineArrow={direction:this.baselineArrow,style:t.baselineArrow,position:{x:e.baseline.position.x-r,y:e.baseline.position.y-(i+r)/2}})),e.baseline&&this.baselineDescr){let n={x:e.baseline.position.x+a,y:e.baseline.position.y};e.baselineDescr={text:this.baselineDescr,style:t.baselineDescr,position:n}}let c=0;this.runtime.progressBar&&(c=this.height*.05,e.progressBar={position:{x:40,y:this.height*(1-2*Uf)-i-c},dimension:{height:c,width:this.width-80},value:this.runtime.progressBar.value,style:{color:this.runtime.progressBar.color,backgroundColor:this.secondaryFontColor}});let{width:l,height:u}=this.getFullTextDimensions(this.keyValue,t.keyValue.font),d=this.getTextDimensions(this.keyDescr,t.keyDescr.font).width,f;switch(this.runtime.keyValueStyle?.align){case`right`:f=this.width-20-d-l;break;case`left`:f=20;break;default:f=(this.width-l-d)/2}if(this.keyValue&&(e.key={text:this.keyValue,style:t.keyValue,position:{x:Math.max(20,f),y:this.height*(.5-Uf*2)+10/2+(n+u/2)/2}}),e.key&&this.keyDescr){let n={x:e.key.position.x+l,y:e.key.position.y};e.keyDescr={text:this.keyDescr,style:t.keyDescr,position:n}}return e}get title(){return this.runtime.title.text??``}get keyValue(){return this.runtime.keyValue}get keyDescr(){return Wf(this.runtime.keyDescr,this.keyValue)}get baseline(){return this.runtime.baselineDisplay}get baselineDescr(){return Wf(this.runtime.baselineDescr,this.baseline)}get baselineArrow(){return this.runtime.baselineArrow}get backgroundColor(){return this.runtime.background}get secondaryFontColor(){return sd(this.backgroundColor)}getTextDimensions(e,t){this.context.font=t;let n=this.context.measureText(e);return{width:n.width,height:n.actualBoundingBoxAscent+n.actualBoundingBoxDescent}}getFullTextDimensions(e,t){this.context.font=t;let n=this.context.measureText(e);return{width:n.width,height:n.fontBoundingBoxAscent+n.fontBoundingBoxDescent}}getTextStyles(){let e=this.runtime.keyValueStyle?.fontSize??32,t=Math.floor(.9*e),n=this.runtime.baselineStyle?.fontSize??16,r=Math.floor(.9*n);return this.runtime.progressBar&&(n/=1.5),{title:{font:Tl(this.runtime.title.fontSize??14,this.runtime.title.bold,this.runtime.title.italic),color:this.runtime.title.color??this.secondaryFontColor},keyValue:{color:this.runtime.keyValueStyle?.textColor||this.runtime.fontColor,font:Tl(e,this.runtime.keyValueStyle?.bold,this.runtime.keyValueStyle?.italic),strikethrough:this.runtime.keyValueStyle?.strikethrough,underline:this.runtime.keyValueStyle?.underline},keyDescr:{color:this.runtime.keyValueDescrStyle?.textColor||this.runtime.fontColor,font:Tl(t,this.runtime.keyValueDescrStyle?.bold,this.runtime.keyValueDescrStyle?.italic),strikethrough:this.runtime.keyValueDescrStyle?.strikethrough,underline:this.runtime.keyValueDescrStyle?.underline},baselineValue:{font:Tl(n,this.runtime.baselineStyle?.bold,this.runtime.baselineStyle?.italic),strikethrough:this.runtime.baselineStyle?.strikethrough,underline:this.runtime.baselineStyle?.underline,color:this.runtime.baselineColor||this.runtime.baselineStyle?.textColor||this.secondaryFontColor},baselineDescr:{font:Tl(r,this.runtime.baselineDescrStyle?.bold,this.runtime.baselineDescrStyle?.italic),strikethrough:this.runtime.baselineDescrStyle?.strikethrough,underline:this.runtime.baselineDescrStyle?.underline,color:this.runtime.baselineDescrStyle?.textColor??this.secondaryFontColor},baselineArrow:this.baselineArrow===`neutral`||this.runtime.progressBar?void 0:{size:this.keyValue?.8*n:0,color:this.runtime.baselineColor||this.runtime.baselineStyle?.textColor||this.secondaryFontColor}}}};let qf=/Mac/i,Jf=!1;function Yf(){let e=document.createElement(`div`);e.setAttribute(`style`,`width:10px;height:1px;zoom:2;position:absolute;z-index:-10000`),document.body.appendChild(e),Jf=e.getBoundingClientRect().width!==20,document.body.removeChild(e)}(0,t.whenReady)(Yf);let Xf=[`Shift`,`Control`,`Alt`,`Meta`];function Zf(e,t){return e?!!t.target&&e.contains(t.target):!1}function Qf(e=1){let t=document.querySelector(`.o-grid-overlay`),n=t&&$f(t,e);if(!n)throw Error(`Can't find spreadsheet position`);return n}function $f(e,t){let n=e.closest(`.o-zoomable`),r,i=1;n?(r=n,i=Jf?t:1):r=e;let a=r.getBoundingClientRect();return{x:a.x*i,y:a.y*i,width:a.width*i,height:a.height*i}}function ep(e){return e.el?tp(e.el):{x:0,y:0,width:0,height:0}}function tp(e){let t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}function*np(e){if(yield e,e.hasChildNodes())for(let t of e.childNodes)yield*np(t)}function rp(){return Array.from(document.querySelectorAll(`.o-spreadsheet .o-menu`))}function ip(e){let{startElement:t,endElement:n,startSelectionOffset:r,endSelectionOffset:i}=ap(e);return{start:op(e,t,r),end:op(e,n,i)}}function ap(e){let t=document.getSelection();return{startElement:t.anchorNode||e,startSelectionOffset:t.anchorOffset,endElement:t.focusNode||e,endSelectionOffset:t.focusOffset}}function op(e,t,n){let r=0,i=np(e),a=i.next(),o=!0;for(;!a.done&&a.value!==t;)a.value.hasChildNodes()||a.value.textContent&&(r+=a.value.textContent.length),(a.value.nodeName===`P`||a.value.nodeName===`DIV`&&a.value!==e)&&(o?o=!1:r++),a=i.next();if(a.value!==t)return 0;if(!a.value.hasChildNodes())r+=n;else{let e=[...a.value.childNodes].slice(0,n);r+=e.reduce((t,n,r)=>{if(n.textContent!==null){let i=n.textContent.length;return n.nodeName===`P`&&r!==e.length-1&&i++,t+i}else return t},0)}return t.nodeName===`P`&&!o&&t.textContent===``&&r++,r}let sp=/^[a-zA-Z]$/;function cp(e,t=`key`){let n=``;Xf.includes(e.key)||(up(e)&&(n+=`Ctrl+`),e.altKey&&(n+=`Alt+`),e.shiftKey&&(n+=`Shift+`));let r=t===`key`?e.key:e.code;return n+=sp.test(r)?r.toUpperCase():r,n}function lp(){return!!qf.test(navigator.userAgent)}function up(e){return lp()||gp()?e.metaKey:e.ctrlKey}function dp(e){return e.button===1||up(e)&&e.button===0}function fp(e,t){let n=document.createElement(`a`);n.href=e,n.download=t,document.body.appendChild(n),n.click(),document.body.removeChild(n)}function pp(){return/Firefox/i.test(navigator.userAgent)}function mp(){return navigator.maxTouchPoints||1}function hp(){return/Android/i.test(navigator.userAgent)}function gp(){return/(iPad|iPhone|iPod)/i.test(navigator.userAgent)||navigator.platform===`MacIntel`&&mp()>1}function _p(){return/(webOS|BlackBerry|Windows Phone)/i.test(navigator.userAgent)}function vp(){return hp()||gp()||_p()}function yp(e,t,n){let r=e.model.getters.getViewportZoomLevel();if(n===void 0&&(n=Sp(t,r)),!n)return bp(t);let i=t.clientX-n.x,a=t.clientY-n.y,o=i/r,s=a/r;return{ev:t,clientX:t.clientX-i+o,clientY:t.clientY-a+s,offsetX:o,offsetY:s}}function bp(e){return{ev:e,clientX:e.clientX,clientY:e.clientY,offsetX:e.offsetX,offsetY:e.offsetY}}function xp(e,t){return{height:t.height*e,width:t.width*e,x:t.x*e,y:t.y*e}}function Sp(e,t){let n=e.target;return!n||!(`classList`in n)||!(n instanceof Element)?null:$f(n,t)}var Cp=class extends t.Component{static template=`o-spreadsheet-ScorecardChart`;static props={chartId:String,isFullScreen:{type:Boolean,optional:!0}};canvas=(0,t.useRef)(`chartContainer`);get runtime(){return this.env.model.getters.getChartRuntime(this.props.chartId)}get title(){let e=this.env.model.getters.getChartDefinition(this.props.chartId).title.text;return e?this.env.model.getters.dynamicTranslate(e):``}setup(){(0,t.useEffect)(this.createChart.bind(this),()=>{let e=this.canvas.el.getBoundingClientRect();return[e.width,e.height,this.runtime,this.canvas.el,window.devicePixelRatio]})}createChart(){let e=this.canvas.el,t=this.env.model.getters.getViewportZoomLevel();Vf(Gf(xp(1/t,e.getBoundingClientRect()),this.runtime),e,t)}};function V(e){return e=wr(e).replace(`#`,``),e.length===8?e.slice(6)+e.slice(0,6):e}let wp=`#F3F2F1`;function Tp(e,t,n=1,r){let i=r??Ep(e),a=typeof globalThis.devicePixelRatio==`number`?globalThis.devicePixelRatio:1;e.width=i.width*a,e.height=i.height*a;let o=e.getContext(`2d`);if(!o)throw Error(`Unable to retrieve 2D context from canvas`);o.scale(a*n,a*n);let s=Mp({width:i.width/n,height:i.height/n,x:0,y:0},t,o);Op(o,s),Dp(o,s),Ap(o,s),kp(o,s),jp(o,s)}function Ep(e){if(e instanceof HTMLCanvasElement){let t=e.getBoundingClientRect();return{width:t.width,height:t.height}}return{width:e.width,height:e.height}}function Dp(e,t){e.save();let n=t.gauge,r=n.rect.x+n.rect.width/2,i=n.rect.y+n.rect.height,a=n.rect.height-n.arcWidth/2;if(a<0)return;let o=n.percentage===1?0:Math.PI*(1+n.percentage);e.strokeStyle=wp,e.beginPath(),e.lineWidth=n.arcWidth,e.arc(r,i,a,o,0),e.stroke(),e.strokeStyle=n.color,e.beginPath(),e.arc(r,i,a,Math.PI,o),e.stroke(),e.restore()}function Op(e,t){e.save(),e.fillStyle=t.backgroundColor,e.fillRect(0,0,t.width,t.height),e.restore()}function kp(e,t){for(let n of[t.minLabel,t.maxLabel,t.gaugeValue])e.save(),e.textAlign=`center`,e.fillStyle=n.color,e.font=`${n.fontSize}px ${we}`,e.fillText(n.label,n.textPosition.x,n.textPosition.y),e.restore()}function Ap(e,t){let{x:n,y:r,width:i,height:a}=t.gauge.rect;for(let o of t.inflectionValues){e.save(),e.translate(n+i/2-.5,r+a-.5),e.rotate(Math.PI/2-o.rotation),e.lineWidth=2,e.strokeStyle=sd(t.backgroundColor)+`aa`,e.beginPath(),e.moveTo(0,-(a-t.gauge.arcWidth)),e.lineTo(0,-a-3),e.stroke(),e.textAlign=`center`,e.font=`${o.fontSize}px ${we}`,e.fillStyle=o.color;let s=-a-6-o.offset;e.fillText(o.label,0,s),e.restore()}}function jp(e,t){e.save();let n=t.title;e.font=Tl(n.fontSize,n.bold,n.italic),e.textBaseline=`middle`,e.fillStyle=n.color,e.fillText(n.label,n.textPosition.x,n.textPosition.y),e.restore()}function Mp(e,t,n){let r=t.maxValue,i=t.minValue,a=Bp(t,`animated`),o=Np(e,t.title.text),s=o.width/6,c=a?(a-i.value)/(r.value-i.value):0,l={x:e.width/2,y:o.y+o.height-o.height/12},u=80;o.height<300&&(u*=o.height/300);let d=o.width/2,f=t.gaugeValue?.label||`-`;Dl(n,f,{fontSize:u},`px`)>d&&(u=Ll(d,u,e=>Dl(n,f,{fontSize:e},`px`)));let p={x:o.x+s/2,y:o.y+o.height+12},m={x:o.x+o.width-s/2,y:o.y+o.height+12},h=sd(t.background),g=Pp(t,o,h,n),_=0,v=0,y=0;switch(t.title.text&&({width:v,height:y}=Al(n,t.title.text,{fontSize:16,...t.title},`px`)),t.title.align){case`right`:_=e.width-v-20;break;case`center`:_=(e.width-v)/2;break;default:_=20;break}return{width:e.width,height:e.height,title:{label:t.title.text??``,fontSize:t.title.fontSize??16,textPosition:{x:_,y:15+y/2},color:t.title.color??h,bold:t.title.bold,italic:t.title.italic},backgroundColor:t.background,gauge:{rect:o,arcWidth:s,percentage:x(c,0,1),color:Fp(t)},inflectionValues:g,gaugeValue:{label:f,textPosition:l,fontSize:u,color:h},minLabel:{label:t.minValue.label,textPosition:p,fontSize:12,color:h},maxLabel:{label:t.maxValue.label,textPosition:m,fontSize:12,color:h}}}function Np(e,t){let n=t?25:0,r=e.height-20-n-10,i=e.width-60,a,o;return i>2*r?(a=2*r,o=r):(a=i,o=i/2),{x:30+(i-a)/2,y:n+10+(r-o)/2,width:a,height:o}}function Pp(e,t,n,r){let i=e.maxValue,a=e.minValue,o={x:t.x+t.width/2,y:t.y+t.height},s={fontSize:12},c=[],l=[];for(let u of e.inflectionValues){let e=(u.value-a.value)/(i.value-a.value),d=Dl(r,u.label,s,`px`),f=Math.PI-Math.PI*e,p=zp(f,t.height+6,o.x,o.y,d+2,12),m=l.some(e=>Rp(e,p))?12:0;l.push(p),c.push({rotation:f,label:u.label,fontSize:12,color:n,offset:m})}return c}function Fp(e){let t=Bp(e,`final`);if(t===void 0)return wp;for(let n=0;n<e.inflectionValues.length;n++){let r=e.inflectionValues[n];if(r.operator===`<`&&t<r.value||r.operator===`<=`&&t<=r.value)return e.colors[n]}return e.colors.at(-1)}function Ip(e){return[{start:e.topLeft,end:e.topRight},{start:e.topRight,end:e.bottomRight},{start:e.bottomRight,end:e.bottomLeft},{start:e.bottomLeft,end:e.topLeft}]}function Lp(e,t){let n=e.start,r=e.end,i=t.start,a=t.end;function o(e,t,n){return(n.y-e.y)*(t.x-e.x)>(t.y-e.y)*(n.x-e.x)}return o(n,i,a)!==o(r,i,a)&&o(n,r,i)!==o(n,r,a)}function Rp(e,t){let n=Ip(e),r=Ip(t);for(let e of n)for(let t of r)if(Lp(e,t))return!0;return!1}function zp(e,t,n,r,i,a){let o=Math.cos(e),s=Math.sin(e),c=o*t,l=s*t,u=i/2*s,d=i/2*o,f={x:c+u+n,y:r-(l-d)},p={x:c-u+n,y:r-(l+d)},m=o*(t+a),h=s*(t+a),g={x:m-u+n,y:r-(h+d)};return{bottomLeft:p,bottomRight:f,topRight:{x:m+u+n,y:r-(h-d)},topLeft:g}}function Bp(e,t){return t===`animated`&&e.animationValue!==void 0?e.animationValue:e.gaugeValue?.value}let Vp={responsive:!0,maintainAspectRatio:!1,elements:{line:{fill:!1},point:{hitRadius:15}},animation:!1,events:[`mousemove`,`mouseout`,`click`,`touchstart`,`touchmove`,`mouseup`]};async function Hp(e,t,n){let r=Gp(t.width,t.height),i;if(`chartJsConfig`in e){if(!globalThis.Chart)return console.log(`Chart.js library is not loaded`),i;let t=Jl();t||Yl();let n=b(e.chartJsConfig);if(n.plugins=[Wp],!globalThis.Chart.registry.controllers.get(n.type))return console.log(`Chart of type "${n.type}" is not registered in Chart.js library.`),t||Xl(),i;let a=new globalThis.Chart(r,n);try{i=await qp(r)}finally{a.destroy(),t||Xl()}}else{if(!globalThis.OffscreenCanvas)throw Error(`converting a ${n} chart to an image using OffscreenCanvas is not supported in this environment`);n===`scorecard`?(Vf(Gf(t,e),r),i=await qp(r)):n===`gauge`&&(Tp(r,e,1,t),i=await qp(r))}return i}async function Up(e,t,n){let r=Gp(t.width,t.height),i=null;if(`chartJsConfig`in e){if(!globalThis.Chart)return console.log(`Chart.js library is not loaded`),i;let t=Jl();t||Yl();let n=b(e.chartJsConfig);if(n.plugins=[Wp],!globalThis.Chart.registry.controllers.get(n.type))return console.log(`Chart of type "${n.type}" is not registered in Chart.js library.`),t||Xl(),i;let a=new globalThis.Chart(r,n);try{i=await Kp(r)}finally{a.destroy(),t||Xl()}}else{if(!globalThis.OffscreenCanvas)throw Error(`converting a ${n} chart to an image using OffscreenCanvas is not supported in this environment`);n===`scorecard`?(Vf(Gf(t,e),r),i=await Kp(r)):n===`gauge`&&(Tp(r,e,1,t),i=await Kp(r))}return i}let Wp={id:`customCanvasBackgroundColor`,beforeDraw:e=>{let{ctx:t}=e;t.save(),t.globalCompositeOperation=`destination-over`,t.fillStyle=`#ffffff`,t.fillRect(0,0,e.width,e.height),t.restore()}};function Gp(e,t){return new OffscreenCanvas(e,t)}async function Kp(e){return`convertToBlob`in e?e.convertToBlob({type:`image/png`}):new Promise(t=>e.toBlob(t,`image/png`))}async function qp(e){let t=await Kp(e);if(t)return new Promise(e=>{let n=new FileReader;n.addEventListener(`load`,()=>{e(n.result)}),n.readAsDataURL(t)})}let Jp={Errors:{InvalidRange:k(`The range is invalid`),FirstArgMissing:k(`The argument is missing. Please provide a value`),SecondArgMissing:k(`The second argument is missing. Please provide a value`),MinNaN:k(`The minpoint must be a number`),MidNaN:k(`The midpoint must be a number`),MaxNaN:k(`The maxpoint must be a number`),ValueUpperInflectionNaN:k(`The first value must be a number`),ValueLowerInflectionNaN:k(`The second value must be a number`),MinBiggerThanMax:k(`Minimum must be smaller then Maximum`),MinBiggerThanMid:k(`Minimum must be smaller then Midpoint`),MidBiggerThanMax:k(`Midpoint must be smaller then Maximum`),LowerBiggerThanUpper:k(`Lower inflection point must be smaller than upper inflection point`),MinInvalidFormula:k(`Invalid Minpoint formula`),MaxInvalidFormula:k(`Invalid Maxpoint formula`),MidInvalidFormula:k(`Invalid Midpoint formula`),ValueUpperInvalidFormula:k(`Invalid upper inflection point formula`),ValueLowerInvalidFormula:k(`Invalid lower inflection point formula`),EmptyRange:k(`A range needs to be defined`),ValueCellIsInvalidFormula:k(`At least one of the provided values is an invalid formula`),Unexpected:k(`The rule is invalid for an unknown reason`)},ColorScale:k(`Color scale`),IconSet:k(`Icon set`),DataBar:k(`Data bar`)},Yp={Series:k(`Series`),BackgroundColor:k(`Background color`),StackedBarChart:k(`Stacked bar chart`),StackedLineChart:k(`Stacked line chart`),StackedAreaChart:k(`Stacked area chart`),StackedColumnChart:k(`Stacked column chart`),CumulativeData:k(`Cumulative data`),TreatLabelsAsText:k(`Treat labels as text`),AggregatedChart:k(`Aggregate`),Errors:{Unexpected:k(`The chart definition is invalid for an unknown reason`),InvalidDataSet:k(`The dataset is invalid`),InvalidLabelRange:k(`Labels are invalid`),InvalidScorecardKeyValue:k(`The key value is invalid`),InvalidScorecardBaseline:k(`The baseline value is invalid`),InvalidGaugeDataRange:k(`The data range is invalid`),EmptyGaugeRangeMin:k(`A minimum range limit value is needed`),GaugeRangeMinNaN:k(`The minimum range limit value must be a number`),EmptyGaugeRangeMax:k(`A maximum range limit value is needed`),GaugeRangeMaxNaN:k(`The maximum range limit value must be a number`),GaugeLowerInflectionPointNaN:k(`The lower inflection point value must be a number`),GaugeUpperInflectionPointNaN:k(`The upper inflection point value must be a number`)},ColorScales:{blues:k(`Blues`),cividis:k(`Cividis`),custom:k(`Custom`),greens:k(`Greens`),greys:k(`Greys`),oranges:k(`Oranges`),purples:k(`Purples`),rainbow:k(`Rainbow`),reds:k(`Reds`),viridis:k(`Viridis`)}},Xp={Custom:k(`Custom`)},Zp=k(`Merged cells are preventing this operation. Unmerge those cells and try again.`),Qp=k(`The header row of a table can't be moved.`),$p={Errors:{Unexpected:k(`Cannot split the selection for an unknown reason`),NoSplitSeparatorInSelection:k(`There is no match for the selected separator in the selection`),MoreThanOneColumnSelected:k(`Only a selection from a single column can be split`),SplitWillOverwriteContent:k(`Splitting will overwrite existing content`)}},em={Errors:{Unexpected:k(`Cannot remove duplicates for an unknown reason`),MoreThanOneRangeSelected:k(`Please select only one range of cells`),EmptyTarget:k(`Please select a range of cells containing values.`),NoColumnsProvided:k(`Please select at latest one column to analyze.`),WillRemoveExistingMerge:k(`This operation is not possible due to a merge. Please remove the merges first than try again.`)}},H={DateIs:{today:k(`today`),yesterday:k(`yesterday`),tomorrow:k(`tomorrow`),lastWeek:k(`in the past week`),lastMonth:k(`in the past month`),lastYear:k(`in the past year`)},DateIsBefore:{today:k(`today`),yesterday:k(`yesterday`),tomorrow:k(`tomorrow`),lastWeek:k(`one week ago`),lastMonth:k(`one month ago`),lastYear:k(`one year ago`)},CriterionError:{notEmptyValue:k(`The value must not be empty`),numberValue:k(`The value must be a number`),dateValue:k(`The value must be a date`),validRange:k(`The value must be a valid range`),validFormula:k(`The formula must be valid`)},Errors:{InvalidRange:k(`The range is invalid.`),InvalidDataValidationCriterionValue:k(`One or more of the provided criteria values are invalid. Please review and correct them.`),InvalidNumberOfCriterionValues:k(`One or more of the provided criteria values are missing.`),Unexpected:k(`The rule is invalid for an unknown reason.`)}},tm={Errors:{Unexpected:k(`The table zone is invalid for an unknown reason`),TableOverlap:k(`You cannot create overlapping tables.`),NonContinuousTargets:k(`A table can only be created on a continuous selection.`),InvalidRange:k(`The range is invalid`),TargetOutOfSheet:k(`The range is out of the sheet`)},Checkboxes:{hasFilters:k(`Filter button`),headerRow:k(`Header row(s)`),bandedRows:k(`Banded rows`),firstColumn:k(`First column`),lastColumn:k(`Last column`),bandedColumns:k(`Banded columns`),automaticAutofill:k(`Automatically autofill formulas`),totalRow:k(`Total row`),isDynamic:k(`Auto-adjust to formula result`)},Tooltips:{filterWithoutHeader:k(`Cannot have filters without a header row`),isDynamic:k(`For tables based on array formulas only`)}},nm={labels:{no_calculations:k(`No calculations`),"%_of_grand_total":k(`% of grand total`),"%_of_col_total":k(`% of column total`),"%_of_row_total":k(`% of row total`),"%_of":k(`% of`),"%_of_parent_row_total":k(`% of parent row total`),"%_of_parent_col_total":k(`% of parent column total`),"%_of_parent_total":k(`% of parent total`),difference_from:k(`Difference from`),"%_difference_from":k(`% difference from`),running_total:k(`Running total`),"%_running_total":k(`% Running total`),rank_asc:k(`Rank smallest to largest`),rank_desc:k(`Rank largest to smallest`),index:k(`Index`)},descriptions:{"%_of_grand_total":()=>k(`Displayed as % of grand total`),"%_of_col_total":()=>k(`Displayed as % of column total`),"%_of_row_total":()=>k(`Displayed as % of row total`),"%_of":e=>k(`Displayed as % of "%s"`,e),"%_of_parent_row_total":e=>k(`Displayed as % of parent row total of "%s"`,e),"%_of_parent_col_total":()=>k(`Displayed as % of parent column total`),"%_of_parent_total":e=>k(`Displayed as % of parent "%s" total`,e),difference_from:e=>k(`Displayed as difference from "%s"`,e),"%_difference_from":e=>k(`Displayed as % difference from "%s"`,e),running_total:e=>k(`Displayed as running total based on "%s"`,e),"%_running_total":e=>k(`Displayed as % running total based on "%s"`,e),rank_asc:e=>k(`Displayed as rank from smallest to largest based on "%s"`,e),rank_desc:e=>k(`Displayed as rank largest to smallest based on "%s"`,e),index:()=>k(`Displayed as index`)},documentation:{no_calculations:k(`Displays the value that is entered in the field.`),"%_of_grand_total":k(`Displays values as a percentage of the grand total of all the values or data points in the report.`),"%_of_col_total":k(`Displays all the values in each column or series as a percentage of the total for the column or series.`),"%_of_row_total":k(`Displays the value in each row or category as a percentage of the total for the row or category.`),"%_of":k(`Displays values as a percentage of the value of the Base item in the Base field.`),"%_of_parent_row_total":k(`Calculates values as follows:
|
|
15
15
|
(value for the item) / (value for the parent item on rows)`),"%_of_parent_col_total":k(`Calculates values as follows:
|
|
@@ -108,24 +108,24 @@ stores.inject(MyMetaStore, storeInstance);
|
|
|
108
108
|
offset="offset"
|
|
109
109
|
direction="'vertical'"
|
|
110
110
|
onScroll.bind="onScroll"
|
|
111
|
-
/>`;static defaultProps={topOffset:0};get offset(){return this.env.model.getters.getActiveSheetScrollInfo().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(),t=this.env.model.getters.getScrollBarWidth();return{top:`${this.props.topOffset+e}px`,right:`0px`,width:`${t}px`,bottom:pp()?`${t}px`:`0`}}onScroll(e){let{scrollX:t}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:t,offsetY:e})}},pV=class extends t.Component{static template=`o-spreadsheet-Selection`;static props={};static components={Highlight:cV};get highlightProps(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getUnboundedZone(e,this.env.model.getters.getSelectedZone());return{range:this.env.model.getters.getRangeFromZone(e,t),color:ae}}};function mV({refName:e}){let n=(0,t.useRef)(e);(0,t.useEffect)(e=>{e?.focus()},()=>[n.el])}var hV=class extends t.Component{static props={value:[Number,String],onChange:Function,class:{type:String,optional:!0},id:{type:String,optional:!0},placeholder:{type:String,optional:!0},autofocus:{type:Boolean,optional:!0},alwaysShowBorder:{type:Boolean,optional:!0},selectContentOnFocus:{type:Boolean,optional:!0}};refName=`input`;inputRef;setup(){this.inputRef=(0,t.useRef)(this.refName),(0,t.useExternalListener)(window,`click`,e=>{e.target!==this.inputRef.el&&this.inputRef.el?.value!==this.props.value&&this.save()},{capture:!0}),this.props.autofocus&&mV({refName:this.refName}),(0,t.onWillUpdateProps)(e=>{document.activeElement!==this.inputRef.el&&this.inputRef.el&&(this.inputRef.el.value=e.value)}),(0,t.onMounted)(()=>{this.inputRef.el&&(this.inputRef.el.value=this.props.value.toString())})}onKeyDown(e){switch(e.key){case`Enter`:this.save(),e.preventDefault(),e.stopPropagation();break;case`Escape`:this.inputRef.el&&(this.inputRef.el.value=this.props.value.toString(),this.inputRef.el.blur()),e.preventDefault(),e.stopPropagation();break}}save(e=!1){let t=(this.inputRef.el?.value||``).trim();t!==this.props.value.toString()&&this.props.onChange(t),e||this.inputRef.el?.blur()}onMouseDown(e){e.target!==document.activeElement&&this.props.selectContentOnFocus&&(e.preventDefault(),e.stopPropagation())}onMouseUp(e){let t=e.target;t!==document.activeElement&&this.props.selectContentOnFocus&&(t.focus(),this.props.selectContentOnFocus&&t.select(),e.preventDefault(),e.stopPropagation())}},gV=class extends hV{static template=`o-spreadsheet-TextInput`;static components={};static props={...hV.props,errorMessage:{type:String,optional:!0}};get inputClass(){return[this.props.class,`w-100 os-input`,this.props.alwaysShowBorder?`o-input-border`:void 0,this.props.errorMessage?`o-invalid`:void 0].filter(C).join(` `)}},_V=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=h(this.props.action);setup(){(0,t.onWillUpdateProps)(e=>{e.action!==this.props.action&&(this.actionButton=h(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`}):``}},vV=class extends t.Component{static template=`o-spreadsheet-ColorPickerWidget`;static props={currentColor:{type:String,optional:!0},toggleColorPicker:Function,showColorPicker:Boolean,onColorPicked:Function,icon:String,title:{type:String,optional:!0},disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};static components={ColorPicker:yk};colorPickerButtonRef=(0,t.useRef)(`colorPickerButton`);get iconStyle(){return this.props.currentColor?`border-color: ${this.props.currentColor}`:`border-bottom-style: hidden`}get colorPickerAnchorRect(){let e=this.colorPickerButtonRef.el.getBoundingClientRect();return{x:e.x,y:e.y,width:e.width,height:e.height}}},yV=class extends t.Component{static template=`o-spreadsheet-NumberEditor`;static props={currentValue:Number,onValueChange:Function,onToggle:{type:Function,optional:!0},onFocusInput:{type:Function,optional:!0},class:String,valueIcon:{type:String,optional:!0},min:Number,max:Number,title:String,valueList:Array};static defaultProps={onFocusInput:()=>{}};static components={Popover:Cv};dropdown=(0,t.useState)({isOpen:!1});inputRef=(0,t.useRef)(`inputNumber`);rootEditorRef=(0,t.useRef)(`NumberEditor`);valueListRef=(0,t.useRef)(`numberList`);DOMFocusableElementStore;setup(){this.DOMFocusableElementStore=D(xO),(0,t.useExternalListener)(window,`click`,this.onExternalClick,{capture:!0}),(0,t.onWillUpdateProps)(e=>{this.inputRef.el&&document.activeElement!==this.inputRef.el&&(this.inputRef.el.value=e.currentValue)}),(0,t.onMounted)(()=>{this.inputRef.el&&(this.inputRef.el.value=this.props.currentValue.toString())})}get popoverProps(){let{x:e,y:t,width:n,height:r}=this.rootEditorRef.el.getBoundingClientRect();return{anchorRect:{x:e,y:t,width:n,height:r},positioning:`bottom-left`,verticalOffset:0}}onExternalClick(e){!Zf(this.valueListRef.el,e)&&!Zf(this.rootEditorRef.el,e)&&this.closeList()}toggleList(){this.dropdown.isOpen?this.closeList():(this.props.onToggle?.(),this.inputRef.el.focus())}closeList(){this.dropdown.isOpen=!1}setValue(e){let t=x(Math.floor(parseFloat(e)),this.props.min,this.props.max);this.props.onValueChange(t),this.closeList()}setValueFromInput(e){this.setValue(e.target.value)}setValueFromList(e){this.setValue(e)}get currentValue(){return`${this.props.currentValue}`}onInputFocused(e){this.dropdown.isOpen=!0,e.target.select()}onInputKeydown(e){if(e.key===`Enter`||e.key===`Escape`){this.closeList();let t=e.target;e.key===`Escape`&&(t.value=`${this.props.currentValue}`),this.props.onToggle?.()}if(e.key===`Tab`){e.preventDefault(),e.stopPropagation(),this.closeList(),this.DOMFocusableElementStore.focus();return}}},bV=class extends t.Component{static template=`o-spreadsheet-FontSizeEditor`;static components={NumberEditor:yV};static props={currentFontSize:Number,onFontSizeChanged:Function,onToggle:{type:Function,optional:!0},onFocusInput:{type:Function,optional:!0},class:String};static defaultProps={onFocusInput:()=>{}};fontSizes=Ie},xV=class extends t.Component{static template=`o-spreadsheet.TextStyler`;static components={ColorPickerWidget:vV,ActionButton:_V,FontSizeEditor:bV};static props={style:Object,updateStyle:{type:Function,optional:!0},defaultStyle:{type:Object,optional:!0},hasVerticalAlign:{type:Boolean,optional:!0},hasHorizontalAlign:{type:Boolean,optional:!0},hasBackgroundColor:{type:Boolean,optional:!0},class:{type:String,optional:!0}};openedEl=null;setup(){(0,t.useExternalListener)(window,`click`,this.onExternalClick)}state=(0,t.useState)({activeTool:``});updateFontSize(e){this.props.updateStyle?.({...this.props.style,fontSize:e})}toggleDropdownTool(e,t){let n=this.state.activeTool===e;this.closeMenus(),this.state.activeTool=n?``:e,this.openedEl=n?null:t.target}onExternalClick(e){this.openedEl!==e.target&&this.closeMenus()}onTextColorChange(e){this.props.updateStyle?.({...this.props.style,color:e}),this.closeMenus()}onFillColorChange(e){this.props.updateStyle?.({...this.props.style,fillColor:e}),this.closeMenus()}updateAlignment(e){this.props.updateStyle?.({...this.props.style,align:e}),this.closeMenus()}updateVerticalAlignment(e){this.props.updateStyle?.({...this.props.style,verticalAlign:e}),this.closeMenus()}toggleBold(){this.props.updateStyle?.({...this.props.style,bold:!this.bold})}toggleItalic(){this.props.updateStyle?.({...this.props.style,italic:!this.italic})}closeMenus(){this.state.activeTool=``,this.openedEl=null}get align(){return this.props.style.align??this.props.defaultStyle?.align}get verticalAlign(){return this.props.style.verticalAlign||this.props.defaultStyle?.verticalAlign}get bold(){return this.props.style.bold??this.props.defaultStyle?.bold}get italic(){return this.props.style.italic??this.props.defaultStyle?.italic}get currentFontSize(){return this.props.style.fontSize??this.props.defaultStyle?.fontSize??ye.fontSize}get boldButtonAction(){return{name:k(`Bold`),execute:()=>this.toggleBold(),isActive:()=>this.bold||!1,icon:`o-spreadsheet-Icon.BOLD`}}get italicButtonAction(){return{name:k(`Italic`),execute:()=>this.toggleItalic(),isActive:()=>this.italic||!1,icon:`o-spreadsheet-Icon.ITALIC`}}get horizontalAlignButtonAction(){let e=`o-spreadsheet-Icon.ALIGN_LEFT`;return this.align===`center`?e=`o-spreadsheet-Icon.ALIGN_CENTER`:this.align===`right`&&(e=`o-spreadsheet-Icon.ALIGN_RIGHT`),{name:k(`Horizontal alignment`),icon:e}}get horizontalAlignActions(){return[{name:k(`Left`),execute:()=>this.updateAlignment(`left`),isActive:()=>this.align===`left`,icon:`o-spreadsheet-Icon.ALIGN_LEFT`},{name:k(`Center`),execute:()=>this.updateAlignment(`center`),isActive:()=>this.align===`center`,icon:`o-spreadsheet-Icon.ALIGN_CENTER`},{name:k(`Right`),execute:()=>this.updateAlignment(`right`),isActive:()=>this.align===`right`,icon:`o-spreadsheet-Icon.ALIGN_RIGHT`}]}get verticalAlignButtonAction(){let e=`o-spreadsheet-Icon.ALIGN_MIDDLE`;return this.verticalAlign===`top`?e=`o-spreadsheet-Icon.ALIGN_TOP`:this.verticalAlign===`bottom`&&(e=`o-spreadsheet-Icon.ALIGN_BOTTOM`),{name:k(`Vertical alignment`),icon:e}}get verticalAlignActions(){return[{name:k(`Top`),execute:()=>this.updateVerticalAlignment(`top`),isActive:()=>this.verticalAlign===`top`,icon:`o-spreadsheet-Icon.ALIGN_TOP`},{name:k(`Middle`),execute:()=>this.updateVerticalAlignment(`middle`),isActive:()=>this.verticalAlign===`middle`,icon:`o-spreadsheet-Icon.ALIGN_MIDDLE`},{name:k(`Bottom`),execute:()=>this.updateVerticalAlignment(`bottom`),isActive:()=>this.verticalAlign===`bottom`,icon:`o-spreadsheet-Icon.ALIGN_BOTTOM`}]}},SV=class extends t.Component{static template=`o-spreadsheet-CogWheelMenu`;static components={MenuPopover:Dv};static props={items:Array};buttonRef=(0,t.useRef)(`button`);menuState=(0,t.useState)({isOpen:!1,anchorRect:null,menuItems:[]});menuId=this.env.model.uuidGenerator.uuidv4();toggleMenu(e){e.closedMenuId!==this.menuId&&(this.menuState.isOpen=!this.menuState.isOpen,this.menuState.anchorRect=tp(this.buttonRef.el),this.menuState.menuItems=p(this.props.items))}},CV=class extends t.Component{static template=`o-spreadsheet-CarouselPanel`;static props={onCloseSidePanel:Function,figureId:String};static components={Section:q,TextInput:gV,TextStyler:xV,CogWheelMenu:SV};DEFAULT_CAROUSEL_TITLE_STYLE=ze;dragAndDrop=Sk();previewListRef=(0,t.useRef)(`previewList`);setup(){let e=[...this.carouselItems];(0,t.onWillUpdateProps)(()=>{w(this.carouselItems,e)||this.dragAndDrop.cancel(),e=[...this.carouselItems]})}get carouselItems(){return this.env.model.getters.getCarousel(this.props.figureId).items}get title(){return this.env.model.getters.getCarousel(this.props.figureId).title}get carousel(){return this.env.model.getters.getCarousel(this.props.figureId)}getPreviewDivStyle(e){return this.dragAndDrop.itemsStyle[this.getItemId(e)]||``}getItemId(e){return e.type===`chart`?e.chartId:`transparent-carousel`}addNewChartToCarousel(){this.env.model.dispatch(`ADD_NEW_CHART_TO_CAROUSEL`,{figureId:this.props.figureId,sheetId:this.carouselSheetId})}get hasDataView(){return this.carouselItems.some(e=>e.type===`carouselDataView`)}isCarouselItemActive(e){return w(this.env.model.getters.getSelectedCarouselItem(this.props.figureId),e)}addDataViewToCarousel(){let e=this.env.model.getters.getCarousel(this.props.figureId);this.updateItems([...e.items,{type:`carouselDataView`}])}activateCarouselItem(e){this.env.model.dispatch(`UPDATE_CAROUSEL_ACTIVE_ITEM`,{figureId:this.props.figureId,sheetId:this.carouselSheetId,item:e})}editCarouselItem(e){e.type===`chart`&&(this.activateCarouselItem(e),this.env.model.dispatch(`SELECT_FIGURE`,{figureId:this.props.figureId}),this.env.openSidePanel(`ChartPanel`,{chartId:e.chartId}))}renameCarouselItem(e,t){let n=t.trim();if(!n||n===this.getItemTitle(e).toString())return;let r=[...this.carouselItems],i=this.carouselItems.findIndex(t=>w(t,e));i!==-1&&(r[i]={...e,title:n},this.updateItems(r))}deleteCarouselItem(e){let t=this.env.model.getters.getCarousel(this.props.figureId).items.filter(t=>!w(t,e));this.updateItems(t)}popOutCarouselItem(e){e.type===`chart`&&this.env.model.dispatch(`POPOUT_CHART_FROM_CAROUSEL`,{sheetId:this.carouselSheetId,carouselId:this.props.figureId,chartId:e.chartId})}duplicateCarouselChart(e){e.type===`chart`&&this.env.model.dispatch(`DUPLICATE_CAROUSEL_CHART`,{sheetId:this.carouselSheetId,carouselId:this.props.figureId,chartId:e.chartId,duplicatedChartId:this.env.model.uuidGenerator.smallUuid()})}onDragHandleMouseDown(e,t){if(t.button!==0)return;let n=Array.from(this.previewListRef.el.children).map(e=>tp(e)),r=this.carouselItems.map((e,t)=>({id:this.getItemId(e),size:n[t].height,position:n[t].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:this.getItemId(e),initialMousePosition:t.clientY,items:r,scrollableContainerEl:this.previewListRef.el,onDragEnd:(t,n)=>this.onDragEnd(e,n)})}onDragEnd(e,t){let n=this.carouselItems.findIndex(t=>w(t,e));if(n===-1||n===t)return;let r=[...this.env.model.getters.getCarousel(this.props.figureId).items];r.splice(n,1),r.splice(t,0,e),this.updateItems(r)}getItemTitle(e){return Y_(this.env.model.getters,e)}getItemPreview(e){return J_(this.env.model.getters,e)}updateItems(e){this.env.model.dispatch(`UPDATE_CAROUSEL`,{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...this.carousel,items:e}})}updateTitleText(e){let t=this.env.model.getters.getCarousel(this.props.figureId);this.env.model.dispatch(`UPDATE_CAROUSEL`,{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...t,title:{...t.title,text:e}}})}updateTitleStyle(e){let t=this.env.model.getters.getCarousel(this.props.figureId);this.env.model.dispatch(`UPDATE_CAROUSEL`,{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...t,title:{...t.title,...e}}})}get carouselAddChartInfoMessage(){return k(`Add a chart to the carousel. You can also add a chart by dragging and dropping it over the carousel figure.`)}getCogWheelMenuItems(e){let t=[];return e.type===`chart`&&(t.push({name:k(`Edit chart`),execute:()=>this.editCarouselItem(e),icon:`o-spreadsheet-Icon.EDIT`}),t.push({name:k(`Pop out chart`),execute:()=>this.popOutCarouselItem(e),icon:`o-spreadsheet-Icon.EXTERNAL`}),t.push({name:k(`Duplicate chart`),execute:()=>this.duplicateCarouselChart(e),icon:`o-spreadsheet-Icon.COPY`})),t.push({name:k(`Delete item`),execute:()=>this.deleteCarouselItem(e),icon:`o-spreadsheet-Icon.TRASH`}),t}get carouselSheetId(){let e=this.env.model.getters.getFigureSheetId(this.props.figureId);if(!e)throw Error(`Could not find the sheetId of the carousel figure`);return e}get carouselDataViewMessage(){return k(`The data view makes the carousel transparent, revealing the data underneath.`)}};let wV={chartId:String,definition:Object,canUpdateChart:Function,updateChart:Function};var TV=class extends t.Component{static template=`o-spreadsheet.ChartDataSeries`;static components={SelectionInput:kk,Section:q};static props={ranges:Array,hasSingleRange:{type:Boolean,optional:!0},onSelectionChanged:Function,onSelectionReordered:{type:Function,optional:!0},onSelectionRemoved:{type:Function,optional:!0},onSelectionConfirmed:Function,title:{type:String,optional:!0},maxNumberOfUsedRanges:{type:Number,optional:!0},datasetOrientation:{type:String,optional:!0},canChangeDatasetOrientation:{type:Boolean,optional:!0},onFlipAxis:{type:Function,optional:!0}};get ranges(){return this.props.ranges.map(e=>e.dataRange)}get disabledRanges(){return this.props.ranges.map((e,t)=>this.props.maxNumberOfUsedRanges?t>=this.props.maxNumberOfUsedRanges:!1)}get colors(){return this.props.ranges.map(e=>e.backgroundColor)}get title(){return this.props.title?this.props.title:this.props.hasSingleRange?k(`Data range`):k(`Data series`)}},EV=class extends t.Component{static template=`o-spreadsheet.ChartErrorSection`;static components={Section:q,ValidationMessages:IB};static props={messages:{type:Array,element:String}}},DV=class extends t.Component{static template=`o-spreadsheet.ChartLabelRange`;static components={SelectionInput:kk,Checkbox:Fk,Section:q};static props={title:{type:String,optional:!0},range:String,isInvalid:Boolean,onSelectionChanged:Function,onSelectionConfirmed:Function,options:{type:Array,optional:!0}};static defaultProps={title:k(`Categories / Labels`),options:[]}},OV=class extends t.Component{static template=`o-spreadsheet-GenericChartConfigPanel`;static components={ChartDataSeries:TV,ChartLabelRange:DV,Section:q,Checkbox:Fk,ChartErrorSection:EV};static props=wV;state=(0,t.useState)({datasetDispatchResult:void 0,labelsDispatchResult:void 0});dataSets=[];labelRange;datasetOrientation=void 0;chartTerms=Yp;setup(){this.dataSets=this.props.definition.dataSets,this.labelRange=this.props.definition.labelRange,this.datasetOrientation=this.computeDatasetOrientation()}get errorMessages(){return[...this.state.datasetDispatchResult?.reasons||[],...this.state.labelsDispatchResult?.reasons||[]].filter(e=>e!==`NoChanges`).map(e=>Yp.Errors[e]||Yp.Errors.Unexpected)}get isDatasetInvalid(){return!!this.state.datasetDispatchResult?.isCancelledBecause(`InvalidDataSet`)}get isLabelInvalid(){return!!this.state.labelsDispatchResult?.isCancelledBecause(`InvalidLabelRange`)}get dataSetsHaveTitleLabel(){return this.datasetOrientation===`rows`?k(`Use col %(column_name)s as headers`,{column_name:Ht(this.calculateHeaderPosition()||0)}):k(`Use row %(row_position)s as headers`,{row_position:this.calculateHeaderPosition()||``})}getLabelRangeOptions(){let e=this.props.definition;return[{name:`aggregated`,label:this.chartTerms.AggregatedChart,value:(`aggregated`in e?e.aggregated:!1)??!1,onChange:this.onUpdateAggregated.bind(this)},{name:`dataSetsHaveTitle`,label:this.dataSetsHaveTitleLabel,value:e.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}onUpdateDataSetsHaveTitle(e){this.props.updateChart(this.props.chartId,{dataSetsHaveTitle:e})}get canChangeDatasetOrientation(){let e=new Set,t=[],n=this.env.model.getters.getActiveSheetName(),r=this.dataSets.map(e=>e.dataRange);this.labelRange&&r.push(this.labelRange);for(let i of r){if(!fn(i))return!1;let r=Pc(i),a=ln(r.xc);if(a.bottom===void 0||a.right===void 0||(t.push(a),e.add(r.sheetName||n),e.size>1))return!1}let i=Xn(t);if(i.length!==1)return!1;let{left:a,right:o,top:s,bottom:c}=i[0];return!t.some(e=>(e.top!==s||e.bottom!==c)&&(e.left!==a||e.right!==o))}computeDatasetOrientation(){let e=!1,t=!1;for(let n of this.dataSets){if(!fn(n.dataRange))return;let r=ln(n.dataRange);if(r.bottom===void 0||r.right===void 0)return;r.top===r.bottom&&(e=!0),r.left===r.right&&(t=!0)}if(e&&!t)return`rows`;if(!e&&t)return`columns`}setDatasetOrientation(e){let t=this.props.definition.dataSets.map(e=>e.dataRange),n=this.transposeDataSet([this.props.definition.labelRange,...t],e);if(n.length===0)return;let r=n.length>1?n.shift().dataRange:``;this.props.updateChart(this.props.chartId,{labelRange:r,dataSets:n}),this.dataSets=n,this.labelRange=r,this.datasetOrientation=e}onDataSeriesRangesChanged(e){this.dataSets=e.map((e,t)=>({...this.dataSets?.[t],dataRange:e})),this.state.datasetDispatchResult=this.props.canUpdateChart(this.props.chartId,{dataSets:this.dataSets})}onDataSeriesReordered(e){let t=_f({dataSets:this.dataSets},this.dataSets.length);this.datasetOrientation=void 0;let n=this.dataSets.map(e=>t.next());this.dataSets=e.map(e=>({backgroundColor:n[e],...this.dataSets[e]})),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{dataSets:this.dataSets})}onDataSeriesRemoved(e){let t=_f({dataSets:this.dataSets},this.dataSets.length),n=this.dataSets.map(e=>t.next());this.dataSets=this.dataSets.map((e,t)=>({backgroundColor:n[t],...e})).filter((t,n)=>n!==e),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{dataSets:this.dataSets})}onDataSeriesConfirmed(){this.dataSets=this.splitRanges,this.datasetOrientation=this.computeDatasetOrientation(),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{dataSets:this.dataSets}),this.state.datasetDispatchResult.isSuccessful&&(this.dataSets=this.env.model.getters.getChartDefinition(this.props.chartId).dataSets)}get splitRanges(){let e=[];for(let t of this.dataSets){let n=t.dataRange;if(!this.env.model.getters.isRangeValid(n)){e.push(t);continue}let{sheetName:r}=Pc(n),i=r?`${r}!`:``,a=ln(n);if(a.bottom!==a.top&&a.left!==a.right){if(this.datasetOrientation!==`rows`){if(a.right!==void 0)for(let n=a.left;n<=a.right;++n){let r=n===a.left?t:{yAxisId:t.yAxisId};e.push({...r,dataRange:`${i}${hn({left:n,right:n,top:a.top,bottom:a.bottom})}`})}else if(a.bottom!==void 0)for(let n=a.top;n<=a.bottom;++n){let r=n===a.top?t:{yAxisId:t.yAxisId};e.push({...r,dataRange:`${i}${hn({left:a.left,right:a.right,top:n,bottom:n})}`})}}else if(a.bottom!==void 0)for(let n=a.top;n<=a.bottom;++n){let r=n===a.top?t:{yAxisId:t.yAxisId};e.push({...r,dataRange:`${i}${hn({left:a.left,right:a.right,top:n,bottom:n})}`})}else if(a.right!==void 0)for(let n=a.left;n<=a.right;++n){let r=n===a.left?t:{yAxisId:t.yAxisId};e.push({...r,dataRange:`${i}${hn({left:n,right:n,top:a.top,bottom:a.bottom})}`})}}else e.push(t)}return e}getDataSeriesRanges(){return this.dataSets}onLabelRangeChanged(e){this.labelRange=e[0],this.state.labelsDispatchResult=this.props.canUpdateChart(this.props.chartId,{labelRange:this.labelRange})}onLabelRangeConfirmed(){this.state.labelsDispatchResult=this.props.updateChart(this.props.chartId,{labelRange:this.labelRange})}getLabelRange(){return this.labelRange||``}onUpdateAggregated(e){this.props.updateChart(this.props.chartId,{aggregated:e})}calculateHeaderPosition(){if(this.isDatasetInvalid||this.isLabelInvalid)return;let e=this.env.model.getters,t=e.getActiveSheetId(),n=Zc(e,t,this.labelRange),r=td(e,this.dataSets,t,this.props.definition.dataSetsHaveTitle);if(r.length)return this.datasetOrientation===`rows`?r[0].dataRange.zone.left:r[0].dataRange.zone.top+1;if(n)return n.zone.top+1}get maxNumberOfUsedRanges(){return f_.get(this.props.definition.type).dataSeriesLimit}transposeDataSet(e,t){let n=this.env.model.getters;if(t===void 0)return e.filter(C).map(e=>({dataRange:e}));let r={},i=[],a=n.getFigureIdFromChartId(this.props.chartId),o=n.getFigureSheetId(a),s=n.getActiveSheet().name;o&&(s=n.getSheet(o).name);for(let t of e){if(!t)continue;if(!fn(t))return e.filter(C).map(e=>({dataRange:e}));let{sheetName:n,xc:i}=Pc(t);n??=s,r[n]||(r[n]=[]),r[n].push(un(i))}for(let e in r){let n=r[e],a=Xn(n);if(t===`columns`)for(let t of a)for(let n=t.left;n<=t.right;n++){let r=`${e===s?``:e+`!`}${hn({...t,left:n,right:n})}`;i.push({dataRange:r})}else for(let t of a)for(let n=t.top;n<=t.bottom;n++){let r=`${e===s?``:e+`!`}${hn({...t,top:n,bottom:n})}`;i.push({dataRange:r})}}return i}},kV=class extends OV{static template=`o-spreadsheet-BarConfigPanel`;get stackedLabel(){return this.props.definition.horizontal?this.chartTerms.StackedBarChart:this.chartTerms.StackedColumnChart}onUpdateStacked(e){this.props.updateChart(this.props.chartId,{stacked:e})}},AV=class extends t.Component{static template=`o-spreadsheet.BadgeSelection`;static props={choices:Array,onChange:Function,selectedValue:String}},jV=class extends t.Component{static template=`o-spreadsheet.ChartTitle`;static components={Section:q,TextStyler:xV,TextInput:gV};static props={title:{type:String,optional:!0},placeholder:{type:String,optional:!0},updateTitle:Function,name:{type:String},style:Object,defaultStyle:{type:Object,optional:!0},updateStyle:Function};static defaultProps={title:``,placeholder:``};updateTitle(e){this.props.updateTitle(e)}},MV=class extends t.Component{static template=`o-spreadsheet-AxisDesignEditor`;static components={Section:q,ChartTitle:jV,BadgeSelection:AV};static props={chartId:String,definition:Object,updateChart:Function,axesList:Array};state=(0,t.useState)({currentAxis:`x`});defaultFontSize=12;get axisTitleStyle(){return this.props.definition.axesDesign?.[this.state.currentAxis]?.title??{}}get badgeAxes(){return this.props.axesList.map(e=>({value:e.id,label:e.name}))}updateAxisEditor(e){this.state.currentAxis=e.target.value}getAxisTitle(){return(this.props.definition.axesDesign??{})[this.state.currentAxis]?.title.text||``}updateAxisTitle(e){let t=b(this.props.definition.axesDesign)??{};t[this.state.currentAxis]={...t[this.state.currentAxis],title:{...t?.[this.state.currentAxis]?.title,text:e}},this.props.updateChart(this.props.chartId,{axesDesign:t})}updateAxisTitleStyle(e){let t=b(this.props.definition.axesDesign)??{};t[this.state.currentAxis]={...t[this.state.currentAxis],title:e},this.props.updateChart(this.props.chartId,{axesDesign:t})}},NV=class extends t.Component{static template=`o-spreadsheet.RadioSelection`;static props={choices:Array,onChange:Function,selectedValue:{optional:!1},name:String,direction:{type:String,optional:!0}};static defaultProps={direction:`horizontal`}},PV=class extends t.Component{static template=`o-spreadsheet-GeneralDesignEditor`;static components={RoundColorPicker:bk,ChartTitle:jV,Section:q,SidePanelCollapsible:Vv,RadioSelection:NV};static props={...wV,defaultChartTitleFontSize:{type:Number,optional:!0},slots:{type:Object,optional:!0}};static defaultProps={defaultChartTitleFontSize:16};state;setup(){this.state=(0,t.useState)({activeTool:``})}get title(){return this.props.definition.title}toggleDropdownTool(e,t){let n=this.state.activeTool===e;this.state.activeTool=n?``:e}updateBackgroundColor(e){this.props.updateChart(this.props.chartId,{background:e})}updateTitle(e){let t={...this.title,text:e};this.props.updateChart(this.props.chartId,{title:t})}updateChartTitleStyle(e){let t={...this.title,...e};this.props.updateChart(this.props.chartId,{title:t}),this.state.activeTool=``}},FV=class extends t.Component{static template=`o-spreadsheet-ChartHumanizeNumbers`;static components={Checkbox:Fk};static props=wV;get title(){let e=this.env.model.getters.getLocale();return k(`E.g. 1234567 -> %(value)s`,{value:z(1234567,{format:gs({value:1234567},void 0,e),locale:e})})}},IV=class extends t.Component{static template=`o-spreadsheet-ChartLegend`;static components={Section:q};static props=wV;updateLegendPosition(e){this.props.updateChart(this.props.chartId,{legendPosition:e.target.value})}},LV=class extends hV{static template=`o-spreadsheet-NumberInput`;static components={};static props={...hV.props,min:{type:Number,optional:!0},max:{type:Number,optional:!0}};debouncedOnChange=dt(this.props.onChange.bind(this),100,!0);save(){let e=(this.inputRef.el?.value||``).trim();e!==this.props.value.toString()&&this.debouncedOnChange(e)}get inputClass(){return[this.props.class,`o-input`].join(` `)}},RV=class extends t.Component{static template=`o-spreadsheet-SeriesDesignEditor`;static components={SidePanelCollapsible:Vv,Section:q,RoundColorPicker:bk};static props={...wV,slots:{type:Object,optional:!0}};state=(0,t.useState)({index:0});getDataSeries(){let e=this.env.model.getters.getChartRuntime(this.props.chartId);return!e||!(`chartJsConfig`in e)?[]:e.chartJsConfig.data.datasets.filter(e=>!vd(e.xAxisID??``)).map(e=>e.label)}updateEditedSeries(e){this.state.index=e.target.selectedIndex}updateDataSeriesColor(e){let t=this.props.definition.dataSets;t?.[this.state.index]&&(t[this.state.index]={...t[this.state.index],backgroundColor:e},this.props.updateChart(this.props.chartId,{dataSets:t}))}getDataSeriesColor(){let e=this.props.definition.dataSets;if(!e?.[this.state.index])return``;let t=e[this.state.index].backgroundColor;return t?wr(t):Zr(this.state.index,Qr(this.props.definition.dataSets.length))}updateDataSeriesLabel(e){let t=e.target.value,n=this.props.definition.dataSets;n?.[this.state.index]&&(n[this.state.index]={...n[this.state.index],label:t},this.props.updateChart(this.props.chartId,{dataSets:n}))}getDataSeriesLabel(){return this.props.definition.dataSets[this.state.index]?.label||this.getDataSeries()[this.state.index]}},zV=class extends t.Component{static template=`o-spreadsheet-SeriesWithAxisDesignEditor`;static components={SeriesDesignEditor:RV,Checkbox:Fk,RadioSelection:NV,Section:q,RoundColorPicker:bk,NumberInput:LV};static props={...wV,slots:{type:Object,optional:!0}};axisChoices=hd;updateDataSeriesAxis(e,t){let n=[...this.props.definition.dataSets];n?.[e]&&(n[e]={...n[e],yAxisId:t===`left`?`y`:`y1`},this.props.updateChart(this.props.chartId,{dataSets:n}))}getDataSerieAxis(e){let t=this.props.definition.dataSets;return t?.[e]&&t[e].yAxisId===`y1`?`right`:`left`}get canHaveTwoVerticalAxis(){return!(`horizontal`in this.props.definition&&this.props.definition.horizontal)}toggleDataTrend(e,t){let n=[...this.props.definition.dataSets];n?.[e]&&(n[e]={...n[e],trend:{type:`polynomial`,order:1,...n[e].trend,display:t}},this.props.updateChart(this.props.chartId,{dataSets:n}))}getTrendLineConfiguration(e){return this.props.definition.dataSets?.[e]?.trend}getTrendType(e){return e?e.type===`polynomial`&&e.order===1?`linear`:e.type:``}onChangeTrendType(e,t){let n=t.target.value,r;switch(n){case`linear`:case`polynomial`:r={type:`polynomial`,order:n===`linear`?1:this.getMaxPolynomialDegree(e)};break;case`exponential`:case`logarithmic`:case`trailingMovingAverage`:r={type:n};break;default:return}this.updateTrendLineValue(e,r)}getPolynomialDegrees(e){return S(1,this.getMaxPolynomialDegree(e)+1)}onChangePolynomialDegree(e,t){let n=t.target;this.updateTrendLineValue(e,{order:parseInt(n.value)})}getMaxPolynomialDegree(e){let t=this.env.model.getters.getChartRuntime(this.props.chartId);return Math.min(10,t.chartJsConfig.data.datasets[e].data.length-1)}get defaultWindowSize(){return 2}onChangeMovingAverageWindow(e,t){let n=parseInt(t)||2;n<=1&&(n=2),this.updateTrendLineValue(e,{window:n})}getDataSeriesColor(e){let t=this.props.definition.dataSets;if(!t?.[e])return``;let n=t[e].backgroundColor;return n?wr(n):Zr(e,Qr(this.props.definition.dataSets.length))}getTrendLineColor(e){return this.getTrendLineConfiguration(e)?.color??Br(this.getDataSeriesColor(e),.5)}updateTrendLineColor(e,t){this.updateTrendLineValue(e,{color:t})}updateTrendLineValue(e,t){let n=[...this.props.definition.dataSets];n?.[e]&&(n[e]={...n[e],trend:{...n[e].trend,...t}},this.props.updateChart(this.props.chartId,{dataSets:n}))}},BV=class extends t.Component{static template=`o-spreadsheet-ChartShowValues`;static components={Checkbox:Fk};static props={...wV,defaultValue:{type:Boolean,optional:!0}}},VV=class extends t.Component{static template=`o-spreadsheet-ChartWithAxisDesignPanel`;static components={GeneralDesignEditor:PV,SidePanelCollapsible:Vv,Section:q,AxisDesignEditor:MV,SeriesWithAxisDesignEditor:zV,ChartLegend:IV,ChartShowValues:BV,ChartHumanizeNumbers:FV};static props=wV;get axesList(){let{useLeftAxis:e,useRightAxis:t}=fd(this.props.definition),n=[{id:`x`,name:k(`Horizontal axis`)}];return e&&n.push({id:`y`,name:k(t?`Left axis`:`Vertical axis`)}),t&&n.push({id:`y1`,name:k(e?`Right axis`:`Vertical axis`)}),n}},HV=class extends VV{static template=`o-spreadsheet-GenericZoomableChartDesignPanel`;static components={...VV.components,Checkbox:Fk};onToggleZoom(e){this.props.updateChart(this.props.chartId,{zoomable:e})}},UV=class extends HV{static template=`o-spreadsheet-BarChartDesignPanel`;get isZoomable(){return!this.props.definition.horizontal}};let WV=[`year`,`quarter_number`,`month_number`,`iso_week_number`,`day_of_month`,`day_of_week`,`hour_number`,`minute_number`,`second_number`];var GV=class extends OV{static template=`o-spreadsheet-CalendarChartConfigPanel`;groupByChoices=WV.map(e=>({value:e,label:uh[e]}));getLabelRangeOptions(){return[{name:`dataSetsHaveTitle`,label:this.dataSetsHaveTitleLabel,value:this.props.definition.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}getGroupByOptions(){let e=this.env.model.getters.getFigureSheetId(this.env.model.getters.getFigureIdFromChartId(this.props.chartId)),t=td(this.env.model.getters,this.props.definition.dataSets,e,this.props.definition.dataSetsHaveTitle);if(t.length===0)return[];let n=Zc(this.env.model.getters,e,this.props.definition.labelRange),r=zh(this.props.definition,t,n,this.env.model.getters).labels.filter(e=>xi(e,R));if(r.length===0)return[];let i=r.map(e=>I(e,this.env.model.getters.getLocale())),a=new Set,o=new Set,s=new Set,c=new Set,l=new Set,u=new Set;for(let e of i)a.add(e.getFullYear()),o.add(e.getMonth()),s.add(e.getDate()),c.add(e.getHours()),l.add(e.getMinutes()),u.add(e.getSeconds());return this.groupByChoices.filter(e=>{switch(e.value){case`year`:return a.size>1;case`quarter_number`:case`month_number`:return o.size>1;case`iso_week_number`:case`day_of_month`:case`day_of_week`:return s.size>1;case`hour_number`:return c.size>1;case`minute_number`:return l.size>1;case`second_number`:return u.size>1;default:return!1}})}getGroupByType(e){return(e===`horizontal`?this.props.definition.horizontalGroupBy:this.props.definition.verticalGroupBy)||`year`}updateGroupBy(e,t){this.props.updateChart(this.props.chartId,{[e===`horizontal`?`horizontalGroupBy`:`verticalGroupBy`]:t})}},KV=class extends t.Component{static template=`o-spreadsheet-ColorScalePicker`;static components={Section:q,RoundColorPicker:bk,Popover:Cv};static props={definition:Object,onUpdateColorScale:Function};colorScales=ii.map(e=>({value:e,label:Yp.ColorScales[e],className:`${e}-color-scale`}));state=(0,t.useState)({popoverProps:void 0,popoverStyle:``});popoverRef=(0,t.useRef)(`popoverRef`);setup(){(0,t.useExternalListener)(window,`click`,this.closePopover)}get currentColorScale(){return this.props.definition.colorScale||Mm(`oranges`)}get currentColorScaleStyle(){let e=this.currentColorScale,t=e.minColor||`#fff`,n=e.midColor,r=e.maxColor||`#000`;return n?`background: linear-gradient(90deg, ${t}, ${n}, ${r});`:`background: linear-gradient(90deg, ${t}, ${r});`}colorScalePreviewStyle(e){return`background: linear-gradient(90deg, ${ri[e].join(`,`)});`}get currentColorScaleLabel(){return Yp.ColorScales[this.selectedColorScale]}onColorScaleChange(e){e===`custom`?this.props.onUpdateColorScale(he):this.props.onUpdateColorScale(Mm(e)),this.closePopover()}onPointerDown(e){if(this.state.popoverProps){this.closePopover();return}let{bottom:t,right:n,width:r}=e.currentTarget.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:n,y:t,width:0,height:0},positioning:`top-right`,verticalOffset:0},this.state.popoverStyle=U({width:`${r}px`})}closePopover(){this.state.popoverProps=void 0}get selectedColorScale(){if(!this.props.definition.colorScale)return`oranges`;let{minColor:e,midColor:t,maxColor:n}=this.props.definition.colorScale||{};for(let[r,i]of Object.entries(ri))if(i[0]===e&&i[2]===n&&i[1]===t)return r;return`custom`}getCustomColorScaleColor(e){return this.props.definition.colorScale?.[e]??``}setCustomColorScaleColor(e,t){!t&&e!==`midColor`&&(t=`#fff`);let n=this.currentColorScale;n&&this.props.onUpdateColorScale({...n,[e]:t})}},qV=class extends t.Component{static template=`o-spreadsheet-CalendarChartDesignPanel`;static components={GeneralDesignEditor:PV,SidePanelCollapsible:Vv,Section:q,AxisDesignEditor:MV,ChartShowValues:BV,ColorScalePicker:KV,RoundColorPicker:bk};static props=wV;get axesList(){return[{id:`x`,name:k(`Horizontal axis`)},{id:`y`,name:k(`Vertical axis`)}]}onColormapChange(e){this.props.updateChart(this.props.chartId,{colorScale:e})}updateMissingValueColor(e){this.props.updateChart(this.props.chartId,{missingValueColor:e})}get selectedMissingValueColor(){return this.props.definition.missingValueColor}updateLegendPosition(e){let t=e.target.value;this.props.updateChart(this.props.chartId,{legendPosition:t})}},JV=class extends t.Component{static template=`o-spreadsheet-ChartShowDataMarkers`;static components={Checkbox:Fk};static props=wV},YV=class extends HV{static template=`o-spreadsheet-ComboChartDesignPanel`;static components={...HV.components,ChartShowDataMarkers:JV,RadioSelection:NV};seriesTypeChoices=[{value:`bar`,label:k(`Bar`)},{value:`line`,label:k(`Line`)}];updateDataSeriesType(e,t){let n=[...this.props.definition.dataSets];n?.[e]&&(n[e]={...n[e],type:t},this.props.updateChart(this.props.chartId,{dataSets:n}))}getDataSeriesType(e){let t=this.props.definition.dataSets;return t?.[e]?t[e].type??`line`:`bar`}},XV=class extends OV{getLabelRangeOptions(){let e=this.props.definition;return[{name:`aggregated`,label:this.chartTerms.AggregatedChart,value:e.aggregated??!1,onChange:this.onUpdateAggregated.bind(this)},{name:`cumulative`,label:this.chartTerms.CumulativeData,value:e.cumulative??!1,onChange:this.onUpdateCumulative.bind(this)},{name:`dataSetsHaveTitle`,label:this.dataSetsHaveTitleLabel,value:e.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}onUpdateCumulative(e){this.props.updateChart(this.props.chartId,{cumulative:e})}},ZV=class extends t.Component{static template=`o-spreadsheet-FunnelChartDesignPanel`;static components={ChartShowValues:BV,GeneralDesignEditor:PV,SidePanelCollapsible:Vv,RoundColorPicker:bk,Section:q,ChartHumanizeNumbers:FV};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function};getFunnelColorItems(){let e=this.env.model.getters.getChartRuntime(this.props.chartId).chartJsConfig.data.labels||[],t=sf(e,this.props.definition.funnelColors);return e.map((e,n)=>({label:e||k(`Value %s`,n+1),color:t[n]}))}updateFunnelItemColor(e,t){let n=At(this.props.definition.funnelColors||[],t,e);this.props.updateChart(this.props.chartId,{funnelColors:n})}},QV=class extends t.Component{static template=`o-spreadsheet-GaugeChartConfigPanel`;static components={ChartErrorSection:EV,ChartDataSeries:TV};static props=wV;state=(0,t.useState)({dataRangeDispatchResult:void 0});dataRange=this.props.definition.dataRange;get configurationErrorMessages(){return[...this.state.dataRangeDispatchResult?.reasons||[]].filter(e=>e!==`NoChanges`).map(e=>Yp.Errors[e]||Yp.Errors.Unexpected)}get isDataRangeInvalid(){return!!this.state.dataRangeDispatchResult?.isCancelledBecause(`InvalidGaugeDataRange`)}onDataRangeChanged(e){this.dataRange=e[0],this.state.dataRangeDispatchResult=this.props.canUpdateChart(this.props.chartId,{dataRange:this.dataRange})}updateDataRange(){this.state.dataRangeDispatchResult=this.props.updateChart(this.props.chartId,{dataRange:this.dataRange})}getDataRange(){return{dataRange:this.dataRange||``}}},$V=class extends t.Component{static template=`o-spreadsheet-GaugeChartDesignPanel`;static components={SidePanelCollapsible:Vv,Section:q,RoundColorPicker:bk,GeneralDesignEditor:PV,ChartErrorSection:EV,StandaloneComposer:fk,ChartHumanizeNumbers:FV};static props=wV;state;setup(){this.state=(0,t.useState)({sectionRuleCancelledReasons:new Set(this.checkSectionRuleFormulasAreValid(this.props.definition.sectionRule)),sectionRule:b(this.props.definition.sectionRule)})}get designErrorMessages(){return[...this.state.sectionRuleCancelledReasons||[]].filter(e=>e!==`NoChanges`).map(e=>Yp.Errors[e]||Yp.Errors.Unexpected)}get isRangeMinInvalid(){return!!(this.state.sectionRuleCancelledReasons?.has(`EmptyGaugeRangeMin`)||this.state.sectionRuleCancelledReasons?.has(`GaugeRangeMinNaN`))}get isRangeMaxInvalid(){return!!(this.state.sectionRuleCancelledReasons?.has(`EmptyGaugeRangeMax`)||this.state.sectionRuleCancelledReasons?.has(`GaugeRangeMaxNaN`))}get isLowerInflectionPointInvalid(){return!!this.state.sectionRuleCancelledReasons?.has(`GaugeLowerInflectionPointNaN`)}get isUpperInflectionPointInvalid(){return!!this.state.sectionRuleCancelledReasons?.has(`GaugeUpperInflectionPointNaN`)}updateSectionColor(e,t){let n=b(this.state.sectionRule);n.colors[e]=t,this.updateSectionRule(n)}updateSectionRule(e){this.state.sectionRuleCancelledReasons=new Set(this.checkSectionRuleFormulasAreValid(this.state.sectionRule));let t=this.props.updateChart(this.props.chartId,{sectionRule:e});if(t.isSuccessful)this.state.sectionRule=b(e);else for(let e of t.reasons)this.state.sectionRuleCancelledReasons.add(e)}onConfirmGaugeRange(e,t){this.state.sectionRule={...this.state.sectionRule,[e]:t},this.updateSectionRule(this.state.sectionRule)}getGaugeInflectionComposerProps(e){let t=e===`lowerColor`?`lowerInflectionPoint`:`upperInflectionPoint`,n=this.state.sectionRule[t];return{onConfirm:e=>{this.state.sectionRule={...this.state.sectionRule,[t]:{...n,value:e}},this.updateSectionRule(this.state.sectionRule)},composerContent:n.value,invalid:e===`lowerColor`?this.isLowerInflectionPointInvalid:this.isUpperInflectionPointInvalid,defaultRangeSheetId:this.sheetId,class:t,placeholder:k(`Value`),title:k(`Value or formula`)}}checkSectionRuleFormulasAreValid(e){let t=new Set;return this.valueIsValidNumber(e.rangeMin)||t.add(`GaugeRangeMinNaN`),this.valueIsValidNumber(e.rangeMax)||t.add(`GaugeRangeMaxNaN`),this.valueIsValidNumber(e.lowerInflectionPoint.value)||t.add(`GaugeLowerInflectionPointNaN`),this.valueIsValidNumber(e.upperInflectionPoint.value)||t.add(`GaugeUpperInflectionPointNaN`),t}valueIsValidNumber(e){let t=this.env.model.getters.getLocale();if(!e.startsWith(`=`))return Oa(e,t)!==void 0;let n=this.env.model.getters.evaluateFormula(this.sheetId,e);return gm(n)?!1:Oa(mm(n),t)!==void 0}get sheetId(){let e=this.env.model.getters.getChart(this.props.chartId);if(!e)throw Error(`Chart not found with id `+this.props.chartId);return e.sheetId}},eH=class extends t.Component{static template=`o-spreadsheet-GeoChartRegionSelectSection`;static components={Section:q};static props={chartId:String,definition:Object,updateChart:Function};updateSelectedRegion(e){let t=e.target.value;this.props.updateChart(this.props.chartId,{region:t})}get availableRegions(){return this.env.model.getters.getGeoChartAvailableRegions()}get selectedRegion(){return this.props.definition.region||this.availableRegions[0]?.id}},tH=class extends OV{static template=`o-spreadsheet-GeoChartConfigPanel`;static components={...OV.components,GeoChartRegionSelectSection:eH};get dataRanges(){return this.getDataSeriesRanges()}get disabledRanges(){return this.props.definition.dataSets.map((e,t)=>t>0)}getLabelRangeOptions(){return[{name:`dataSetsHaveTitle`,label:this.dataSetsHaveTitleLabel,value:this.props.definition.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}},nH=class extends VV{static template=`o-spreadsheet-GeoChartDesignPanel`;static components={...VV.components,RoundColorPicker:bk,ColorScalePicker:KV};updateColorScale(e){this.props.updateChart(this.props.chartId,{colorScale:e})}updateMissingValueColor(e){this.props.updateChart(this.props.chartId,{missingValueColor:e})}updateLegendPosition(e){let t=e.target.value;this.props.updateChart(this.props.chartId,{legendPosition:t})}get selectedMissingValueColor(){return this.props.definition.missingValueColor||`#ffffff`}},rH=class extends OV{static template=`o-spreadsheet-HierarchicalChartConfigPanel`;static components={...OV.components};getLabelRangeOptions(){return[{name:`dataSetsHaveTitle`,label:this.dataSetsHaveTitleLabel,value:this.props.definition.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}},iH=class extends OV{static template=`o-spreadsheet-LineConfigPanel`;get canTreatLabelsAsText(){let e=this.env.model.getters.getChart(this.props.chartId);return e&&e instanceof k_?rg(e.getDefinition(),e.dataSets,e.labelRange,this.env.model.getters):!1}get stackedLabel(){return this.props.definition.fillArea?this.chartTerms.StackedAreaChart:this.chartTerms.StackedLineChart}getLabelRangeOptions(){let e=super.getLabelRangeOptions();return this.canTreatLabelsAsText&&e.push({name:`labelsAsText`,value:this.props.definition.labelsAsText,label:this.chartTerms.TreatLabelsAsText,onChange:this.onUpdateLabelsAsText.bind(this)}),e}onUpdateLabelsAsText(e){this.props.updateChart(this.props.chartId,{labelsAsText:e})}onUpdateStacked(e){this.props.updateChart(this.props.chartId,{stacked:e})}onUpdateCumulative(e){this.props.updateChart(this.props.chartId,{cumulative:e})}},aH=class extends HV{static template=`o-spreadsheet-LineChartDesignPanel`;static components={...HV.components,ChartShowDataMarkers:JV}},oH=class extends t.Component{static template=`o-spreadsheet.PieHoleSize`;static components={Section:q,NumberInput:LV};static props={onValueChange:Function,value:Number};onChange(e){isNaN(Number(e))||this.props.onValueChange(x(Number(e),0,95))}},sH=class extends t.Component{static template=`o-spreadsheet-PieChartDesignPanel`;static components={GeneralDesignEditor:PV,Section:q,ChartLegend:IV,ChartShowValues:BV,PieHoleSize:oH,Checkbox:Fk,ChartHumanizeNumbers:FV};static props=wV;onPieHoleSizeChange(e){this.props.updateChart(this.props.chartId,{...this.props.definition,pieHolePercentage:e})}get defaultHoleSize(){return 50}},cH=class extends t.Component{static template=`o-spreadsheet-RadarChartDesignPanel`;static components={GeneralDesignEditor:PV,SeriesDesignEditor:RV,Section:q,ChartLegend:IV,ChartShowValues:BV,ChartShowDataMarkers:JV,Checkbox:Fk,ChartHumanizeNumbers:FV};static props=wV},lH=class e extends Af{dataSets;labelRange;background;legendPosition;labelsAsText;aggregated;type=`scatter`;dataSetsHaveTitle;dataSetDesign;axesDesign;showValues;constructor(e,t,n){super(e,t,n),this.dataSets=td(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Zc(this.getters,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.labelsAsText=e.labelsAsText,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues}static validateChartDefinition(e,t){return e.checkValidations(t,cd,ld)}static transformDefinition(e,t,n){return ad(e,t,n)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,labelsAsText:e.labelsAsText??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`scatter`,labelRange:e.auxiliaryRange||void 0,aggregated:e.aggregated??!1,axesDesign:e.axesDesign,showValues:e.showValues,humanize:e.humanize}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`scatter`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,labelsAsText:this.labelsAsText,aggregated:this.aggregated,axesDesign:this.axesDesign,showValues:this.showValues,humanize:this.humanize}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=Zu(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}getDefinitionForExcel(){let e=this.dataSets.map(e=>rd(this.getters,e)).filter(e=>e.range!==``),t=id(this.getters,this.labelRange,ud(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),n=this.getDefinition();return{...n,backgroundColor:V(this.background||`#FFFFFF`),fontColor:V(od(this.background)),dataSets:e,labelRange:t,verticalAxis:fd(n)}}duplicateInDuplicatedSheet(t){let n=Qu(this.sheetId,t,this.dataSets),r=$u(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}};function uH(e,t){let n=e.getDefinition(),r=Wh(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`line`,data:{labels:r.labels,datasets:ef(n,r)},options:{...Vp,layout:Tg(n,r),scales:Ld(n,r),plugins:{title:Gg(n,t),legend:jg(n,r),tooltip:Zg(n,r),chartShowValuesPlugin:zg(n,r)}}},background:e.background||`#FFFFFF`}}var dH=class extends OV{static template=`o-spreadsheet-ScatterConfigPanel`;get canTreatLabelsAsText(){let e=this.env.model.getters.getChart(this.props.chartId);return e&&e instanceof lH?rg(e.getDefinition(),e.dataSets,e.labelRange,this.env.model.getters):!1}onUpdateLabelsAsText(e){this.props.updateChart(this.props.chartId,{labelsAsText:e})}getLabelRangeOptions(){let e=super.getLabelRangeOptions();return this.canTreatLabelsAsText&&e.push({name:`labelsAsText`,value:this.props.definition.labelsAsText,label:this.chartTerms.TreatLabelsAsText,onChange:this.onUpdateLabelsAsText.bind(this)}),e}},fH=class extends t.Component{static template=`o-spreadsheet-ScorecardChartConfigPanel`;static components={SelectionInput:kk,ChartErrorSection:EV,Section:q};static props=wV;state=(0,t.useState)({keyValueDispatchResult:void 0,baselineDispatchResult:void 0});keyValue=this.props.definition.keyValue;baseline=this.props.definition.baseline;get errorMessages(){return[...this.state.keyValueDispatchResult?.reasons||[],...this.state.baselineDispatchResult?.reasons||[]].filter(e=>e!==`NoChanges`).map(e=>Yp.Errors[e]||Yp.Errors.Unexpected)}get isKeyValueInvalid(){return!!this.state.keyValueDispatchResult?.isCancelledBecause(`InvalidScorecardKeyValue`)}get isBaselineInvalid(){return!!this.state.keyValueDispatchResult?.isCancelledBecause(`InvalidScorecardBaseline`)}onKeyValueRangeChanged(e){this.keyValue=e[0],this.state.keyValueDispatchResult=this.props.canUpdateChart(this.props.chartId,{keyValue:this.keyValue})}updateKeyValueRange(){this.state.keyValueDispatchResult=this.props.updateChart(this.props.chartId,{keyValue:this.keyValue})}getKeyValueRange(){return this.keyValue||``}onBaselineRangeChanged(e){this.baseline=e[0],this.state.baselineDispatchResult=this.props.canUpdateChart(this.props.chartId,{baseline:this.baseline})}updateBaselineRange(){this.state.baselineDispatchResult=this.props.updateChart(this.props.chartId,{baseline:this.baseline})}getBaselineRange(){return this.baseline||``}updateBaselineMode(e){this.props.updateChart(this.props.chartId,{baselineMode:e.target.value})}},pH=class extends t.Component{static template=`o-spreadsheet-ScorecardChartDesignPanel`;static components={GeneralDesignEditor:PV,RoundColorPicker:bk,SidePanelCollapsible:Vv,Section:q,Checkbox:Fk,ChartTitle:jV,ChartHumanizeNumbers:FV};static props=wV;get colorsSectionTitle(){return this.props.definition.baselineMode===`progress`?k(`Progress bar colors`):k(`Baseline colors`)}get defaultScorecardTitleFontSize(){return 14}translate(e){return this.env.model.getters.dynamicTranslate(e)}setColor(e,t){switch(t){case`backgroundColor`:this.props.updateChart(this.props.chartId,{background:e});break;case`baselineColorDown`:this.props.updateChart(this.props.chartId,{baselineColorDown:e});break;case`baselineColorUp`:this.props.updateChart(this.props.chartId,{baselineColorUp:e});break}}get keyStyle(){return{align:`center`,fontSize:32,...this.props.definition.keyDescr}}get baselineStyle(){return{align:`center`,fontSize:16,...this.props.definition.baselineDescr}}setKeyText(e){this.props.updateChart(this.props.chartId,{keyDescr:{...this.props.definition.keyDescr,text:e}})}updateKeyStyle(e){let t={...this.keyStyle,...e};this.props.updateChart(this.props.chartId,{keyDescr:t})}setBaselineText(e){this.props.updateChart(this.props.chartId,{baselineDescr:{...this.props.definition.baselineDescr,text:e}})}updateBaselineStyle(e){let t={...this.baselineStyle,...e};this.props.updateChart(this.props.chartId,{baselineDescr:t})}},mH=class extends t.Component{static template=`o-spreadsheet-SunburstChartDesignPanel`;static components={GeneralDesignEditor:PV,Section:q,SidePanelCollapsible:Vv,ChartShowValues:BV,Checkbox:Fk,TextStyler:xV,RoundColorPicker:bk,ChartLegend:IV,PieHoleSize:oH,ChartHumanizeNumbers:FV};static props=wV;defaults=Rg;get showValues(){return this.props.definition.showValues??Rg.showValues}get showLabels(){return this.props.definition.showLabels??Rg.showLabels}get groupColors(){let e=this.props.chartId;return this.env.model.getters.getChartRuntime(e).chartJsConfig.data.datasets[0]?.groupColors||[]}onGroupColorChanged(e,t){let n=b(this.props.definition.groupColors)??[];n[e]=t,this.props.updateChart(this.props.chartId,{groupColors:n})}onPieHoleSizeChange(e){this.props.updateChart(this.props.chartId,{...this.props.definition,pieHolePercentage:e})}},hH=class extends t.Component{static template=`o-spreadsheet-TreeMapCategoryColors`;static components={Checkbox:Fk,RoundColorPicker:bk};static props={chartId:String,definition:Object,onColorChanged:Function};get coloringOptions(){let e=this.props.definition.coloringOptions??Td.coloringOptions;if(e.type!==`categoryColor`)throw Error(`Coloring options is not solid color`);return e}getTreeGroupAndColors(){return this.env.model.getters.getChartRuntime(this.props.chartId).chartJsConfig.data.datasets[0]?.groupColors||[]}onGroupColorChanged(e,t){let n=b(this.coloringOptions);n.colors[e]=t||void 0,this.props.onColorChanged(n)}useValueBasedGradient(e){if(this.coloringOptions.type!==`categoryColor`)throw Error(`Coloring options is not solid color`);this.props.onColorChanged({...this.coloringOptions,useValueBasedGradient:e})}},gH=class extends t.Component{static template=`o-spreadsheet-TreeMapColorScale`;static components={RoundColorPicker:bk};static props={chartId:String,definition:Object,onColorChanged:Function};get coloringOptions(){let e=this.props.definition.coloringOptions??Td.coloringOptions;if(e.type!==`colorScale`)throw Error(`Coloring options is not a color scale`);return e}setColorScaleColor(e,t){this.props.onColorChanged({...this.coloringOptions,[e]:t})}};let _H={type:`colorScale`,minColor:`#FFF5EB`,midColor:`#FD8D3C`,maxColor:`#7F2704`},vH={type:`categoryColor`,colors:[],useValueBasedGradient:!0};var yH=class extends t.Component{static template=`o-spreadsheet-TreeMapChartDesignPanel`;static components={GeneralDesignEditor:PV,Section:q,SidePanelCollapsible:Vv,ChartShowValues:BV,Checkbox:Fk,TextStyler:xV,RoundColorPicker:bk,BadgeSelection:AV,TreeMapCategoryColors:hH,TreeMapColorScale:gH,ChartHumanizeNumbers:FV};static props=wV;savedColors={categoryColors:vH,colorScale:_H};defaults=Td;get showHeaders(){return this.props.definition.showHeaders??Td.showHeaders}get showValues(){return this.props.definition.showValues??Td.showValues}get showLabels(){return this.props.definition.showLabels??Td.showLabels}get coloringOptions(){return this.props.definition.coloringOptions??Td.coloringOptions}changeColoringOption(e){let t=e===`categoryColor`?this.savedColors.categoryColors:this.savedColors.colorScale;this.props.updateChart(this.props.chartId,{coloringOptions:t})}onCategoryColorChange(e){this.savedColors.categoryColors=e,this.props.updateChart(this.props.chartId,{coloringOptions:e})}onColorScaleChange(e){this.savedColors.colorScale=e,this.props.updateChart(this.props.chartId,{coloringOptions:e})}get coloringOptionChoices(){return[{label:k(`Category color`),value:`categoryColor`},{label:k(`Color scale`),value:`colorScale`}]}},bH=class extends t.Component{static template=`o-spreadsheet-WaterfallChartDesignPanel`;static components={GeneralDesignEditor:PV,ChartShowValues:BV,Checkbox:Fk,SidePanelCollapsible:Vv,Section:q,RoundColorPicker:bk,AxisDesignEditor:MV,RadioSelection:NV,ChartLegend:IV,ChartHumanizeNumbers:FV};static props=wV;axisChoices=hd;onUpdateShowSubTotals(e){this.props.updateChart(this.props.chartId,{showSubTotals:e})}onUpdateShowConnectorLines(e){this.props.updateChart(this.props.chartId,{showConnectorLines:e})}onUpdateFirstValueAsSubtotal(e){this.props.updateChart(this.props.chartId,{firstValueAsSubtotal:e})}updateColor(e,t){this.props.updateChart(this.props.chartId,{[e]:t})}get axesList(){return[{id:`x`,name:k(`Horizontal axis`)},{id:`y`,name:k(`Vertical axis`)}]}get positiveValuesColor(){return this.props.definition.positiveValuesColor||`#4EA7F2`}get negativeValuesColor(){return this.props.definition.negativeValuesColor||`#EA6175`}get subTotalValuesColor(){return this.props.definition.subTotalValuesColor||`#AAAAAA`}updateVerticalAxisPosition(e){this.props.updateChart(this.props.chartId,{verticalAxisPosition:e})}onToggleZoom(e){this.props.updateChart(this.props.chartId,{zoomable:e})}};let xH=new B;xH.add(`line`,{configuration:iH,design:aH}).add(`scatter`,{configuration:dH,design:VV}).add(`bar`,{configuration:kV,design:UV}).add(`combo`,{configuration:OV,design:YV}).add(`pie`,{configuration:OV,design:sH}).add(`gauge`,{configuration:QV,design:$V}).add(`scorecard`,{configuration:fH,design:pH}).add(`waterfall`,{configuration:OV,design:bH}).add(`pyramid`,{configuration:OV,design:VV}).add(`radar`,{configuration:OV,design:cH}).add(`sunburst`,{configuration:rH,design:mH}).add(`geo`,{configuration:tH,design:nH}).add(`funnel`,{configuration:XV,design:ZV}).add(`treemap`,{configuration:rH,design:yH}).add(`calendar`,{configuration:GV,design:qV});let SH={line:k(`Line`),column:k(`Column`),bar:k(`Bar`),area:k(`Area`),pie:k(`Pie`),hierarchical:k(`Hierarchical`),misc:k(`Miscellaneous`)};var CH=class extends t.Component{static template=`o-spreadsheet-ChartTypePicker`;static components={Section:q,Popover:Cv};static props={chartId:String,chartPanelStore:Object};categories=SH;chartTypeByCategories={};popoverRef=(0,t.useRef)(`popoverRef`);selectRef=(0,t.useRef)(`selectRef`);state=(0,t.useState)({popoverProps:void 0,popoverStyle:``});setup(){(0,t.useExternalListener)(window,`pointerdown`,this.onExternalClick,{capture:!0});for(let e of K_.getAll())this.chartTypeByCategories[e.category]?this.chartTypeByCategories[e.category].push(e):this.chartTypeByCategories[e.category]=[e]}onExternalClick(e){Zf(this.popoverRef.el?.parentElement,e)||Zf(this.selectRef.el,e)||this.closePopover()}onTypeChange(e){this.props.chartPanelStore.changeChartType(this.props.chartId,e),this.closePopover()}getChartDefinition(e){return this.env.model.getters.getChartDefinition(e)}getSelectedChartSubtypeProperties(){let e=this.getChartDefinition(this.props.chartId);return K_.getAll().find(t=>t.matcher?.(e)||!1)||K_.get(e.type)}onPointerDown(e){if(this.state.popoverProps){this.closePopover();return}let{bottom:t,right:n,width:r}=e.currentTarget.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:n,y:t,width:0,height:0},positioning:`top-right`,verticalOffset:0},this.state.popoverStyle=U({width:`${r}px`})}closePopover(){this.state.popoverProps=void 0}},wH=class extends hr{mutators=[`activatePanel`,`changeChartType`];panel=`configuration`;creationContexts={};activatePanel(e){this.panel=e}changeChartType(e,t){let n=this.getters.getContextCreationChart(e),r=this.creationContexts[e]||{},i=n?.range;i?.every((e,t)=>w(e,r.range?.[t]))&&(i=Object.assign([],r.range,n?.range)),this.creationContexts[e]={...r,...n,range:i};let a=this.getters.getFigureIdFromChartId(e),o=this.getters.getFigureSheetId(a);if(!o)return;let s=this.getChartDefinitionFromContextCreation(e,t);this.model.dispatch(`UPDATE_CHART`,{definition:s,chartId:e,figureId:a,sheetId:o})}getChartDefinitionFromContextCreation(e,t){let n=K_.get(t);return{...f_.get(n.chartType).getChartDefinitionFromContextCreation(this.creationContexts[e]),...n.subtypeDefinition}}},TH=class extends t.Component{static template=`o-spreadsheet-ChartPanel`;static components={Section:q,ChartTypePicker:CH};static props={onCloseSidePanel:Function,chartId:String};store;get chartId(){return this.props.chartId}setup(){this.store=or(wH)}switchPanel(e){this.store.activatePanel(e)}updateChart(e,t){let n=this.env.model.getters.getFigureIdFromChartId(e);if(e!==this.chartId)return;let r={...this.getChartDefinition(this.chartId),...t};return this.env.model.dispatch(`UPDATE_CHART`,{definition:r,chartId:e,figureId:n,sheetId:this.env.model.getters.getFigureSheetId(n)})}canUpdateChart(e,t){let n=this.env.model.getters.getFigureIdFromChartId(e);if(e!==this.chartId||!this.env.model.getters.isChartDefined(e))return;let r={...this.getChartDefinition(this.chartId),...t};return this.env.model.canDispatch(`UPDATE_CHART`,{definition:r,chartId:e,figureId:n,sheetId:this.env.model.getters.getFigureSheetId(n)})}onTypeChange(e){this.chartId&&this.store.changeChartType(this.chartId,e)}get chartPanel(){if(!this.chartId)throw Error(`Chart not defined.`);let e=this.env.model.getters.getChartType(this.chartId);if(!e)throw Error(`Chart not defined.`);let t=xH.get(e);if(!t)throw Error(`Component is not defined for type ${e}`);return t}getChartDefinition(e){return this.env.model.getters.getChartDefinition(e)}},EH=class extends t.Component{static template=`o-spreadsheet-IconPicker`;static props={onIconPicked:Function};icons=cj;iconSets=lj;onIconClick(e){e&&this.props.onIconPicked(e)}};function DH(e,t){let n=zB(e);OH({get highlights(){return n.hovered?t.highlights:[]}})}function OH(e){let n=ar(),r=or(sk);(0,t.onMounted)(()=>{r.register(e)});let i=e.highlights;(0,t.useEffect)(e=>{w(e,i)||(i=e,n.trigger(`store-updated`))},()=>[e.highlights])}var kH=class extends t.Component{static template=`o-spreadsheet-ConditionalFormatPreview`;icons=cj;ref=(0,t.useRef)(`cfPreview`);setup(){DH(this.ref,this)}getPreviewImageStyle(){let e=this.props.conditionalFormat.rule;if(e.type===`CellIsRule`)return U(uv(e.style));if(e.type===`ColorScaleRule`){let t=Sr(e.minimum.color),n=e.midpoint?Sr(e.midpoint.color):null,r=Sr(e.maximum.color),i=`background-image: linear-gradient(to right, `;return n?i+t+`, `+n+`, `+r+`)`:i+t+`, `+r+`)`}else if(e.type===`DataBarRule`)return`${`background-image: linear-gradient(to right, ${Sr(e.color)} 50%, white 50%)`}; color: ${pe};`;return``}getDescription(){let e=this.props.conditionalFormat;switch(e.rule.type){case`CellIsRule`:return W.get(e.rule.operator).getPreview({...e.rule,type:e.rule.operator},this.env.model.getters);case`ColorScaleRule`:return Jp.ColorScale;case`IconSetRule`:return Jp.IconSet;case`DataBarRule`:return Jp.DataBar}}deleteConditionalFormat(){this.env.model.dispatch(`REMOVE_CONDITIONAL_FORMAT`,{id:this.props.conditionalFormat.id,sheetId:this.env.model.getters.getActiveSheetId()})}onMouseDown(e){this.props.onMouseDown(e)}get highlights(){let e=this.env.model.getters.getActiveSheetId();return this.props.conditionalFormat.ranges.map(t=>({range:this.env.model.getters.getRangeFromSheetXC(e,t),color:ee,fillAlpha:.06}))}};kH.props={conditionalFormat:Object,onPreviewClick:Function,onMouseDown:Function,class:String};var AH=class extends t.Component{static template=`o-spreadsheet-ConditionalFormatPreviewList`;static props={conditionalFormats:Array,onPreviewClick:Function,onAddConditionalFormat:Function};static components={ConditionalFormatPreview:kH};icons=cj;dragAndDrop=Sk();cfListRef=(0,t.useRef)(`cfList`);setup(){(0,t.onWillUpdateProps)(e=>{w(this.props.conditionalFormats,e.conditionalFormats)||this.dragAndDrop.cancel()})}getPreviewDivStyle(e){return this.dragAndDrop.itemsStyle[e.id]||``}onPreviewMouseDown(e,t){if(t.button!==0)return;let n=Array.from(this.cfListRef.el.children).map(e=>tp(e)),r=this.props.conditionalFormats.map((e,t)=>({id:e.id,size:n[t].height,position:n[t].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.id,initialMousePosition:t.clientY,items:r,scrollableContainerEl:this.cfListRef.el,onDragEnd:(e,t)=>this.onDragEnd(e,t)})}onDragEnd(e,t){let n=this.props.conditionalFormats.findIndex(t=>t.id===e)-t;n!==0&&this.env.model.dispatch(`CHANGE_CONDITIONAL_FORMAT_PRIORITY`,{cfId:e,delta:n,sheetId:this.env.model.getters.getActiveSheetId()})}},jH=class extends t.Component{static template=`o-spreadsheet-ConditionalFormattingEditor`;static props={editedCf:Object,onCancel:Function,onExit:Function,isNewCf:Boolean};static components={SelectionInput:kk,IconPicker:EH,ColorPickerWidget:vV,ConditionalFormatPreviewList:AH,Section:q,RoundColorPicker:bk,StandaloneComposer:fk,BadgeSelection:AV,ValidationMessages:IB,SelectMenu:Nk};icons=cj;iconSets=lj;getTextDecoration=lv;colorNumberToHex=Sr;state;setup(){switch(this.state=(0,t.useState)({errors:[],currentCFType:this.props.editedCf.rule.type,ranges:this.props.editedCf.ranges,rules:this.getDefaultRules(),hasEditedCf:this.props.isNewCf}),this.props.editedCf.rule.type){case`CellIsRule`:this.state.rules.cellIs=this.props.editedCf.rule;break;case`ColorScaleRule`:this.state.rules.colorScale=this.props.editedCf.rule;break;case`IconSetRule`:this.state.rules.iconSet=this.props.editedCf.rule;break;case`DataBarRule`:this.state.rules.dataBar=this.props.editedCf.rule;break}(0,t.useExternalListener)(window,`click`,this.closeMenus)}get isRangeValid(){return this.state.errors.includes(`EmptyRange`)}get errorMessages(){return this.state.errors.map(e=>Jp.Errors[e]||Jp.Errors.Unexpected)}get cfTypesValues(){return[{value:`CellIsRule`,label:k(`Single color`)},{value:`ColorScaleRule`,label:k(`Color scale`)},{value:`IconSetRule`,label:k(`Icon set`)},{value:`DataBarRule`,label:k(`Data bar`)}]}updateConditionalFormat(e){let t=e.ranges||this.state.ranges;if(this.state.ranges.some(e=>!e.match(Oc)))return e.suppressErrors||(this.state.errors=[`InvalidRange`]),[`InvalidRange`];let n=this.env.model.getters.getActiveSheetId(),r=this.env.model.getters.getLocale(),i=e.rule||this.getEditedRule(this.state.currentCFType),a=this.env.model.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{rule:ty(i,r),id:this.props.editedCf.id},ranges:t.map(e=>this.env.model.getters.getRangeDataFromXc(n,e)),sheetId:n});a.isSuccessful&&(this.state.hasEditedCf=!0);let o=a.reasons.filter(e=>e!==`NoChanges`);return e.suppressErrors||(this.state.errors=o),o}getEditedRule(e){switch(e){case`CellIsRule`:return this.state.rules.cellIs;case`ColorScaleRule`:return this.state.rules.colorScale;case`IconSetRule`:return this.state.rules.iconSet;case`DataBarRule`:return this.state.rules.dataBar}}onSave(){this.updateConditionalFormat({}).length===0&&this.props.onExit()}onCancel(){this.state.hasEditedCf?this.props.onCancel():this.props.onExit()}getDefaultRules(){return{cellIs:{type:`CellIsRule`,operator:`isNotEmpty`,values:[],style:{fillColor:`#b6d7a8`}},colorScale:{type:`ColorScaleRule`,minimum:{type:`value`,color:qj(`EFF7FF`)},midpoint:void 0,maximum:{type:`value`,color:6989903}},iconSet:{type:`IconSetRule`,icons:{upper:`arrowGood`,middle:`arrowNeutral`,lower:`arrowBad`},upperInflectionPoint:{type:`percentage`,value:`66`,operator:`gt`},lowerInflectionPoint:{type:`percentage`,value:`33`,operator:`gt`}},dataBar:{type:`DataBarRule`,color:14281427}}}changeRuleType(e){this.state.currentCFType!==e&&(this.state.errors=[],this.state.currentCFType=e,this.updateConditionalFormat({rule:this.getEditedRule(e),suppressErrors:!0}))}onRangeUpdate(e){this.state.ranges=e}onRangeConfirmed(){this.updateConditionalFormat({ranges:this.state.ranges})}toggleMenu(e){let t=this.state.openedMenu===e;this.closeMenus(),t||(this.state.openedMenu=e)}closeMenus(){this.state.openedMenu=void 0}get isValue1Invalid(){return this.state.errors.includes(`FirstArgMissing`)||this.state.errors.includes(`ValueCellIsInvalidFormula`)}get isValue2Invalid(){return this.state.errors.includes(`SecondArgMissing`)}toggleStyle(e){let t=this.state.rules.cellIs.style;t[e]=!t[e],this.updateConditionalFormat({rule:this.state.rules.cellIs}),this.closeMenus()}onKeydown(e){if(e.key===`F4`){let t=e.target,n=ik({start:t.selectionStart??0,end:t.selectionEnd??0},t.value,this.env.model.getters.getLocale());if(!n)return;t.value=n.content,t.setSelectionRange(n.selection.start,n.selection.end),t.dispatchEvent(new Event(`input`))}}setColor(e,t){this.state.rules.cellIs.style[e]=t,this.updateConditionalFormat({rule:this.state.rules.cellIs}),this.closeMenus()}editOperator(e){this.state.rules.cellIs.operator=e,e.includes(`date`)&&!this.state.rules.cellIs.dateValue&&(this.state.rules.cellIs.dateValue=`exactDate`),this.updateConditionalFormat({rule:this.state.rules.cellIs,suppressErrors:!0}),this.closeMenus()}get cfCriterionMenuItems(){return Mk(e=>this.editOperator(e),Nm)}get selectedCriterionName(){return W.get(this.state.rules.cellIs.operator).name}get criterionComponent(){return J.get(this.state.rules.cellIs.operator).component}get genericCriterion(){return{type:this.state.rules.cellIs.operator,values:this.state.rules.cellIs.values,dateValue:this.state.rules.cellIs.dateValue}}onRuleValuesChanged(e){this.state.rules.cellIs.values=e.values,this.state.rules.cellIs.dateValue=e.dateValue,this.updateConditionalFormat({rule:{...this.state.rules.cellIs,values:e.values,dateValue:e.dateValue}})}isValueInvalid(e){switch(e){case`minimum`:return this.state.errors.includes(`MinInvalidFormula`)||this.state.errors.includes(`MinBiggerThanMid`)||this.state.errors.includes(`MinBiggerThanMax`)||this.state.errors.includes(`MinNaN`);case`midpoint`:return this.state.errors.includes(`MidInvalidFormula`)||this.state.errors.includes(`MidNaN`)||this.state.errors.includes(`MidBiggerThanMax`);case`maximum`:return this.state.errors.includes(`MaxInvalidFormula`)||this.state.errors.includes(`MaxNaN`);default:return!1}}setColorScaleColor(e,t){if(!Tr(t))return;let n=this.state.rules.colorScale[e];n&&(n.color=Cr(t)),this.updateConditionalFormat({rule:this.state.rules.colorScale}),this.closeMenus()}getColorScalePreviewStyle(){let e=this.state.rules.colorScale,t=Sr(e.minimum.color),n=Sr(e.midpoint?.color||11982760),r=Sr(e.maximum.color),i=`linear-gradient(to right, `;return U({"background-image":e.midpoint===void 0?i+t+`, `+r+`)`:i+t+`, `+n+`, `+r+`)`,color:`#000`})}getThresholdColor(e){return Sr(e?e.color:se)}onMidpointChange(e){let t=e.target.value,n=this.state.rules.colorScale;t===`none`?n.midpoint=void 0:n.midpoint={color:se,value:``,...n.midpoint,type:t},this.updateConditionalFormat({rule:n,suppressErrors:!0})}updateThresholdType(e,t){this.state.rules.colorScale[e].type=t,this.updateConditionalFormat({rule:this.state.rules.colorScale,suppressErrors:!0})}updateThresholdValue(e,t){this.state.rules.colorScale[e].value=t,this.updateConditionalFormat({rule:this.state.rules.colorScale})}isInflectionPointInvalid(e){switch(e){case`lowerInflectionPoint`:return this.state.errors.includes(`ValueLowerInflectionNaN`)||this.state.errors.includes(`ValueLowerInvalidFormula`)||this.state.errors.includes(`LowerBiggerThanUpper`);case`upperInflectionPoint`:return this.state.errors.includes(`ValueUpperInflectionNaN`)||this.state.errors.includes(`ValueUpperInvalidFormula`)||this.state.errors.includes(`LowerBiggerThanUpper`);default:return!0}}reverseIcons(){let e=this.state.rules.iconSet.icons,t=e.upper;e.upper=e.lower,e.lower=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setIconSet(e){let t=this.state.rules.iconSet.icons;t.upper=this.iconSets[e].good,t.middle=this.iconSets[e].neutral,t.lower=this.iconSets[e].bad,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setIcon(e,t){this.state.rules.iconSet.icons[e]=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setInflectionOperator(e,t){this.state.rules.iconSet[e].operator=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setInflectionValue(e,t){this.state.rules.iconSet[e].value=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setInflectionType(e,t,n){this.state.rules.iconSet[e].type=t,this.updateConditionalFormat({rule:this.state.rules.iconSet,suppressErrors:!0})}getColorScaleComposerProps(e){let t=this.state.rules.colorScale[e];if(!t)throw Error(`Threshold not found`);let n=this.isValueInvalid(e);return{onConfirm:e=>{t.value=e,this.updateConditionalFormat({rule:this.state.rules.colorScale})},composerContent:t.value||``,placeholder:k(`Formula`),defaultStatic:!0,invalid:n,class:`o-sidePanel-composer`,defaultRangeSheetId:this.env.model.getters.getActiveSheetId()}}getColorIconSetComposerProps(e){let t=this.state.rules.iconSet[e],n=this.isInflectionPointInvalid(e);return{onConfirm:e=>{t.value=e,this.updateConditionalFormat({rule:this.state.rules.iconSet})},composerContent:t.value||``,placeholder:k(`Formula`),defaultStatic:!0,invalid:n,class:`o-sidePanel-composer`,defaultRangeSheetId:this.env.model.getters.getActiveSheetId()}}getRangeValues(){return[this.state.rules.dataBar.rangeValues||``]}updateDataBarColor(e){Tr(e)&&(this.state.rules.dataBar.color=Number.parseInt(e.slice(1),16),this.updateConditionalFormat({rule:this.state.rules.dataBar}))}onDataBarRangeUpdate(e){this.state.rules.dataBar.rangeValues=e[0]}onDataBarRangeChange(){this.updateConditionalFormat({rule:this.state.rules.dataBar})}},MH=class extends t.Component{static template=`o-spreadsheet-ConditionalFormattingPanel`;static props={selection:{type:Object,optional:!0},onCloseSidePanel:Function};static components={ConditionalFormatPreviewList:AH,ConditionalFormattingEditor:jH,Section:q};activeSheetId;originalEditedCf=void 0;state=(0,t.useState)({mode:`list`});setup(){this.activeSheetId=this.env.model.getters.getActiveSheetId();let e=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getRulesSelection(e,this.props.selection||[]);if(n.length===1){let e=this.conditionalFormats.find(e=>e.id===n[0]);e&&this.editConditionalFormat(e)}(0,t.onWillUpdateProps)(e=>{let t=this.env.model.getters.getActiveSheetId();if(t!==this.activeSheetId)this.activeSheetId=t,this.switchToList();else if(e.selection!==this.props.selection){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getRulesSelection(t,e.selection||[]);if(n.length===1){let e=this.conditionalFormats.find(e=>e.id===n[0]);e&&this.editConditionalFormat(e)}else this.switchToList()}else this.editedCF||this.switchToList()})}get conditionalFormats(){return this.env.model.getters.getConditionalFormats(this.env.model.getters.getActiveSheetId()).map(e=>({...e,rule:ny(e.rule,this.env.model.getters.getLocale())}))}switchToList(){this.state.mode=`list`,this.state.editedCfId=void 0,this.originalEditedCf=void 0}addConditionalFormat(){let e=this.env.model.uuidGenerator.smallUuid();this.env.model.dispatch(`ADD_CONDITIONAL_FORMAT`,{sheetId:this.activeSheetId,ranges:this.env.model.getters.getSelectedZones().map(e=>this.env.model.getters.getRangeDataFromZone(this.activeSheetId,e)),cf:{id:e,rule:{type:`CellIsRule`,operator:`isNotEmpty`,style:{fillColor:`#b6d7a8`},values:[]}}}),this.state.editedCfId=e,this.state.mode=`edit`,this.originalEditedCf=void 0}editConditionalFormat(e){this.state.mode=`edit`,this.state.editedCfId=e.id,this.originalEditedCf=e}cancelEdition(){this.originalEditedCf?this.env.model.dispatch(`ADD_CONDITIONAL_FORMAT`,{sheetId:this.activeSheetId,ranges:this.originalEditedCf.ranges.map(e=>this.env.model.getters.getRangeDataFromXc(this.activeSheetId,e)),cf:this.originalEditedCf}):this.state.editedCfId&&this.env.model.dispatch(`REMOVE_CONDITIONAL_FORMAT`,{sheetId:this.activeSheetId,id:this.state.editedCfId}),this.switchToList()}get editedCF(){return this.conditionalFormats.find(e=>e.id===this.state.editedCfId)}},NH=class extends t.Component{static template=`o-spreadsheet-DataValidationEditor`;static components={SelectionInput:kk,SelectMenu:Nk,Section:q,ValidationMessages:IB};static props={rule:{type:Object,optional:!0},onExit:Function,onCloseSidePanel:{type:Function,optional:!0}};state=(0,t.useState)({rule:this.defaultDataValidationRule,errors:[],isTypeUpdated:!1});editingSheetId;setup(){this.editingSheetId=this.env.model.getters.getActiveSheetId(),this.props.rule&&(this.state.rule={...this.props.rule,ranges:this.props.rule.ranges.map(e=>this.env.model.getters.getRangeString(e,this.editingSheetId))},this.state.rule.criterion.type=this.props.rule.criterion.type)}onCriterionTypeChanged(e){this.state.rule.criterion.type=e,this.state.isTypeUpdated=!0}onRangesChanged(e){this.state.rule.ranges=e}onCriterionChanged(e){this.state.rule.criterion=e}changeRuleIsBlocking(e){let t=e.target.value;this.state.rule.isBlocking=t===`true`}onSave(){if(this.state.rule){let e=this.env.model.dispatch(`ADD_DATA_VALIDATION_RULE`,this.dispatchPayload);e.isSuccessful?this.props.onExit():this.state.errors=e.reasons}}get dispatchPayload(){let e={...this.state.rule,ranges:void 0},t=this.env.model.getters.getLocale(),n=e.criterion,r=W.get(n.type),i=n.values.slice(0,r.numberOfValues(n)).filter(e=>e&&e.trim()!==``).map(e=>Gv(e,t));return e.criterion={...n,values:i},{sheetId:this.editingSheetId,ranges:this.state.rule.ranges.map(e=>this.env.model.getters.getRangeDataFromXc(this.editingSheetId,e)),rule:e}}get dvCriterionMenuItems(){return Mk(e=>this.onCriterionTypeChanged(e),Pm)}get selectedCriterionName(){let e=this.state.rule.criterion.type;return W.get(e).name}get defaultDataValidationRule(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones().map(t=>hn(this.env.model.getters.getUnboundedZone(e,t)));return{id:this.env.model.uuidGenerator.smallUuid(),criterion:{type:`containsText`,values:[``]},ranges:t}}get criterionComponent(){return J.get(this.state.rule.criterion.type).component}get errorMessages(){return this.state.errors.map(e=>H.Errors[e]||H.Errors.Unexpected)}},PH=class extends t.Component{static template=`o-spreadsheet-DataValidationPreview`;static props={onClick:Function,rule:Object};ref=(0,t.useRef)(`dvPreview`);setup(){DH(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=>({range:e,color:ee,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 W.get(this.props.rule.criterion.type).getPreview(this.props.rule.criterion,this.env.model.getters)}},FH=class extends t.Component{static template=`o-spreadsheet-DataValidationPanel`;static props={onCloseSidePanel:Function};static components={DataValidationPreview:PH,DataValidationEditor:NH};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&&ry(e,this.env.model.getters.getLocale())}get validationRules(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getDataValidationRules(e)}};let IH=`#8B008B`;var LH=class extends hr{mutators=[`updateSearchOptions`,`updateSearchContent`,`searchFormulas`,`selectPreviousMatch`,`selectNextMatch`,`replace`];allSheetsMatches=[];activeSheetMatches=[];specificRangeMatches=[];currentSearchRegex=null;initialShowFormulaState;preserveSelectedMatchIndex=!1;irreplaceableMatchCount=0;isSearchDirty=!1;shouldFinalizeUpdateSelection=!1;notificationStore=this.get(ck);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(sk);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,{jumpToMatchSheet:!0,updateSelection:!0})}selectNextMatch(){this.selectNextCell(1,{jumpToMatchSheet:!0,updateSelection:!0})}handle(e){switch(e.type){case`SET_FORMULA_VISIBILITY`:this.updateSearchOptions({searchFormulas:e.show});break;case`UNDO`:case`REDO`:case`REMOVE_TABLE`:case`UPDATE_FILTER`:case`REMOVE_COLUMNS_ROWS`:case`HIDE_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`ADD_COLUMNS_ROWS`:case`EVALUATE_CELLS`:case`UPDATE_CELL`:this.isSearchDirty=!0;break;case`ACTIVATE_SHEET`:this.isSearchDirty=!0,this.shouldFinalizeUpdateSelection=!0,this.searchOptions.specificRange&&(this.searchOptions.specificRange={...this.searchOptions.specificRange,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({jumpToMatchSheet:!1,updateSelection:this.shouldFinalizeUpdateSelection}),this.shouldFinalizeUpdateSelection=!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=Nt(this.toSearch,this.searchOptions),this.refreshSearch({jumpToMatchSheet:!0,updateSelection:!0})}refreshSearch(e){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&&En(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){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.jumpToMatchSheet&&this.getters.getActiveSheetId()!==i.sheetId&&(this.preserveSelectedMatchIndex=!0,this.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:i.sheetId}),this.preserveSelectedMatchIndex=!1,this.isSearchDirty=!1),this.model.selection.getBackToDefault(),t.updateSelection&&this.model.selection.selectCell(i.col,i.row)}replace(){this.selectedMatchIndex!==null&&(this.preserveSelectedMatchIndex=!0,this.shouldFinalizeUpdateSelection=!0,this.model.dispatch(`REPLACE_SEARCH`,{searchString:this.toSearch,replaceWith:this.toReplace,matches:[this.searchMatches[this.selectedMatchIndex]],searchOptions:this.searchOptions}),this.preserveSelectedMatchIndex=!1)}replaceAll(){this.model.dispatch(`REPLACE_SEARCH`,{searchString:this.toSearch,replaceWith:this.toReplace,matches:this.searchMatches,searchOptions:this.searchOptions})}showReplaceWarningMessage(e,t){let n=e-t;n===0?this.notificationStore.notifyUser({type:`warning`,sticky:!1,text:k(`Match(es) cannot be replaced as they are part of a formula.`)}):this.notificationStore.notifyUser({type:`warning`,sticky:!1,text:k(`%(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=Nt(t,r),o=new RegExp(a.source,a.flags+`g`),s=Wv(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=E(r),a=this.getters.expandZone(t,i),{width:o,height:s}=this.getters.getVisibleRect(a);o>0&&s>0&&e.push({range:this.model.getters.getRangeFromZone(t,a),color:IH,noBorder:n!==this.selectedMatchIndex,thinLine:!0,fillAlpha:.2})}if(this.searchOptions.searchScope===`specificRange`){let n=this.searchOptions.specificRange;n&&n.sheetId===t&&e.push({range:n,color:IH,noFill:!0,thinLine:!0})}return e}},RH=class extends t.Component{static template=`o-spreadsheet-FindAndReplacePanel`;static components={SelectionInput:kk,Section:q,Checkbox:Fk,ValidationMessages:IB};static props={onCloseSidePanel:Function};searchInput=(0,t.useRef)(`searchInput`);store;state;updateSearchContent;get hasSearchResult(){return this.store.selectedMatchIndex!==null}get searchOptions(){return this.store.searchOptions}get allSheetsMatchesCount(){return k(`%s matches in all sheets`,this.store.allSheetMatchesCount)}get currentSheetMatchesCount(){return k(`%(matches)s matches in %(sheetName)s`,{matches:this.store.activeSheetMatchesCount,sheetName:this.env.model.getters.getSheetName(this.env.model.getters.getActiveSheetId())})}get specificRangeMatchesCount(){let e=this.searchOptions.specificRange;if(!e)return``;let{sheetId:t,zone:n}=e;return k(`%(matches)s matches in range %(range)s of %(sheetName)s`,{matches:this.store.specificRangeMatchesCount,range:hn(n),sheetName:this.env.model.getters.getSheetName(t)})}get searchInfo(){return this.store.toSearch?[this.specificRangeMatchesCount,this.currentSheetMatchesCount,this.allSheetsMatchesCount]:[]}setup(){this.store=or(LH),this.state=(0,t.useState)({dataRange:``}),(0,t.onMounted)(()=>this.searchInput.el?.focus()),(0,t.onWillUnmount)(()=>this.updateSearchContent.stopDebounce()),this.updateSearchContent=dt(this.store.updateSearchContent,200),(0,t.useExternalListener)(window,`keydown`,e=>{let t=cp(e);(t===`Ctrl+F`||t===`Ctrl+H`)&&(this.searchInput.el?.focus(),e.preventDefault(),e.stopPropagation())},{capture:!0})}onFocusSearch(){this.updateDataRange()}onSearchInput(e){this.updateSearchContent(e.target.value)}onKeydownSearch(e){e.key===`Enter`&&(e.preventDefault(),e.stopPropagation(),e.shiftKey?this.store.selectPreviousMatch():this.store.selectNextMatch())}onKeydownReplace(e){e.key===`Enter`&&(e.preventDefault(),e.stopPropagation(),this.store.replace())}searchFormulas(e){this.store.searchFormulas(e)}searchExactMatch(e){this.store.updateSearchOptions({exactMatch:e})}searchMatchCase(e){this.store.updateSearchOptions({matchCase:e})}changeSearchScope(e){let t=e.target.value;this.store.updateSearchOptions({searchScope:t})}onSearchRangeChanged(e){this.state.dataRange=e[0]}updateDataRange(){if(!this.state.dataRange||this.searchOptions.searchScope!==`specificRange`)return;let e=this.env.model.getters.getRangeFromSheetXC(this.env.model.getters.getActiveSheetId(),this.state.dataRange);this.store.updateSearchOptions({specificRange:e})}get specificRange(){let e=this.store.searchOptions.specificRange;return e?this.env.model.getters.getRangeString(e,`forceSheetReference`):``}get pendingSearch(){return this.updateSearchContent.isDebouncePending()}get selectionInputKey(){return this.env.model.getters.getActiveSheetId()}};let zH=new B,BH={name:Xp.Custom,code:``,symbol:``,decimalPlaces:2,position:`after`};var VH=class extends hr{mutators=[`updateFormat`,`changeCategory`,`selectCurrency`,`changeCurrencyCode`,`changeCurrencySymbol`,`updateAvailableCurrencies`];invalidFormat=!1;isApplyingFormatFromPanel=!1;currentFormat=this.formatInSelection;category=this.detectFormatCategory(this.formatInSelection);selectedCurrencyIndex=0;currencyCode=``;currencySymbol=``;isAccountingFormat=!1;availableCurrencies=[BH,...zH.getAll()];lastFormatInSelection=this.currentFormat;usedFormatForCategory={};constructor(e,t){super(e),t&&(this.category=t),this.model.selection.observe(this,{handleEvent:this.handleSelectionEvent.bind(this)}),this.onDispose(()=>{this.model.selection.unobserve(this)})}handle(){this.isApplyingFormatFromPanel||this.syncActiveFormat()}handleSelectionEvent(){this.getters.isGridSelectionActive()&&this.syncActiveFormat()}syncActiveFormat(){let e=this.formatInSelection;e!==this.lastFormatInSelection&&(this.setActiveFormat(e),this.lastFormatInSelection=e)}setActiveFormat(e){this.currentFormat=e,this.invalidFormat=!Es(e||``),this.category=this.detectFormatCategory(e)}get categories(){return[{label:k(`Number`),value:`number`},{label:k(`Date`),value:`date`},{label:k(`Currency`),value:`currency`}]}get formatInSelection(){let e=this.getters.getActivePosition();return this.getters.getPivotCellFromPosition(e).type===`VALUE`?this.getters.getEvaluatedCell(e).format:this.getters.getCell(e)?.format}detectFormatCategory(e){return e?ns(e)?`date`:e.includes(`$`)||e.includes(`"`)?`currency`:`number`:`number`}get formatProposals(){return this.category===`date`?this.dateFormatProposals:this.category===`currency`?this.currencyFormatProposals:this.category===`number`?this.numberFormatProposals:[]}get numberFormatProposals(){let e=[`0.00`,`0`,`#,##0`,`#,##0.00`,`0%`,`0.00%`,`0.00e`,`0.00;(0.00);-`].map(e=>({label:z(-1234.56,{format:e,locale:this.getters.getLocale()}),format:e}));return[{label:k(`Automatic`),format:void 0},{label:k(`Plain text`),format:`@`},...e]}get dateFormatProposals(){let e=this.getters.getLocale();return[e.dateFormat,e.timeFormat,e.dateFormat+` `+e.timeFormat,`dddd d mmmm yyyy hh:mm:ss a`,`yyyy-mm-dd`,`yyyy-mm-dd hh:mm:ss`,`dddd d mmmm yyyy`,`d mmmm yyyy`,`ddd d mmm yyyy`,`d mmm yyyy`,`mmmm yyyy`,`mmm yyyy`,`hhhh:mm:ss`,`qq yyyy`,`qqqq yyyy`].map(t=>({label:z(WR,{format:t,locale:e}),format:t}))}get currencyFormatProposals(){let e=this.availableCurrencies[this.selectedCurrencyIndex],t=e.position,n=e.position===`before`?`after`:`before`,r=this.currencySymbol.trim()?this.currencySymbol:``,i=this.currencyCode.trim()?this.currencyCode:``,a=e.decimalPlaces;if(!r&&!i)return[];let o=[{symbol:r,position:t,decimalPlaces:0},{symbol:r,position:t,decimalPlaces:a},{symbol:r,position:t,decimalPlaces:0,code:i},{symbol:r,position:t,decimalPlaces:a,code:i},{symbol:r,position:n,decimalPlaces:0},{symbol:r,position:n,decimalPlaces:a},{symbol:r,position:n,decimalPlaces:0,code:i},{symbol:r,position:n,decimalPlaces:a,code:i}],s=new Set,c=this.getters.getLocale();return o.map(e=>{let t=this.isAccountingFormat?us(e):ls(e);if(!(!e.symbol&&!e.code||s.has(t)))return s.add(t),{format:t,label:z(1e3,{format:t,locale:c})}}).filter(C)}get formatExamples(){let e=this.currentFormat,t=this.getters.getLocale();if(!e||!Es(e))return[];if(this.category===`date`)return[{label:k(`Sample:`),value:z(WR,{format:e,locale:t})}];{let n=Ds(e),r=[{label:k(`Positive:`),value:z(1234.56,{format:e,locale:t})},{label:k(`Negative:`),value:z(-1234.56,{format:e,locale:t})},{label:k(`Zero:`),value:z(0,{format:e,locale:t})}];return n===4&&r.push({label:k(`Text:`),value:z(`Text`,{format:e,locale:t})}),r}}updateAvailableCurrencies(){this.availableCurrencies=[BH,...zH.getAll()]}updateFormat(e){this.currentFormat=e,this.invalidFormat=!Es(e),this.invalidFormat||(this.lastFormatInSelection=e,this.isApplyingFormatFromPanel=!0,this.model.dispatch(`SET_FORMATTING_WITH_PIVOT`,{sheetId:this.getters.getActiveSheetId(),target:this.getters.getSelectedZones(),format:e||``}),this.isApplyingFormatFromPanel=!1)}changeCategory(e){if(e===this.category)return`noStateChange`;this.usedFormatForCategory[this.category]=this.currentFormat,this.category=e;let t=this.usedFormatForCategory[e]||this.formatProposals[0]?.format||``;this.updateFormat(t)}selectCurrency(e){let t=this.formatProposals.findIndex(e=>e.format===this.currentFormat);this.selectedCurrencyIndex=e;let n=this.availableCurrencies[e];this.currencyCode=n.code,this.currencySymbol=n.symbol,this.updateFormat(this.formatProposals[t]?.format||this.formatProposals[0]?.format||``)}changeCurrencyCode(e){let t=this.formatProposals.findIndex(e=>e.format===this.currentFormat);this.currencyCode=e,this.selectedCurrencyIndex=0,this.updateFormat(this.formatProposals[t]?.format||this.formatProposals[0]?.format||``)}changeCurrencySymbol(e){let t=this.formatProposals.findIndex(e=>e.format===this.currentFormat);this.currencySymbol=e,this.selectedCurrencyIndex=0,this.updateFormat(this.formatProposals[t]?.format||this.formatProposals[0]?.format||``)}toggleAccountingFormat(){let e=this.formatProposals.findIndex(e=>e.format===this.currentFormat);this.isAccountingFormat=!this.isAccountingFormat,this.updateFormat(this.formatProposals[e]?.format||this.formatProposals[0]?.format||``)}get invalidFormatMessage(){return this.invalidFormat?k(`The format entered is not valid.`):void 0}},HH=class extends t.Component{static template=`o-spreadsheet-MoreFormatsPanel`;static props={onCloseSidePanel:Function,category:{type:String,optional:!0}};static components={BadgeSelection:AV,Section:q,TextInput:gV,Checkbox:Fk};store;setup(){this.store=or(VH,this.props.category),(0,t.onWillStart)(()=>this.loadCurrencies()),(0,t.onWillUpdateProps)(e=>{e.category&&e.category!==this.props.category&&this.store.changeCategory(e.category)})}async loadCurrencies(){zH.getAll().length===0&&((await(this.env.loadCurrencies?.()??Promise.resolve([]))).forEach((e,t)=>{zH.replace(t.toString(),e)}),this.store.updateAvailableCurrencies())}currencyDisplayName(e){return e.name+(e.code?` (${e.code})`:``)}updateSelectCurrency(e){let t=e.target,n=parseInt(t.value,10);this.store.selectCurrency(n)}isFormatSelected(e){return e===this.store.currentFormat}},UH=class extends hr{pivotId;initialMeasure;mutators=[`cancelMeasureDisplayEdition`,`updateMeasureDisplayType`,`updateMeasureDisplayField`,`updateMeasureDisplayValue`];measureDisplay;constructor(e,t,n){super(e),this.pivotId=t,this.initialMeasure=n,this.measureDisplay=n.display||{type:`no_calculations`}}updateMeasureDisplayType(e){this.updatePivotMeasureDisplay(this.getMeasureDisplay(e,this.measureDisplay.fieldNameWithGranularity,this.measureDisplay.value))}updateMeasureDisplayField(e){this.updatePivotMeasureDisplay(this.getMeasureDisplay(this.measureDisplay.type,e,this.measureDisplay.value))}updateMeasureDisplayValue(e){this.updatePivotMeasureDisplay(this.getMeasureDisplay(this.measureDisplay.type,this.measureDisplay.fieldNameWithGranularity,e))}updatePivotMeasureDisplay(e){let t=b(this.model.getters.getPivotCoreDefinition(this.pivotId)),n=this.getMeasureIndex(this.initialMeasure.id,t),r={...t.measures[n],display:e};t.measures[n]=r,this.model.dispatch(`UPDATE_PIVOT`,{pivot:t,pivotId:this.pivotId}).isSuccessful&&(this.measureDisplay=e)}getMeasureDisplay(e,t,n){switch(e){case`no_calculations`:case`%_of_grand_total`:case`%_of_col_total`:case`%_of_row_total`:case`%_of_parent_row_total`:case`%_of_parent_col_total`:case`index`:return{type:e};case`%_of_parent_total`:case`running_total`:case`%_running_total`:case`rank_asc`:case`rank_desc`:return t||=this.fields[0]?.nameWithGranularity,{type:e,fieldNameWithGranularity:t};case`%_of`:case`difference_from`:case`%_difference_from`:t||=this.fields[0]?.nameWithGranularity;let r=this.getPossibleValues(t);return(n===void 0||!r.find(e=>e.value===n))&&(n=Fm),{type:e,fieldNameWithGranularity:t,value:n??`(previous)`}}}getMeasureIndex(e,t){let n=t.measures.findIndex(t=>t.id===e);if(n===-1)throw Error(`Measure with id ${e} not found in pivot.`);return n}get doesDisplayNeedsField(){return[`%_of_parent_total`,`running_total`,`%_running_total`,`rank_asc`,`rank_desc`].includes(this.measureDisplay.type)||this.doesDisplayNeedsValue}get fields(){let e=this.getters.getPivot(this.pivotId).definition;return[...e.columns,...e.rows].map(e=>({...e,displayName:Ch(e)}))}get doesDisplayNeedsValue(){return this.isDisplayValueDependant(this.measureDisplay)}isDisplayValueDependant(e){return[`%_of`,`difference_from`,`%_difference_from`].includes(e.type)}get values(){let e=this.measureDisplay;return this.isDisplayValueDependant(e)?this.getPossibleValues(e.fieldNameWithGranularity):[]}getPossibleValues(e){let t=[{value:Fm,label:k(`(previous)`)},{value:`(next)`,label:k(`(next)`)}],n=this.fields.find(t=>t.nameWithGranularity===e);if(!n)return[];let r=this.getters.getPivot(this.pivotId).getPossibleFieldValues(n);return[...t,...r]}cancelMeasureDisplayEdition(){let e=b(this.model.getters.getPivotCoreDefinition(this.pivotId)),t=this.getMeasureIndex(this.initialMeasure.id,e);e.measures[t]={...e.measures[t],display:this.initialMeasure.display},this.model.dispatch(`UPDATE_PIVOT`,{pivot:e,pivotId:this.pivotId})}},WH=class extends t.Component{static template=`o-spreadsheet-PivotMeasureDisplayPanel`;static props={onCloseSidePanel:Function,pivotId:String,measure:Object};static components={Section:q,Checkbox:Fk,RadioSelection:NV};measureDisplayTypeLabels=nm.labels;measureDisplayDescription=nm.documentation;store;setup(){this.store=or(UH,this.props.pivotId,this.props.measure)}onSave(){this.env.replaceSidePanel(`PivotSidePanel`,`pivot_measure_display_${this.props.pivotId}_${this.props.measure.id}`,{pivotId:this.props.pivotId})}onCancel(){this.store.cancelMeasureDisplayEdition(),this.env.replaceSidePanel(`PivotSidePanel`,`pivot_measure_display_${this.props.pivotId}_${this.props.measure.id}`,{pivotId:this.props.pivotId})}get fieldChoices(){return this.store.fields.map(e=>({value:e.nameWithGranularity,label:e.displayName}))}};function GH(e,t){let n=e.getActiveSheetId();return Xn(KH(e,t).map(E)).map(t=>({range:e.getRangeFromZone(n,t),noFill:!0,color:ee}))}function KH(e,t){let n=[],r=e.getActiveSheetId();for(let i of e.getSheetViewVisibleCols())for(let a of e.getSheetViewVisibleRows()){let o={sheetId:r,col:i,row:a};t===e.getPivotIdFromPosition(o)&&n.push(o)}return n}var qH=class extends t.Component{static template=`o-spreadsheet-PivotDeferUpdate`;static props={deferUpdate:Boolean,isDirty:Boolean,toggleDeferUpdate:Function,discard:Function,apply:Function};static components={Section:q,Checkbox:Fk};get deferUpdatesLabel(){return k(`Defer updates`)}get deferUpdatesTooltip(){return k(`Changing the pivot definition requires to reload the data. It may take some time.`)}},JH=class extends t.Component{static template=`o-spreadsheet-PivotCustomGroupsCollapsible`;static props={pivotId:String,customField:Object,onCustomFieldUpdated:Function};static components={SidePanelCollapsible:Vv,TextInput:gV,Checkbox:Fk};get groups(){return this.props.customField.groups.sort((e,t)=>!e.isOtherGroup&&!t.isOtherGroup?0:e.isOtherGroup?1:-1)}get hasOthersGroup(){return this.props.customField.groups.some(e=>e.isOtherGroup)}addOthersGroup(){if(this.hasOthersGroup)return;let e={name:Eh(k(`Others`),this.props.customField),values:[],isOtherGroup:!0},t=[...this.props.customField.groups,e];this.updateCustomField({...this.props.customField,groups:t})}onDeleteGroup(e){let t=[...this.props.customField.groups];t.splice(e,1),this.updateCustomField({...this.props.customField,groups:t})}onRenameGroup(e,t){let n=b(this.props.customField.groups),r=n[e];r&&(r.name=Eh(t,this.props.customField),this.updateCustomField({...this.props.customField,groups:n}))}updateCustomField(e){let t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);this.props.onCustomFieldUpdated({customFields:{...t.customFields,[e.name]:e}})}};function YH(e,t,n,r){let i=[];e=e.toLowerCase();for(let a of e){let e=t.toLocaleLowerCase().indexOf(a);e!==-1&&(i.push({value:t.slice(0,e),color:``},{value:t[e],color:n,classes:[r]}),t=t.slice(e+1))}return i.push({value:t}),i.filter(e=>e.value)}var XH=class extends t.Component{static template=`o-spreadsheet-AddDimensionButton`;static components={Popover:Cv,TextValueProvider:wO};static props={onFieldPicked:Function,fields:Array,slots:{type:Object,optional:!0}};buttonRef=(0,t.useRef)(`button`);popover=(0,t.useState)({isOpen:!1});search=(0,t.useState)({input:``});autoComplete;setup(){this.autoComplete=or(lk),this.autoComplete.useProvider(this.getProvider()),(0,t.useExternalListener)(window,`click`,e=>{e.target!==this.buttonRef.el&&(this.popover.isOpen=!1)}),mV({refName:`autofocus`})}getProvider(){return{proposals:this.proposals,autoSelectFirstProposal:!1,selectProposal:e=>{let t=this.props.fields.find(t=>t.string===e);t&&this.pickField(t)}}}get proposals(){let e;return e=this.search.input?fl(this.search.input,this.props.fields,e=>e.string===e.name?e.string:e.string+e.name):this.props.fields,e.map(e=>{let t=e.string;return{text:t,fuzzySearchKey:t,htmlContent:YH(this.search.input,t,le,`o-semi-bold`)}})}get popoverProps(){let{x:e,y:t,width:n,height:r}=this.buttonRef.el.getBoundingClientRect();return{anchorRect:{x:e,y:t,width:n,height:r},positioning:`bottom-left`}}updateSearch(e){this.search.input=e,this.autoComplete.useProvider(this.getProvider())}pickField(e){this.props.onFieldPicked(e.name),this.togglePopover()}togglePopover(){this.popover.isOpen=!this.popover.isOpen,this.search.input=``,this.autoComplete.useProvider(this.getProvider())}onKeyDown(e){switch(e.key){case`Enter`:let t=this.autoComplete.provider?.proposals;t?.length===1&&this.autoComplete.provider?.selectProposal(t[0].text||``);let n=this.autoComplete.selectedProposal;this.autoComplete.provider?.selectProposal(n?.text||``);break;case`ArrowUp`:case`ArrowDown`:this.autoComplete.moveSelection(e.key===`ArrowDown`?`next`:`previous`);break;case`Escape`:this.popover.isOpen=!1;break;default:break}}},ZH=class extends t.Component{static template=`o-spreadsheet-PivotDimension`;static props={dimension:Object,onRemoved:{type:Function,optional:!0},onNameUpdated:{type:Function,optional:!0},slots:{type:Object,optional:!0}};static components={CogWheelMenu:SV,TextInput:gV};updateName(e){this.props.onNameUpdated?.(this.props.dimension,e===``||e.startsWith(`=`)?void 0:e)}get dimensionDisplayName(){let e=this.props.dimension.displayName;return Ph(e)}},QH=class extends t.Component{static template=`o-spreadsheet-PivotDimensionGranularity`;static props={dimension:Object,onUpdated:Function,availableGranularities:Set,allGranularities:Array};periods=uh},$H=class extends t.Component{static template=`o-spreadsheet-PivotDimensionOrder`;static props={dimension:Object,onUpdated:Function}},eU=class{scope;code=``;constructor(e=new nU){this.scope=e}append(...e){this.code+=e.map(e=>e.toString()).join(`
|
|
111
|
+
/>`;static defaultProps={topOffset:0};get offset(){return this.env.model.getters.getActiveSheetScrollInfo().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(),t=this.env.model.getters.getScrollBarWidth();return{top:`${this.props.topOffset+e}px`,right:`0px`,width:`${t}px`,bottom:pp()?`${t}px`:`0`}}onScroll(e){let{scrollX:t}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:t,offsetY:e})}},pV=class extends t.Component{static template=`o-spreadsheet-Selection`;static props={};static components={Highlight:cV};get highlightProps(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getUnboundedZone(e,this.env.model.getters.getSelectedZone());return{range:this.env.model.getters.getRangeFromZone(e,t),color:ae}}};function mV({refName:e}){let n=(0,t.useRef)(e);(0,t.useEffect)(e=>{e?.focus()},()=>[n.el])}var hV=class extends t.Component{static props={value:[Number,String],onChange:Function,class:{type:String,optional:!0},id:{type:String,optional:!0},placeholder:{type:String,optional:!0},autofocus:{type:Boolean,optional:!0},alwaysShowBorder:{type:Boolean,optional:!0},selectContentOnFocus:{type:Boolean,optional:!0}};refName=`input`;inputRef;setup(){this.inputRef=(0,t.useRef)(this.refName),(0,t.useExternalListener)(window,`click`,e=>{e.target!==this.inputRef.el&&this.inputRef.el?.value!==this.props.value&&this.save()},{capture:!0}),this.props.autofocus&&mV({refName:this.refName}),(0,t.onWillUpdateProps)(e=>{document.activeElement!==this.inputRef.el&&this.inputRef.el&&(this.inputRef.el.value=e.value)}),(0,t.onMounted)(()=>{this.inputRef.el&&(this.inputRef.el.value=this.props.value.toString())})}onKeyDown(e){switch(e.key){case`Enter`:this.save(),e.preventDefault(),e.stopPropagation();break;case`Escape`:this.inputRef.el&&(this.inputRef.el.value=this.props.value.toString(),this.inputRef.el.blur()),e.preventDefault(),e.stopPropagation();break}}save(e=!1){let t=(this.inputRef.el?.value||``).trim();t!==this.props.value.toString()&&this.props.onChange(t),e||this.inputRef.el?.blur()}onMouseDown(e){e.target!==document.activeElement&&this.props.selectContentOnFocus&&(e.preventDefault(),e.stopPropagation())}onMouseUp(e){let t=e.target;t!==document.activeElement&&this.props.selectContentOnFocus&&(t.focus(),this.props.selectContentOnFocus&&t.select(),e.preventDefault(),e.stopPropagation())}},gV=class extends hV{static template=`o-spreadsheet-TextInput`;static components={};static props={...hV.props,errorMessage:{type:String,optional:!0}};get inputClass(){return[this.props.class,`w-100 os-input`,this.props.alwaysShowBorder?`o-input-border`:void 0,this.props.errorMessage?`o-invalid`:void 0].filter(C).join(` `)}},_V=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=h(this.props.action);setup(){(0,t.onWillUpdateProps)(e=>{e.action!==this.props.action&&(this.actionButton=h(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`}):``}},vV=class extends t.Component{static template=`o-spreadsheet-ColorPickerWidget`;static props={currentColor:{type:String,optional:!0},toggleColorPicker:Function,showColorPicker:Boolean,onColorPicked:Function,icon:String,title:{type:String,optional:!0},disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};static components={ColorPicker:yk};colorPickerButtonRef=(0,t.useRef)(`colorPickerButton`);get iconStyle(){return this.props.currentColor?`border-color: ${this.props.currentColor}`:`border-bottom-style: hidden`}get colorPickerAnchorRect(){let e=this.colorPickerButtonRef.el.getBoundingClientRect();return{x:e.x,y:e.y,width:e.width,height:e.height}}},yV=class extends t.Component{static template=`o-spreadsheet-NumberEditor`;static props={currentValue:Number,onValueChange:Function,onToggle:{type:Function,optional:!0},onFocusInput:{type:Function,optional:!0},class:String,valueIcon:{type:String,optional:!0},min:Number,max:Number,title:String,valueList:Array};static defaultProps={onFocusInput:()=>{}};static components={Popover:Cv};dropdown=(0,t.useState)({isOpen:!1});inputRef=(0,t.useRef)(`inputNumber`);rootEditorRef=(0,t.useRef)(`NumberEditor`);valueListRef=(0,t.useRef)(`numberList`);DOMFocusableElementStore;setup(){this.DOMFocusableElementStore=D(xO),(0,t.useExternalListener)(window,`click`,this.onExternalClick,{capture:!0}),(0,t.onWillUpdateProps)(e=>{this.inputRef.el&&document.activeElement!==this.inputRef.el&&(this.inputRef.el.value=e.currentValue)}),(0,t.onMounted)(()=>{this.inputRef.el&&(this.inputRef.el.value=this.props.currentValue.toString())})}get popoverProps(){let{x:e,y:t,width:n,height:r}=this.rootEditorRef.el.getBoundingClientRect();return{anchorRect:{x:e,y:t,width:n,height:r},positioning:`bottom-left`,verticalOffset:0}}onExternalClick(e){!Zf(this.valueListRef.el,e)&&!Zf(this.rootEditorRef.el,e)&&this.closeList()}toggleList(){this.dropdown.isOpen?this.closeList():(this.props.onToggle?.(),this.inputRef.el.focus())}closeList(){this.dropdown.isOpen=!1}setValue(e){let t=x(Math.floor(parseFloat(e)),this.props.min,this.props.max);this.props.onValueChange(t),this.closeList()}setValueFromInput(e){this.setValue(e.target.value)}setValueFromList(e){this.setValue(e)}get currentValue(){return`${this.props.currentValue}`}onInputFocused(e){this.dropdown.isOpen=!0,e.target.select()}onInputKeydown(e){if(e.key===`Enter`||e.key===`Escape`){this.closeList();let t=e.target;e.key===`Escape`&&(t.value=`${this.props.currentValue}`),this.props.onToggle?.()}if(e.key===`Tab`){e.preventDefault(),e.stopPropagation(),this.closeList(),this.DOMFocusableElementStore.focus();return}}},bV=class extends t.Component{static template=`o-spreadsheet-FontSizeEditor`;static components={NumberEditor:yV};static props={currentFontSize:Number,onFontSizeChanged:Function,onToggle:{type:Function,optional:!0},onFocusInput:{type:Function,optional:!0},class:String};static defaultProps={onFocusInput:()=>{}};fontSizes=Ie},xV=class extends t.Component{static template=`o-spreadsheet.TextStyler`;static components={ColorPickerWidget:vV,ActionButton:_V,FontSizeEditor:bV};static props={style:Object,updateStyle:{type:Function,optional:!0},defaultStyle:{type:Object,optional:!0},hasVerticalAlign:{type:Boolean,optional:!0},hasHorizontalAlign:{type:Boolean,optional:!0},hasBackgroundColor:{type:Boolean,optional:!0},class:{type:String,optional:!0}};openedEl=null;setup(){(0,t.useExternalListener)(window,`click`,this.onExternalClick)}state=(0,t.useState)({activeTool:``});updateFontSize(e){this.props.updateStyle?.({...this.props.style,fontSize:e})}toggleDropdownTool(e,t){let n=this.state.activeTool===e;this.closeMenus(),this.state.activeTool=n?``:e,this.openedEl=n?null:t.target}onExternalClick(e){this.openedEl!==e.target&&this.closeMenus()}onTextColorChange(e){this.props.updateStyle?.({...this.props.style,color:e}),this.closeMenus()}onFillColorChange(e){this.props.updateStyle?.({...this.props.style,fillColor:e}),this.closeMenus()}updateAlignment(e){this.props.updateStyle?.({...this.props.style,align:e}),this.closeMenus()}updateVerticalAlignment(e){this.props.updateStyle?.({...this.props.style,verticalAlign:e}),this.closeMenus()}toggleBold(){this.props.updateStyle?.({...this.props.style,bold:!this.bold})}toggleItalic(){this.props.updateStyle?.({...this.props.style,italic:!this.italic})}closeMenus(){this.state.activeTool=``,this.openedEl=null}get align(){return this.props.style.align??this.props.defaultStyle?.align}get verticalAlign(){return this.props.style.verticalAlign||this.props.defaultStyle?.verticalAlign}get bold(){return this.props.style.bold??this.props.defaultStyle?.bold}get italic(){return this.props.style.italic??this.props.defaultStyle?.italic}get currentFontSize(){return this.props.style.fontSize??this.props.defaultStyle?.fontSize??ye.fontSize}get boldButtonAction(){return{name:k(`Bold`),execute:()=>this.toggleBold(),isActive:()=>this.bold||!1,icon:`o-spreadsheet-Icon.BOLD`}}get italicButtonAction(){return{name:k(`Italic`),execute:()=>this.toggleItalic(),isActive:()=>this.italic||!1,icon:`o-spreadsheet-Icon.ITALIC`}}get horizontalAlignButtonAction(){let e=`o-spreadsheet-Icon.ALIGN_LEFT`;return this.align===`center`?e=`o-spreadsheet-Icon.ALIGN_CENTER`:this.align===`right`&&(e=`o-spreadsheet-Icon.ALIGN_RIGHT`),{name:k(`Horizontal alignment`),icon:e}}get horizontalAlignActions(){return[{name:k(`Left`),execute:()=>this.updateAlignment(`left`),isActive:()=>this.align===`left`,icon:`o-spreadsheet-Icon.ALIGN_LEFT`},{name:k(`Center`),execute:()=>this.updateAlignment(`center`),isActive:()=>this.align===`center`,icon:`o-spreadsheet-Icon.ALIGN_CENTER`},{name:k(`Right`),execute:()=>this.updateAlignment(`right`),isActive:()=>this.align===`right`,icon:`o-spreadsheet-Icon.ALIGN_RIGHT`}]}get verticalAlignButtonAction(){let e=`o-spreadsheet-Icon.ALIGN_MIDDLE`;return this.verticalAlign===`top`?e=`o-spreadsheet-Icon.ALIGN_TOP`:this.verticalAlign===`bottom`&&(e=`o-spreadsheet-Icon.ALIGN_BOTTOM`),{name:k(`Vertical alignment`),icon:e}}get verticalAlignActions(){return[{name:k(`Top`),execute:()=>this.updateVerticalAlignment(`top`),isActive:()=>this.verticalAlign===`top`,icon:`o-spreadsheet-Icon.ALIGN_TOP`},{name:k(`Middle`),execute:()=>this.updateVerticalAlignment(`middle`),isActive:()=>this.verticalAlign===`middle`,icon:`o-spreadsheet-Icon.ALIGN_MIDDLE`},{name:k(`Bottom`),execute:()=>this.updateVerticalAlignment(`bottom`),isActive:()=>this.verticalAlign===`bottom`,icon:`o-spreadsheet-Icon.ALIGN_BOTTOM`}]}},SV=class extends t.Component{static template=`o-spreadsheet-CogWheelMenu`;static components={MenuPopover:Dv};static props={items:Array};buttonRef=(0,t.useRef)(`button`);menuState=(0,t.useState)({isOpen:!1,anchorRect:null,menuItems:[]});menuId=this.env.model.uuidGenerator.uuidv4();toggleMenu(e){e.closedMenuId!==this.menuId&&(this.menuState.isOpen=!this.menuState.isOpen,this.menuState.anchorRect=tp(this.buttonRef.el),this.menuState.menuItems=p(this.props.items))}},CV=class extends t.Component{static template=`o-spreadsheet-CarouselPanel`;static props={onCloseSidePanel:Function,figureId:String};static components={Section:q,TextInput:gV,TextStyler:xV,CogWheelMenu:SV};DEFAULT_CAROUSEL_TITLE_STYLE=ze;dragAndDrop=Sk();previewListRef=(0,t.useRef)(`previewList`);setup(){let e=[...this.carouselItems];(0,t.onWillUpdateProps)(()=>{w(this.carouselItems,e)||this.dragAndDrop.cancel(),e=[...this.carouselItems]})}get carouselItems(){return this.env.model.getters.getCarousel(this.props.figureId).items}get title(){return this.env.model.getters.getCarousel(this.props.figureId).title}get carousel(){return this.env.model.getters.getCarousel(this.props.figureId)}getPreviewDivStyle(e){return this.dragAndDrop.itemsStyle[this.getItemId(e)]||``}getItemId(e){return e.type===`chart`?e.chartId:`transparent-carousel`}addNewChartToCarousel(){this.env.model.dispatch(`ADD_NEW_CHART_TO_CAROUSEL`,{figureId:this.props.figureId,sheetId:this.carouselSheetId})}get hasDataView(){return this.carouselItems.some(e=>e.type===`carouselDataView`)}isCarouselItemActive(e){return w(this.env.model.getters.getSelectedCarouselItem(this.props.figureId),e)}addDataViewToCarousel(){let e=this.env.model.getters.getCarousel(this.props.figureId);this.updateItems([...e.items,{type:`carouselDataView`}])}activateCarouselItem(e){this.env.model.dispatch(`UPDATE_CAROUSEL_ACTIVE_ITEM`,{figureId:this.props.figureId,sheetId:this.carouselSheetId,item:e})}editCarouselItem(e){e.type===`chart`&&(this.activateCarouselItem(e),this.env.model.dispatch(`SELECT_FIGURE`,{figureId:this.props.figureId}),this.env.openSidePanel(`ChartPanel`,{chartId:e.chartId}))}renameCarouselItem(e,t){let n=t.trim();if(!n||n===this.getItemTitle(e).toString())return;let r=[...this.carouselItems],i=this.carouselItems.findIndex(t=>w(t,e));i!==-1&&(r[i]={...e,title:n},this.updateItems(r))}deleteCarouselItem(e){let t=this.env.model.getters.getCarousel(this.props.figureId).items.filter(t=>!w(t,e));this.updateItems(t)}popOutCarouselItem(e){e.type===`chart`&&this.env.model.dispatch(`POPOUT_CHART_FROM_CAROUSEL`,{sheetId:this.carouselSheetId,carouselId:this.props.figureId,chartId:e.chartId})}duplicateCarouselChart(e){e.type===`chart`&&this.env.model.dispatch(`DUPLICATE_CAROUSEL_CHART`,{sheetId:this.carouselSheetId,carouselId:this.props.figureId,chartId:e.chartId,duplicatedChartId:this.env.model.uuidGenerator.smallUuid()})}onDragHandleMouseDown(e,t){if(t.button!==0)return;let n=Array.from(this.previewListRef.el.children).map(e=>tp(e)),r=this.carouselItems.map((e,t)=>({id:this.getItemId(e),size:n[t].height,position:n[t].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:this.getItemId(e),initialMousePosition:t.clientY,items:r,scrollableContainerEl:this.previewListRef.el,onDragEnd:(t,n)=>this.onDragEnd(e,n)})}onDragEnd(e,t){let n=this.carouselItems.findIndex(t=>w(t,e));if(n===-1||n===t)return;let r=[...this.env.model.getters.getCarousel(this.props.figureId).items];r.splice(n,1),r.splice(t,0,e),this.updateItems(r)}getItemTitle(e){return Y_(this.env.model.getters,e)}getItemPreview(e){return J_(this.env.model.getters,e)}updateItems(e){this.env.model.dispatch(`UPDATE_CAROUSEL`,{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...this.carousel,items:e}})}updateTitleText(e){let t=this.env.model.getters.getCarousel(this.props.figureId);this.env.model.dispatch(`UPDATE_CAROUSEL`,{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...t,title:{...t.title,text:e}}})}updateTitleStyle(e){let t=this.env.model.getters.getCarousel(this.props.figureId);this.env.model.dispatch(`UPDATE_CAROUSEL`,{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...t,title:{...t.title,...e}}})}get carouselAddChartInfoMessage(){return k(`Add a chart to the carousel. You can also add a chart by dragging and dropping it over the carousel figure.`)}getCogWheelMenuItems(e){let t=[];return e.type===`chart`&&(t.push({name:k(`Edit chart`),execute:()=>this.editCarouselItem(e),icon:`o-spreadsheet-Icon.EDIT`}),t.push({name:k(`Pop out chart`),execute:()=>this.popOutCarouselItem(e),icon:`o-spreadsheet-Icon.EXTERNAL`}),t.push({name:k(`Duplicate chart`),execute:()=>this.duplicateCarouselChart(e),icon:`o-spreadsheet-Icon.COPY`})),t.push({name:k(`Delete item`),execute:()=>this.deleteCarouselItem(e),icon:`o-spreadsheet-Icon.TRASH`}),t}get carouselSheetId(){let e=this.env.model.getters.getFigureSheetId(this.props.figureId);if(!e)throw Error(`Could not find the sheetId of the carousel figure`);return e}get carouselDataViewMessage(){return k(`The data view makes the carousel transparent, revealing the data underneath.`)}};let wV={chartId:String,definition:Object,canUpdateChart:Function,updateChart:Function};var TV=class extends t.Component{static template=`o-spreadsheet.ChartDataSeries`;static components={SelectionInput:kk,Section:q};static props={ranges:Array,hasSingleRange:{type:Boolean,optional:!0},onSelectionChanged:Function,onSelectionReordered:{type:Function,optional:!0},onSelectionRemoved:{type:Function,optional:!0},onSelectionConfirmed:Function,title:{type:String,optional:!0},maxNumberOfUsedRanges:{type:Number,optional:!0},datasetOrientation:{type:String,optional:!0},canChangeDatasetOrientation:{type:Boolean,optional:!0},onFlipAxis:{type:Function,optional:!0}};get ranges(){return this.props.ranges.map(e=>e.dataRange)}get disabledRanges(){return this.props.ranges.map((e,t)=>this.props.maxNumberOfUsedRanges?t>=this.props.maxNumberOfUsedRanges:!1)}get colors(){return this.props.ranges.map(e=>e.backgroundColor)}get title(){return this.props.title?this.props.title:this.props.hasSingleRange?k(`Data range`):k(`Data series`)}},EV=class extends t.Component{static template=`o-spreadsheet.ChartErrorSection`;static components={Section:q,ValidationMessages:IB};static props={messages:{type:Array,element:String}}},DV=class extends t.Component{static template=`o-spreadsheet.ChartLabelRange`;static components={SelectionInput:kk,Checkbox:Fk,Section:q};static props={title:{type:String,optional:!0},range:String,isInvalid:Boolean,onSelectionChanged:Function,onSelectionConfirmed:Function,options:{type:Array,optional:!0}};static defaultProps={title:k(`Categories / Labels`),options:[]}},OV=class extends t.Component{static template=`o-spreadsheet-GenericChartConfigPanel`;static components={ChartDataSeries:TV,ChartLabelRange:DV,Section:q,Checkbox:Fk,ChartErrorSection:EV};static props=wV;state=(0,t.useState)({datasetDispatchResult:void 0,labelsDispatchResult:void 0});dataSets=[];labelRange;datasetOrientation=void 0;chartTerms=Yp;setup(){this.dataSets=this.props.definition.dataSets,this.labelRange=this.props.definition.labelRange,this.datasetOrientation=this.computeDatasetOrientation()}get errorMessages(){return[...this.state.datasetDispatchResult?.reasons||[],...this.state.labelsDispatchResult?.reasons||[]].filter(e=>e!==`NoChanges`).map(e=>Yp.Errors[e]||Yp.Errors.Unexpected)}get isDatasetInvalid(){return!!this.state.datasetDispatchResult?.isCancelledBecause(`InvalidDataSet`)}get isLabelInvalid(){return!!this.state.labelsDispatchResult?.isCancelledBecause(`InvalidLabelRange`)}get dataSetsHaveTitleLabel(){return this.datasetOrientation===`rows`?k(`Use col %(column_name)s as headers`,{column_name:Ht(this.calculateHeaderPosition()||0)}):k(`Use row %(row_position)s as headers`,{row_position:this.calculateHeaderPosition()||``})}getLabelRangeOptions(){let e=this.props.definition;return[{name:`aggregated`,label:this.chartTerms.AggregatedChart,value:(`aggregated`in e?e.aggregated:!1)??!1,onChange:this.onUpdateAggregated.bind(this)},{name:`dataSetsHaveTitle`,label:this.dataSetsHaveTitleLabel,value:e.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}onUpdateDataSetsHaveTitle(e){this.props.updateChart(this.props.chartId,{dataSetsHaveTitle:e})}get canChangeDatasetOrientation(){let e=new Set,t=[],n=this.env.model.getters.getActiveSheetName(),r=this.dataSets.map(e=>e.dataRange);this.labelRange&&r.push(this.labelRange);for(let i of r){if(!fn(i))return!1;let r=Pc(i),a=ln(r.xc);if(a.bottom===void 0||a.right===void 0||(t.push(a),e.add(r.sheetName||n),e.size>1))return!1}let i=Xn(t);if(i.length!==1)return!1;let{left:a,right:o,top:s,bottom:c}=i[0];return!t.some(e=>(e.top!==s||e.bottom!==c)&&(e.left!==a||e.right!==o))}computeDatasetOrientation(){let e=!1,t=!1;for(let n of this.dataSets){if(!fn(n.dataRange))return;let r=ln(n.dataRange);if(r.bottom===void 0||r.right===void 0)return;r.top===r.bottom&&(e=!0),r.left===r.right&&(t=!0)}if(e&&!t)return`rows`;if(!e&&t)return`columns`}setDatasetOrientation(e){let t=this.props.definition.dataSets.map(e=>e.dataRange),n=this.transposeDataSet([this.props.definition.labelRange,...t],e);if(n.length===0)return;let r=n.length>1?n.shift().dataRange:``;this.props.updateChart(this.props.chartId,{labelRange:r,dataSets:n}),this.dataSets=n,this.labelRange=r,this.datasetOrientation=e}onDataSeriesRangesChanged(e){this.dataSets=e.map((e,t)=>({...this.dataSets?.[t],dataRange:e})),this.state.datasetDispatchResult=this.props.canUpdateChart(this.props.chartId,{dataSets:this.dataSets})}onDataSeriesReordered(e){let t=_f({dataSets:this.dataSets},this.dataSets.length);this.datasetOrientation=void 0;let n=this.dataSets.map(e=>t.next());this.dataSets=e.map(e=>({backgroundColor:n[e],...this.dataSets[e]})),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{dataSets:this.dataSets})}onDataSeriesRemoved(e){let t=_f({dataSets:this.dataSets},this.dataSets.length),n=this.dataSets.map(e=>t.next());this.dataSets=this.dataSets.map((e,t)=>({backgroundColor:n[t],...e})).filter((t,n)=>n!==e),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{dataSets:this.dataSets})}onDataSeriesConfirmed(){this.dataSets=this.splitRanges,this.datasetOrientation=this.computeDatasetOrientation(),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{dataSets:this.dataSets}),this.state.datasetDispatchResult.isSuccessful&&(this.dataSets=this.env.model.getters.getChartDefinition(this.props.chartId).dataSets)}get splitRanges(){let e=[];for(let t of this.dataSets){let n=t.dataRange;if(!this.env.model.getters.isRangeValid(n)){e.push(t);continue}let{sheetName:r}=Pc(n),i=r?`${r}!`:``,a=ln(n);if(a.bottom!==a.top&&a.left!==a.right){if(this.datasetOrientation!==`rows`){if(a.right!==void 0)for(let n=a.left;n<=a.right;++n){let r=n===a.left?t:{yAxisId:t.yAxisId};e.push({...r,dataRange:`${i}${hn({left:n,right:n,top:a.top,bottom:a.bottom})}`})}else if(a.bottom!==void 0)for(let n=a.top;n<=a.bottom;++n){let r=n===a.top?t:{yAxisId:t.yAxisId};e.push({...r,dataRange:`${i}${hn({left:a.left,right:a.right,top:n,bottom:n})}`})}}else if(a.bottom!==void 0)for(let n=a.top;n<=a.bottom;++n){let r=n===a.top?t:{yAxisId:t.yAxisId};e.push({...r,dataRange:`${i}${hn({left:a.left,right:a.right,top:n,bottom:n})}`})}else if(a.right!==void 0)for(let n=a.left;n<=a.right;++n){let r=n===a.left?t:{yAxisId:t.yAxisId};e.push({...r,dataRange:`${i}${hn({left:n,right:n,top:a.top,bottom:a.bottom})}`})}}else e.push(t)}return e}getDataSeriesRanges(){return this.dataSets}onLabelRangeChanged(e){this.labelRange=e[0],this.state.labelsDispatchResult=this.props.canUpdateChart(this.props.chartId,{labelRange:this.labelRange})}onLabelRangeConfirmed(){this.state.labelsDispatchResult=this.props.updateChart(this.props.chartId,{labelRange:this.labelRange})}getLabelRange(){return this.labelRange||``}onUpdateAggregated(e){this.props.updateChart(this.props.chartId,{aggregated:e})}calculateHeaderPosition(){if(this.isDatasetInvalid||this.isLabelInvalid)return;let e=this.env.model.getters,t=e.getActiveSheetId(),n=Zc(e,t,this.labelRange),r=td(e,this.dataSets,t,this.props.definition.dataSetsHaveTitle);if(r.length)return this.datasetOrientation===`rows`?r[0].dataRange.zone.left:r[0].dataRange.zone.top+1;if(n)return n.zone.top+1}get maxNumberOfUsedRanges(){return f_.get(this.props.definition.type).dataSeriesLimit}transposeDataSet(e,t){let n=this.env.model.getters;if(t===void 0)return e.filter(C).map(e=>({dataRange:e}));let r={},i=[],a=n.getFigureIdFromChartId(this.props.chartId),o=n.getFigureSheetId(a),s=n.getActiveSheet().name;o&&(s=n.getSheet(o).name);for(let t of e){if(!t)continue;if(!fn(t))return e.filter(C).map(e=>({dataRange:e}));let{sheetName:n,xc:i}=Pc(t);n??=s,r[n]||(r[n]=[]),r[n].push(un(i))}for(let e in r){let n=r[e],a=Xn(n);if(t===`columns`)for(let t of a)for(let n=t.left;n<=t.right;n++){let r=`${e===s?``:e+`!`}${hn({...t,left:n,right:n})}`;i.push({dataRange:r})}else for(let t of a)for(let n=t.top;n<=t.bottom;n++){let r=`${e===s?``:e+`!`}${hn({...t,top:n,bottom:n})}`;i.push({dataRange:r})}}return i}},kV=class extends OV{static template=`o-spreadsheet-BarConfigPanel`;get stackedLabel(){return this.props.definition.horizontal?this.chartTerms.StackedBarChart:this.chartTerms.StackedColumnChart}onUpdateStacked(e){this.props.updateChart(this.props.chartId,{stacked:e})}},AV=class extends t.Component{static template=`o-spreadsheet.BadgeSelection`;static props={choices:Array,onChange:Function,selectedValue:String}},jV=class extends t.Component{static template=`o-spreadsheet.ChartTitle`;static components={Section:q,TextStyler:xV,TextInput:gV};static props={title:{type:String,optional:!0},placeholder:{type:String,optional:!0},updateTitle:Function,name:{type:String},style:Object,defaultStyle:{type:Object,optional:!0},updateStyle:Function};static defaultProps={title:``,placeholder:``};updateTitle(e){this.props.updateTitle(e)}},MV=class extends t.Component{static template=`o-spreadsheet-AxisDesignEditor`;static components={Section:q,ChartTitle:jV,BadgeSelection:AV};static props={chartId:String,definition:Object,updateChart:Function,axesList:Array};state=(0,t.useState)({currentAxis:`x`});defaultFontSize=12;get axisTitleStyle(){return this.props.definition.axesDesign?.[this.state.currentAxis]?.title??{}}get badgeAxes(){return this.props.axesList.map(e=>({value:e.id,label:e.name}))}updateAxisEditor(e){this.state.currentAxis=e.target.value}getAxisTitle(){return(this.props.definition.axesDesign??{})[this.state.currentAxis]?.title.text||``}updateAxisTitle(e){let t=b(this.props.definition.axesDesign)??{};t[this.state.currentAxis]={...t[this.state.currentAxis],title:{...t?.[this.state.currentAxis]?.title,text:e}},this.props.updateChart(this.props.chartId,{axesDesign:t})}updateAxisTitleStyle(e){let t=b(this.props.definition.axesDesign)??{};t[this.state.currentAxis]={...t[this.state.currentAxis],title:e},this.props.updateChart(this.props.chartId,{axesDesign:t})}},NV=class extends t.Component{static template=`o-spreadsheet.RadioSelection`;static props={choices:Array,onChange:Function,selectedValue:{optional:!1},name:String,direction:{type:String,optional:!0}};static defaultProps={direction:`horizontal`}},PV=class extends t.Component{static template=`o-spreadsheet-GeneralDesignEditor`;static components={RoundColorPicker:bk,ChartTitle:jV,Section:q,SidePanelCollapsible:Vv,RadioSelection:NV};static props={...wV,defaultChartTitleFontSize:{type:Number,optional:!0},slots:{type:Object,optional:!0}};static defaultProps={defaultChartTitleFontSize:16};state;setup(){this.state=(0,t.useState)({activeTool:``})}get title(){return this.props.definition.title}toggleDropdownTool(e,t){let n=this.state.activeTool===e;this.state.activeTool=n?``:e}updateBackgroundColor(e){this.props.updateChart(this.props.chartId,{background:e})}updateTitle(e){let t={...this.title,text:e};this.props.updateChart(this.props.chartId,{title:t})}updateChartTitleStyle(e){let t={...this.title,...e};this.props.updateChart(this.props.chartId,{title:t}),this.state.activeTool=``}},FV=class extends t.Component{static template=`o-spreadsheet-ChartHumanizeNumbers`;static components={Checkbox:Fk};static props=wV;get title(){let e=this.env.model.getters.getLocale();return k(`E.g. 1234567 -> %(value)s`,{value:z(1234567,{format:gs({value:1234567},void 0,e),locale:e})})}},IV=class extends t.Component{static template=`o-spreadsheet-ChartLegend`;static components={Section:q};static props=wV;updateLegendPosition(e){this.props.updateChart(this.props.chartId,{legendPosition:e.target.value})}},LV=class extends hV{static template=`o-spreadsheet-NumberInput`;static components={};static props={...hV.props,min:{type:Number,optional:!0},max:{type:Number,optional:!0}};debouncedOnChange=dt(this.props.onChange.bind(this),100,!0);save(){let e=(this.inputRef.el?.value||``).trim();e!==this.props.value.toString()&&this.debouncedOnChange(e)}get inputClass(){return[this.props.class,`o-input`].join(` `)}},RV=class extends t.Component{static template=`o-spreadsheet-SeriesDesignEditor`;static components={SidePanelCollapsible:Vv,Section:q,RoundColorPicker:bk};static props={...wV,slots:{type:Object,optional:!0}};state=(0,t.useState)({index:0});getDataSeries(){let e=this.env.model.getters.getChartRuntime(this.props.chartId);return!e||!(`chartJsConfig`in e)?[]:e.chartJsConfig.data.datasets.filter(e=>!vd(e.xAxisID??``)).map(e=>e.label)}updateEditedSeries(e){this.state.index=e.target.selectedIndex}updateDataSeriesColor(e){let t=this.props.definition.dataSets;t?.[this.state.index]&&(t[this.state.index]={...t[this.state.index],backgroundColor:e},this.props.updateChart(this.props.chartId,{dataSets:t}))}getDataSeriesColor(){let e=this.props.definition.dataSets;if(!e?.[this.state.index])return``;let t=e[this.state.index].backgroundColor;return t?wr(t):Zr(this.state.index,Qr(this.props.definition.dataSets.length))}updateDataSeriesLabel(e){let t=e.target.value,n=this.props.definition.dataSets;n?.[this.state.index]&&(n[this.state.index]={...n[this.state.index],label:t},this.props.updateChart(this.props.chartId,{dataSets:n}))}getDataSeriesLabel(){return this.props.definition.dataSets[this.state.index]?.label||this.getDataSeries()[this.state.index]}},zV=class extends t.Component{static template=`o-spreadsheet-SeriesWithAxisDesignEditor`;static components={SeriesDesignEditor:RV,Checkbox:Fk,RadioSelection:NV,Section:q,RoundColorPicker:bk,NumberInput:LV};static props={...wV,slots:{type:Object,optional:!0}};axisChoices=hd;updateDataSeriesAxis(e,t){let n=[...this.props.definition.dataSets];n?.[e]&&(n[e]={...n[e],yAxisId:t===`left`?`y`:`y1`},this.props.updateChart(this.props.chartId,{dataSets:n}))}getDataSerieAxis(e){let t=this.props.definition.dataSets;return t?.[e]&&t[e].yAxisId===`y1`?`right`:`left`}get canHaveTwoVerticalAxis(){return!(`horizontal`in this.props.definition&&this.props.definition.horizontal)}toggleDataTrend(e,t){let n=[...this.props.definition.dataSets];n?.[e]&&(n[e]={...n[e],trend:{type:`polynomial`,order:1,...n[e].trend,display:t}},this.props.updateChart(this.props.chartId,{dataSets:n}))}getTrendLineConfiguration(e){return this.props.definition.dataSets?.[e]?.trend}getTrendType(e){return e?e.type===`polynomial`&&e.order===1?`linear`:e.type:``}onChangeTrendType(e,t){let n=t.target.value,r;switch(n){case`linear`:case`polynomial`:r={type:`polynomial`,order:n===`linear`?1:this.getMaxPolynomialDegree(e)};break;case`exponential`:case`logarithmic`:case`trailingMovingAverage`:r={type:n};break;default:return}this.updateTrendLineValue(e,r)}getPolynomialDegrees(e){return S(1,this.getMaxPolynomialDegree(e)+1)}onChangePolynomialDegree(e,t){let n=t.target;this.updateTrendLineValue(e,{order:parseInt(n.value)})}getMaxPolynomialDegree(e){let t=this.env.model.getters.getChartRuntime(this.props.chartId);return Math.min(10,t.chartJsConfig.data.datasets[e].data.length-1)}get defaultWindowSize(){return 2}onChangeMovingAverageWindow(e,t){let n=parseInt(t)||2;n<=1&&(n=2),this.updateTrendLineValue(e,{window:n})}getDataSeriesColor(e){let t=this.props.definition.dataSets;if(!t?.[e])return``;let n=t[e].backgroundColor;return n?wr(n):Zr(e,Qr(this.props.definition.dataSets.length))}getTrendLineColor(e){return this.getTrendLineConfiguration(e)?.color??Br(this.getDataSeriesColor(e),.5)}updateTrendLineColor(e,t){this.updateTrendLineValue(e,{color:t})}updateTrendLineValue(e,t){let n=[...this.props.definition.dataSets];n?.[e]&&(n[e]={...n[e],trend:{...n[e].trend,...t}},this.props.updateChart(this.props.chartId,{dataSets:n}))}},BV=class extends t.Component{static template=`o-spreadsheet-ChartShowValues`;static components={Checkbox:Fk};static props={...wV,defaultValue:{type:Boolean,optional:!0}}},VV=class extends t.Component{static template=`o-spreadsheet-ChartWithAxisDesignPanel`;static components={GeneralDesignEditor:PV,SidePanelCollapsible:Vv,Section:q,AxisDesignEditor:MV,SeriesWithAxisDesignEditor:zV,ChartLegend:IV,ChartShowValues:BV,ChartHumanizeNumbers:FV};static props=wV;get axesList(){let{useLeftAxis:e,useRightAxis:t}=fd(this.props.definition),n=[{id:`x`,name:k(`Horizontal axis`)}];return e&&n.push({id:`y`,name:k(t?`Left axis`:`Vertical axis`)}),t&&n.push({id:`y1`,name:k(e?`Right axis`:`Vertical axis`)}),n}},HV=class extends VV{static template=`o-spreadsheet-GenericZoomableChartDesignPanel`;static components={...VV.components,Checkbox:Fk};onToggleZoom(e){this.props.updateChart(this.props.chartId,{zoomable:e})}},UV=class extends HV{static template=`o-spreadsheet-BarChartDesignPanel`;get isZoomable(){return!this.props.definition.horizontal}};let WV=[`year`,`quarter_number`,`month_number`,`iso_week_number`,`day_of_month`,`day_of_week`,`hour_number`,`minute_number`,`second_number`];var GV=class extends OV{static template=`o-spreadsheet-CalendarChartConfigPanel`;groupByChoices=WV.map(e=>({value:e,label:uh[e]}));getLabelRangeOptions(){return[{name:`dataSetsHaveTitle`,label:this.dataSetsHaveTitleLabel,value:this.props.definition.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}getGroupByOptions(){let e=this.env.model.getters.getFigureSheetId(this.env.model.getters.getFigureIdFromChartId(this.props.chartId)),t=td(this.env.model.getters,this.props.definition.dataSets,e,this.props.definition.dataSetsHaveTitle);if(t.length===0)return[];let n=Zc(this.env.model.getters,e,this.props.definition.labelRange),r=zh(this.props.definition,t,n,this.env.model.getters).labels.filter(e=>xi(e,R));if(r.length===0)return[];let i=r.map(e=>I(e,this.env.model.getters.getLocale())),a=new Set,o=new Set,s=new Set,c=new Set,l=new Set,u=new Set;for(let e of i)a.add(e.getFullYear()),o.add(e.getMonth()),s.add(e.getDate()),c.add(e.getHours()),l.add(e.getMinutes()),u.add(e.getSeconds());return this.groupByChoices.filter(e=>{switch(e.value){case`year`:return a.size>1;case`quarter_number`:case`month_number`:return o.size>1;case`iso_week_number`:case`day_of_month`:case`day_of_week`:return s.size>1;case`hour_number`:return c.size>1;case`minute_number`:return l.size>1;case`second_number`:return u.size>1;default:return!1}})}getGroupByType(e){return(e===`horizontal`?this.props.definition.horizontalGroupBy:this.props.definition.verticalGroupBy)||`year`}updateGroupBy(e,t){this.props.updateChart(this.props.chartId,{[e===`horizontal`?`horizontalGroupBy`:`verticalGroupBy`]:t})}},KV=class extends t.Component{static template=`o-spreadsheet-ColorScalePicker`;static components={Section:q,RoundColorPicker:bk,Popover:Cv};static props={definition:Object,onUpdateColorScale:Function};colorScales=ii.map(e=>({value:e,label:Yp.ColorScales[e],className:`${e}-color-scale`}));state=(0,t.useState)({popoverProps:void 0,popoverStyle:``});popoverRef=(0,t.useRef)(`popoverRef`);setup(){(0,t.useExternalListener)(window,`click`,this.closePopover)}get currentColorScale(){return this.props.definition.colorScale||Mm(`oranges`)}get currentColorScaleStyle(){let e=this.currentColorScale,t=e.minColor||`#fff`,n=e.midColor,r=e.maxColor||`#000`;return n?`background: linear-gradient(90deg, ${t}, ${n}, ${r});`:`background: linear-gradient(90deg, ${t}, ${r});`}colorScalePreviewStyle(e){return`background: linear-gradient(90deg, ${ri[e].join(`,`)});`}get currentColorScaleLabel(){return Yp.ColorScales[this.selectedColorScale]}onColorScaleChange(e){e===`custom`?this.props.onUpdateColorScale(he):this.props.onUpdateColorScale(Mm(e)),this.closePopover()}onPointerDown(e){if(this.state.popoverProps){this.closePopover();return}let{bottom:t,right:n,width:r}=e.currentTarget.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:n,y:t,width:0,height:0},positioning:`top-right`,verticalOffset:0},this.state.popoverStyle=U({width:`${r}px`})}closePopover(){this.state.popoverProps=void 0}get selectedColorScale(){if(!this.props.definition.colorScale)return`oranges`;let{minColor:e,midColor:t,maxColor:n}=this.props.definition.colorScale||{};for(let[r,i]of Object.entries(ri))if(i[0]===e&&i[2]===n&&i[1]===t)return r;return`custom`}getCustomColorScaleColor(e){return this.props.definition.colorScale?.[e]??``}setCustomColorScaleColor(e,t){!t&&e!==`midColor`&&(t=`#fff`);let n=this.currentColorScale;n&&this.props.onUpdateColorScale({...n,[e]:t})}},qV=class extends t.Component{static template=`o-spreadsheet-CalendarChartDesignPanel`;static components={GeneralDesignEditor:PV,SidePanelCollapsible:Vv,Section:q,AxisDesignEditor:MV,ChartShowValues:BV,ColorScalePicker:KV,RoundColorPicker:bk};static props=wV;get axesList(){return[{id:`x`,name:k(`Horizontal axis`)},{id:`y`,name:k(`Vertical axis`)}]}onColormapChange(e){this.props.updateChart(this.props.chartId,{colorScale:e})}updateMissingValueColor(e){this.props.updateChart(this.props.chartId,{missingValueColor:e})}get selectedMissingValueColor(){return this.props.definition.missingValueColor}updateLegendPosition(e){let t=e.target.value;this.props.updateChart(this.props.chartId,{legendPosition:t})}},JV=class extends t.Component{static template=`o-spreadsheet-ChartShowDataMarkers`;static components={Checkbox:Fk};static props=wV},YV=class extends HV{static template=`o-spreadsheet-ComboChartDesignPanel`;static components={...HV.components,ChartShowDataMarkers:JV,RadioSelection:NV};seriesTypeChoices=[{value:`bar`,label:k(`Bar`)},{value:`line`,label:k(`Line`)}];updateDataSeriesType(e,t){let n=[...this.props.definition.dataSets];n?.[e]&&(n[e]={...n[e],type:t},this.props.updateChart(this.props.chartId,{dataSets:n}))}getDataSeriesType(e){let t=this.props.definition.dataSets;return t?.[e]?t[e].type??`line`:`bar`}},XV=class extends OV{getLabelRangeOptions(){let e=this.props.definition;return[{name:`aggregated`,label:this.chartTerms.AggregatedChart,value:e.aggregated??!1,onChange:this.onUpdateAggregated.bind(this)},{name:`cumulative`,label:this.chartTerms.CumulativeData,value:e.cumulative??!1,onChange:this.onUpdateCumulative.bind(this)},{name:`dataSetsHaveTitle`,label:this.dataSetsHaveTitleLabel,value:e.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}onUpdateCumulative(e){this.props.updateChart(this.props.chartId,{cumulative:e})}},ZV=class extends t.Component{static template=`o-spreadsheet-FunnelChartDesignPanel`;static components={ChartShowValues:BV,GeneralDesignEditor:PV,SidePanelCollapsible:Vv,RoundColorPicker:bk,Section:q,ChartHumanizeNumbers:FV};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function};getFunnelColorItems(){let e=this.env.model.getters.getChartRuntime(this.props.chartId).chartJsConfig.data.labels||[],t=sf(e,this.props.definition.funnelColors);return e.map((e,n)=>({label:e||k(`Value %s`,n+1),color:t[n]}))}updateFunnelItemColor(e,t){let n=At(this.props.definition.funnelColors||[],t,e);this.props.updateChart(this.props.chartId,{funnelColors:n})}},QV=class extends t.Component{static template=`o-spreadsheet-GaugeChartConfigPanel`;static components={ChartErrorSection:EV,ChartDataSeries:TV};static props=wV;state=(0,t.useState)({dataRangeDispatchResult:void 0});dataRange=this.props.definition.dataRange;get configurationErrorMessages(){return[...this.state.dataRangeDispatchResult?.reasons||[]].filter(e=>e!==`NoChanges`).map(e=>Yp.Errors[e]||Yp.Errors.Unexpected)}get isDataRangeInvalid(){return!!this.state.dataRangeDispatchResult?.isCancelledBecause(`InvalidGaugeDataRange`)}onDataRangeChanged(e){this.dataRange=e[0],this.state.dataRangeDispatchResult=this.props.canUpdateChart(this.props.chartId,{dataRange:this.dataRange})}updateDataRange(){this.state.dataRangeDispatchResult=this.props.updateChart(this.props.chartId,{dataRange:this.dataRange})}getDataRange(){return{dataRange:this.dataRange||``}}},$V=class extends t.Component{static template=`o-spreadsheet-GaugeChartDesignPanel`;static components={SidePanelCollapsible:Vv,Section:q,RoundColorPicker:bk,GeneralDesignEditor:PV,ChartErrorSection:EV,StandaloneComposer:fk,ChartHumanizeNumbers:FV};static props=wV;state;setup(){this.state=(0,t.useState)({sectionRuleCancelledReasons:new Set(this.checkSectionRuleFormulasAreValid(this.props.definition.sectionRule)),sectionRule:b(this.props.definition.sectionRule)})}get designErrorMessages(){return[...this.state.sectionRuleCancelledReasons||[]].filter(e=>e!==`NoChanges`).map(e=>Yp.Errors[e]||Yp.Errors.Unexpected)}get isRangeMinInvalid(){return!!(this.state.sectionRuleCancelledReasons?.has(`EmptyGaugeRangeMin`)||this.state.sectionRuleCancelledReasons?.has(`GaugeRangeMinNaN`))}get isRangeMaxInvalid(){return!!(this.state.sectionRuleCancelledReasons?.has(`EmptyGaugeRangeMax`)||this.state.sectionRuleCancelledReasons?.has(`GaugeRangeMaxNaN`))}get isLowerInflectionPointInvalid(){return!!this.state.sectionRuleCancelledReasons?.has(`GaugeLowerInflectionPointNaN`)}get isUpperInflectionPointInvalid(){return!!this.state.sectionRuleCancelledReasons?.has(`GaugeUpperInflectionPointNaN`)}updateSectionColor(e,t){let n=b(this.state.sectionRule);n.colors[e]=t,this.updateSectionRule(n)}updateSectionRule(e){this.state.sectionRuleCancelledReasons=new Set(this.checkSectionRuleFormulasAreValid(this.state.sectionRule));let t=this.props.updateChart(this.props.chartId,{sectionRule:e});if(t.isSuccessful)this.state.sectionRule=b(e);else for(let e of t.reasons)this.state.sectionRuleCancelledReasons.add(e)}onConfirmGaugeRange(e,t){this.state.sectionRule={...this.state.sectionRule,[e]:t},this.updateSectionRule(this.state.sectionRule)}getGaugeInflectionComposerProps(e){let t=e===`lowerColor`?`lowerInflectionPoint`:`upperInflectionPoint`,n=this.state.sectionRule[t];return{onConfirm:e=>{this.state.sectionRule={...this.state.sectionRule,[t]:{...n,value:e}},this.updateSectionRule(this.state.sectionRule)},composerContent:n.value,invalid:e===`lowerColor`?this.isLowerInflectionPointInvalid:this.isUpperInflectionPointInvalid,defaultRangeSheetId:this.sheetId,class:t,placeholder:k(`Value`),title:k(`Value or formula`)}}checkSectionRuleFormulasAreValid(e){let t=new Set;return this.valueIsValidNumber(e.rangeMin)||t.add(`GaugeRangeMinNaN`),this.valueIsValidNumber(e.rangeMax)||t.add(`GaugeRangeMaxNaN`),this.valueIsValidNumber(e.lowerInflectionPoint.value)||t.add(`GaugeLowerInflectionPointNaN`),this.valueIsValidNumber(e.upperInflectionPoint.value)||t.add(`GaugeUpperInflectionPointNaN`),t}valueIsValidNumber(e){let t=this.env.model.getters.getLocale();if(!e.startsWith(`=`))return Oa(e,t)!==void 0;let n=this.env.model.getters.evaluateFormula(this.sheetId,e);return gm(n)?!1:Oa(mm(n),t)!==void 0}get sheetId(){let e=this.env.model.getters.getChart(this.props.chartId);if(!e)throw Error(`Chart not found with id `+this.props.chartId);return e.sheetId}},eH=class extends t.Component{static template=`o-spreadsheet-GeoChartRegionSelectSection`;static components={Section:q};static props={chartId:String,definition:Object,updateChart:Function};updateSelectedRegion(e){let t=e.target.value;this.props.updateChart(this.props.chartId,{region:t})}get availableRegions(){return this.env.model.getters.getGeoChartAvailableRegions()}get selectedRegion(){return this.props.definition.region||this.availableRegions[0]?.id}},tH=class extends OV{static template=`o-spreadsheet-GeoChartConfigPanel`;static components={...OV.components,GeoChartRegionSelectSection:eH};get dataRanges(){return this.getDataSeriesRanges()}get disabledRanges(){return this.props.definition.dataSets.map((e,t)=>t>0)}getLabelRangeOptions(){return[{name:`dataSetsHaveTitle`,label:this.dataSetsHaveTitleLabel,value:this.props.definition.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}},nH=class extends VV{static template=`o-spreadsheet-GeoChartDesignPanel`;static components={...VV.components,RoundColorPicker:bk,ColorScalePicker:KV};updateColorScale(e){this.props.updateChart(this.props.chartId,{colorScale:e})}updateMissingValueColor(e){this.props.updateChart(this.props.chartId,{missingValueColor:e})}updateLegendPosition(e){let t=e.target.value;this.props.updateChart(this.props.chartId,{legendPosition:t})}get selectedMissingValueColor(){return this.props.definition.missingValueColor||`#ffffff`}},rH=class extends OV{static template=`o-spreadsheet-HierarchicalChartConfigPanel`;static components={...OV.components};getLabelRangeOptions(){return[{name:`dataSetsHaveTitle`,label:this.dataSetsHaveTitleLabel,value:this.props.definition.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}},iH=class extends OV{static template=`o-spreadsheet-LineConfigPanel`;get canTreatLabelsAsText(){let e=this.env.model.getters.getChart(this.props.chartId);return e&&e instanceof k_?rg(e.getDefinition(),e.dataSets,e.labelRange,this.env.model.getters):!1}get stackedLabel(){return this.props.definition.fillArea?this.chartTerms.StackedAreaChart:this.chartTerms.StackedLineChart}getLabelRangeOptions(){let e=super.getLabelRangeOptions();return this.canTreatLabelsAsText&&e.push({name:`labelsAsText`,value:this.props.definition.labelsAsText,label:this.chartTerms.TreatLabelsAsText,onChange:this.onUpdateLabelsAsText.bind(this)}),e}onUpdateLabelsAsText(e){this.props.updateChart(this.props.chartId,{labelsAsText:e})}onUpdateStacked(e){this.props.updateChart(this.props.chartId,{stacked:e})}onUpdateCumulative(e){this.props.updateChart(this.props.chartId,{cumulative:e})}},aH=class extends HV{static template=`o-spreadsheet-LineChartDesignPanel`;static components={...HV.components,ChartShowDataMarkers:JV}},oH=class extends t.Component{static template=`o-spreadsheet.PieHoleSize`;static components={Section:q,NumberInput:LV};static props={onValueChange:Function,value:Number};onChange(e){isNaN(Number(e))||this.props.onValueChange(x(Number(e),0,95))}},sH=class extends t.Component{static template=`o-spreadsheet-PieChartDesignPanel`;static components={GeneralDesignEditor:PV,Section:q,ChartLegend:IV,ChartShowValues:BV,PieHoleSize:oH,Checkbox:Fk,ChartHumanizeNumbers:FV};static props=wV;onPieHoleSizeChange(e){this.props.updateChart(this.props.chartId,{...this.props.definition,pieHolePercentage:e})}get defaultHoleSize(){return 50}},cH=class extends t.Component{static template=`o-spreadsheet-RadarChartDesignPanel`;static components={GeneralDesignEditor:PV,SeriesDesignEditor:RV,Section:q,ChartLegend:IV,ChartShowValues:BV,ChartShowDataMarkers:JV,Checkbox:Fk,ChartHumanizeNumbers:FV};static props=wV},lH=class e extends Af{dataSets;labelRange;background;legendPosition;labelsAsText;aggregated;type=`scatter`;dataSetsHaveTitle;dataSetDesign;axesDesign;showValues;constructor(e,t,n){super(e,t,n),this.dataSets=td(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Zc(this.getters,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.labelsAsText=e.labelsAsText,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues}static validateChartDefinition(e,t){return e.checkValidations(t,cd,ld)}static transformDefinition(e,t,n){return ad(e,t,n)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,labelsAsText:e.labelsAsText??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`scatter`,labelRange:e.auxiliaryRange||void 0,aggregated:e.aggregated??!1,axesDesign:e.axesDesign,showValues:e.showValues,humanize:e.humanize}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`scatter`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,labelsAsText:this.labelsAsText,aggregated:this.aggregated,axesDesign:this.axesDesign,showValues:this.showValues,humanize:this.humanize}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=Zu(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}getDefinitionForExcel(){let e=this.dataSets.map(e=>rd(this.getters,e)).filter(e=>e.range!==``),t=id(this.getters,this.labelRange,ud(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),n=this.getDefinition();return{...n,backgroundColor:V(this.background||`#FFFFFF`),fontColor:V(od(this.background)),dataSets:e,labelRange:t,verticalAxis:fd(n)}}duplicateInDuplicatedSheet(t){let n=Qu(this.sheetId,t,this.dataSets),r=$u(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}};function uH(e,t){let n=e.getDefinition(),r=Wh(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`line`,data:{labels:r.labels,datasets:ef(n,r)},options:{...Vp,layout:Tg(n,r),scales:Ld(n,r),plugins:{title:Gg(n,t),legend:jg(n,r),tooltip:Zg(n,r),chartShowValuesPlugin:zg(n,r)}}},background:e.background||`#FFFFFF`}}var dH=class extends OV{static template=`o-spreadsheet-ScatterConfigPanel`;get canTreatLabelsAsText(){let e=this.env.model.getters.getChart(this.props.chartId);return e&&e instanceof lH?rg(e.getDefinition(),e.dataSets,e.labelRange,this.env.model.getters):!1}onUpdateLabelsAsText(e){this.props.updateChart(this.props.chartId,{labelsAsText:e})}getLabelRangeOptions(){let e=super.getLabelRangeOptions();return this.canTreatLabelsAsText&&e.push({name:`labelsAsText`,value:this.props.definition.labelsAsText,label:this.chartTerms.TreatLabelsAsText,onChange:this.onUpdateLabelsAsText.bind(this)}),e}},fH=class extends t.Component{static template=`o-spreadsheet-ScorecardChartConfigPanel`;static components={SelectionInput:kk,ChartErrorSection:EV,Section:q};static props=wV;state=(0,t.useState)({keyValueDispatchResult:void 0,baselineDispatchResult:void 0});keyValue=this.props.definition.keyValue;baseline=this.props.definition.baseline;get errorMessages(){return[...this.state.keyValueDispatchResult?.reasons||[],...this.state.baselineDispatchResult?.reasons||[]].filter(e=>e!==`NoChanges`).map(e=>Yp.Errors[e]||Yp.Errors.Unexpected)}get isKeyValueInvalid(){return!!this.state.keyValueDispatchResult?.isCancelledBecause(`InvalidScorecardKeyValue`)}get isBaselineInvalid(){return!!this.state.keyValueDispatchResult?.isCancelledBecause(`InvalidScorecardBaseline`)}onKeyValueRangeChanged(e){this.keyValue=e[0],this.state.keyValueDispatchResult=this.props.canUpdateChart(this.props.chartId,{keyValue:this.keyValue})}updateKeyValueRange(){this.state.keyValueDispatchResult=this.props.updateChart(this.props.chartId,{keyValue:this.keyValue})}getKeyValueRange(){return this.keyValue||``}onBaselineRangeChanged(e){this.baseline=e[0],this.state.baselineDispatchResult=this.props.canUpdateChart(this.props.chartId,{baseline:this.baseline})}updateBaselineRange(){this.state.baselineDispatchResult=this.props.updateChart(this.props.chartId,{baseline:this.baseline})}getBaselineRange(){return this.baseline||``}updateBaselineMode(e){this.props.updateChart(this.props.chartId,{baselineMode:e.target.value})}},pH=class extends t.Component{static template=`o-spreadsheet-ScorecardChartDesignPanel`;static components={GeneralDesignEditor:PV,RoundColorPicker:bk,SidePanelCollapsible:Vv,Section:q,Checkbox:Fk,ChartTitle:jV,ChartHumanizeNumbers:FV};static props=wV;get colorsSectionTitle(){return this.props.definition.baselineMode===`progress`?k(`Progress bar colors`):k(`Baseline colors`)}get defaultScorecardTitleFontSize(){return 14}translate(e){return this.env.model.getters.dynamicTranslate(e)}setColor(e,t){switch(t){case`backgroundColor`:this.props.updateChart(this.props.chartId,{background:e});break;case`baselineColorDown`:this.props.updateChart(this.props.chartId,{baselineColorDown:e});break;case`baselineColorUp`:this.props.updateChart(this.props.chartId,{baselineColorUp:e});break}}get keyStyle(){return{align:`center`,fontSize:32,...this.props.definition.keyDescr}}get baselineStyle(){return{align:`center`,fontSize:16,...this.props.definition.baselineDescr}}setKeyText(e){this.props.updateChart(this.props.chartId,{keyDescr:{...this.props.definition.keyDescr,text:e}})}updateKeyStyle(e){let t={...this.keyStyle,...e};this.props.updateChart(this.props.chartId,{keyDescr:t})}setBaselineText(e){this.props.updateChart(this.props.chartId,{baselineDescr:{...this.props.definition.baselineDescr,text:e}})}updateBaselineStyle(e){let t={...this.baselineStyle,...e};this.props.updateChart(this.props.chartId,{baselineDescr:t})}},mH=class extends t.Component{static template=`o-spreadsheet-SunburstChartDesignPanel`;static components={GeneralDesignEditor:PV,Section:q,SidePanelCollapsible:Vv,ChartShowValues:BV,Checkbox:Fk,TextStyler:xV,RoundColorPicker:bk,ChartLegend:IV,PieHoleSize:oH,ChartHumanizeNumbers:FV};static props=wV;defaults=Rg;get showValues(){return this.props.definition.showValues??Rg.showValues}get showLabels(){return this.props.definition.showLabels??Rg.showLabels}get groupColors(){let e=this.props.chartId;return this.env.model.getters.getChartRuntime(e).chartJsConfig.data.datasets[0]?.groupColors||[]}onGroupColorChanged(e,t){let n=b(this.props.definition.groupColors)??[];n[e]=t,this.props.updateChart(this.props.chartId,{groupColors:n})}onPieHoleSizeChange(e){this.props.updateChart(this.props.chartId,{...this.props.definition,pieHolePercentage:e})}},hH=class extends t.Component{static template=`o-spreadsheet-TreeMapCategoryColors`;static components={Checkbox:Fk,RoundColorPicker:bk};static props={chartId:String,definition:Object,onColorChanged:Function};get coloringOptions(){let e=this.props.definition.coloringOptions??Td.coloringOptions;if(e.type!==`categoryColor`)throw Error(`Coloring options is not solid color`);return e}getTreeGroupAndColors(){return this.env.model.getters.getChartRuntime(this.props.chartId).chartJsConfig.data.datasets[0]?.groupColors||[]}onGroupColorChanged(e,t){let n=b(this.coloringOptions);n.colors[e]=t||void 0,this.props.onColorChanged(n)}useValueBasedGradient(e){if(this.coloringOptions.type!==`categoryColor`)throw Error(`Coloring options is not solid color`);this.props.onColorChanged({...this.coloringOptions,useValueBasedGradient:e})}},gH=class extends t.Component{static template=`o-spreadsheet-TreeMapColorScale`;static components={RoundColorPicker:bk};static props={chartId:String,definition:Object,onColorChanged:Function};get coloringOptions(){let e=this.props.definition.coloringOptions??Td.coloringOptions;if(e.type!==`colorScale`)throw Error(`Coloring options is not a color scale`);return e}setColorScaleColor(e,t){this.props.onColorChanged({...this.coloringOptions,[e]:t})}};let _H={type:`colorScale`,minColor:`#FFF5EB`,midColor:`#FD8D3C`,maxColor:`#7F2704`},vH={type:`categoryColor`,colors:[],useValueBasedGradient:!0};var yH=class extends t.Component{static template=`o-spreadsheet-TreeMapChartDesignPanel`;static components={GeneralDesignEditor:PV,Section:q,SidePanelCollapsible:Vv,ChartShowValues:BV,Checkbox:Fk,TextStyler:xV,RoundColorPicker:bk,BadgeSelection:AV,TreeMapCategoryColors:hH,TreeMapColorScale:gH,ChartHumanizeNumbers:FV};static props=wV;savedColors={categoryColors:vH,colorScale:_H};defaults=Td;get showHeaders(){return this.props.definition.showHeaders??Td.showHeaders}get showValues(){return this.props.definition.showValues??Td.showValues}get showLabels(){return this.props.definition.showLabels??Td.showLabels}get coloringOptions(){return this.props.definition.coloringOptions??Td.coloringOptions}changeColoringOption(e){let t=e===`categoryColor`?this.savedColors.categoryColors:this.savedColors.colorScale;this.props.updateChart(this.props.chartId,{coloringOptions:t})}onCategoryColorChange(e){this.savedColors.categoryColors=e,this.props.updateChart(this.props.chartId,{coloringOptions:e})}onColorScaleChange(e){this.savedColors.colorScale=e,this.props.updateChart(this.props.chartId,{coloringOptions:e})}get coloringOptionChoices(){return[{label:k(`Category color`),value:`categoryColor`},{label:k(`Color scale`),value:`colorScale`}]}},bH=class extends t.Component{static template=`o-spreadsheet-WaterfallChartDesignPanel`;static components={GeneralDesignEditor:PV,ChartShowValues:BV,Checkbox:Fk,SidePanelCollapsible:Vv,Section:q,RoundColorPicker:bk,AxisDesignEditor:MV,RadioSelection:NV,ChartLegend:IV,ChartHumanizeNumbers:FV};static props=wV;axisChoices=hd;onUpdateShowSubTotals(e){this.props.updateChart(this.props.chartId,{showSubTotals:e})}onUpdateShowConnectorLines(e){this.props.updateChart(this.props.chartId,{showConnectorLines:e})}onUpdateFirstValueAsSubtotal(e){this.props.updateChart(this.props.chartId,{firstValueAsSubtotal:e})}updateColor(e,t){this.props.updateChart(this.props.chartId,{[e]:t})}get axesList(){return[{id:`x`,name:k(`Horizontal axis`)},{id:`y`,name:k(`Vertical axis`)}]}get positiveValuesColor(){return this.props.definition.positiveValuesColor||`#4EA7F2`}get negativeValuesColor(){return this.props.definition.negativeValuesColor||`#EA6175`}get subTotalValuesColor(){return this.props.definition.subTotalValuesColor||`#AAAAAA`}updateVerticalAxisPosition(e){this.props.updateChart(this.props.chartId,{verticalAxisPosition:e})}onToggleZoom(e){this.props.updateChart(this.props.chartId,{zoomable:e})}};let xH=new B;xH.add(`line`,{configuration:iH,design:aH}).add(`scatter`,{configuration:dH,design:VV}).add(`bar`,{configuration:kV,design:UV}).add(`combo`,{configuration:OV,design:YV}).add(`pie`,{configuration:OV,design:sH}).add(`gauge`,{configuration:QV,design:$V}).add(`scorecard`,{configuration:fH,design:pH}).add(`waterfall`,{configuration:OV,design:bH}).add(`pyramid`,{configuration:OV,design:VV}).add(`radar`,{configuration:OV,design:cH}).add(`sunburst`,{configuration:rH,design:mH}).add(`geo`,{configuration:tH,design:nH}).add(`funnel`,{configuration:XV,design:ZV}).add(`treemap`,{configuration:rH,design:yH}).add(`calendar`,{configuration:GV,design:qV});let SH={line:k(`Line`),column:k(`Column`),bar:k(`Bar`),area:k(`Area`),pie:k(`Pie`),hierarchical:k(`Hierarchical`),misc:k(`Miscellaneous`)};var CH=class extends t.Component{static template=`o-spreadsheet-ChartTypePicker`;static components={Section:q,Popover:Cv};static props={chartId:String,chartPanelStore:Object};categories=SH;chartTypeByCategories={};popoverRef=(0,t.useRef)(`popoverRef`);selectRef=(0,t.useRef)(`selectRef`);state=(0,t.useState)({popoverProps:void 0,popoverStyle:``});setup(){(0,t.useExternalListener)(window,`pointerdown`,this.onExternalClick,{capture:!0});for(let e of K_.getAll())this.chartTypeByCategories[e.category]?this.chartTypeByCategories[e.category].push(e):this.chartTypeByCategories[e.category]=[e]}onExternalClick(e){Zf(this.popoverRef.el?.parentElement,e)||Zf(this.selectRef.el,e)||this.closePopover()}onTypeChange(e){this.props.chartPanelStore.changeChartType(this.props.chartId,e),this.closePopover()}getChartDefinition(e){return this.env.model.getters.getChartDefinition(e)}getSelectedChartSubtypeProperties(){let e=this.getChartDefinition(this.props.chartId);return K_.getAll().find(t=>t.matcher?.(e)||!1)||K_.get(e.type)}onPointerDown(e){if(this.state.popoverProps){this.closePopover();return}let{bottom:t,right:n,width:r}=e.currentTarget.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:n,y:t,width:0,height:0},positioning:`top-right`,verticalOffset:0},this.state.popoverStyle=U({width:`${r}px`})}closePopover(){this.state.popoverProps=void 0}},wH=class extends hr{mutators=[`activatePanel`,`changeChartType`];panel=`configuration`;creationContexts={};activatePanel(e){this.panel=e}changeChartType(e,t){let n=this.getters.getContextCreationChart(e),r=this.creationContexts[e]||{},i=n?.range;i?.every((e,t)=>w(e,r.range?.[t]))&&(i=Object.assign([],r.range,n?.range)),this.creationContexts[e]={...r,...n,range:i};let a=this.getters.getFigureIdFromChartId(e),o=this.getters.getFigureSheetId(a);if(!o)return;let s=this.getChartDefinitionFromContextCreation(e,t);this.model.dispatch(`UPDATE_CHART`,{definition:s,chartId:e,figureId:a,sheetId:o})}getChartDefinitionFromContextCreation(e,t){let n=K_.get(t);return{...f_.get(n.chartType).getChartDefinitionFromContextCreation(this.creationContexts[e]),...n.subtypeDefinition}}},TH=class extends t.Component{static template=`o-spreadsheet-ChartPanel`;static components={Section:q,ChartTypePicker:CH};static props={onCloseSidePanel:Function,chartId:String};store;get chartId(){return this.props.chartId}setup(){this.store=or(wH)}switchPanel(e){this.store.activatePanel(e)}updateChart(e,t){let n=this.env.model.getters.getFigureIdFromChartId(e);if(e!==this.chartId)return;let r={...this.getChartDefinition(this.chartId),...t};return this.env.model.dispatch(`UPDATE_CHART`,{definition:r,chartId:e,figureId:n,sheetId:this.env.model.getters.getFigureSheetId(n)})}canUpdateChart(e,t){let n=this.env.model.getters.getFigureIdFromChartId(e);if(e!==this.chartId||!this.env.model.getters.isChartDefined(e))return;let r={...this.getChartDefinition(this.chartId),...t};return this.env.model.canDispatch(`UPDATE_CHART`,{definition:r,chartId:e,figureId:n,sheetId:this.env.model.getters.getFigureSheetId(n)})}onTypeChange(e){this.chartId&&this.store.changeChartType(this.chartId,e)}get chartPanel(){if(!this.chartId)throw Error(`Chart not defined.`);let e=this.env.model.getters.getChartType(this.chartId);if(!e)throw Error(`Chart not defined.`);let t=xH.get(e);if(!t)throw Error(`Component is not defined for type ${e}`);return t}getChartDefinition(e){return this.env.model.getters.getChartDefinition(e)}},EH=class extends t.Component{static template=`o-spreadsheet-IconPicker`;static props={onIconPicked:Function};icons=cj;iconSets=lj;onIconClick(e){e&&this.props.onIconPicked(e)}};function DH(e,t){let n=zB(e);OH({get highlights(){return n.hovered?t.highlights:[]}})}function OH(e){let n=ar(),r=or(sk);(0,t.onMounted)(()=>{r.register(e)});let i=e.highlights;(0,t.useEffect)(e=>{w(e,i)||(i=e,n.trigger(`store-updated`))},()=>[e.highlights])}var kH=class extends t.Component{static template=`o-spreadsheet-ConditionalFormatPreview`;icons=cj;ref=(0,t.useRef)(`cfPreview`);setup(){DH(this.ref,this)}getPreviewImageStyle(){let e=this.props.conditionalFormat.rule;if(e.type===`CellIsRule`)return U(uv(e.style));if(e.type===`ColorScaleRule`){let t=Sr(e.minimum.color),n=e.midpoint?Sr(e.midpoint.color):null,r=Sr(e.maximum.color),i=`background-image: linear-gradient(to right, `;return n?i+t+`, `+n+`, `+r+`)`:i+t+`, `+r+`)`}else if(e.type===`DataBarRule`)return`${`background-image: linear-gradient(to right, ${Sr(e.color)} 50%, white 50%)`}; color: ${pe};`;return``}getDescription(){let e=this.props.conditionalFormat;switch(e.rule.type){case`CellIsRule`:return W.get(e.rule.operator).getPreview({...e.rule,type:e.rule.operator},this.env.model.getters);case`ColorScaleRule`:return Jp.ColorScale;case`IconSetRule`:return Jp.IconSet;case`DataBarRule`:return Jp.DataBar}}deleteConditionalFormat(){this.env.model.dispatch(`REMOVE_CONDITIONAL_FORMAT`,{id:this.props.conditionalFormat.id,sheetId:this.env.model.getters.getActiveSheetId()})}onMouseDown(e){this.props.onMouseDown(e)}get highlights(){let e=this.env.model.getters.getActiveSheetId();return this.props.conditionalFormat.ranges.map(t=>({range:this.env.model.getters.getRangeFromSheetXC(e,t),color:ee,fillAlpha:.06}))}};kH.props={conditionalFormat:Object,onPreviewClick:Function,onMouseDown:Function,class:String};var AH=class extends t.Component{static template=`o-spreadsheet-ConditionalFormatPreviewList`;static props={conditionalFormats:Array,onPreviewClick:Function,onAddConditionalFormat:Function};static components={ConditionalFormatPreview:kH};icons=cj;dragAndDrop=Sk();cfListRef=(0,t.useRef)(`cfList`);setup(){(0,t.onWillUpdateProps)(e=>{w(this.props.conditionalFormats,e.conditionalFormats)||this.dragAndDrop.cancel()})}getPreviewDivStyle(e){return this.dragAndDrop.itemsStyle[e.id]||``}onPreviewMouseDown(e,t){if(t.button!==0)return;let n=Array.from(this.cfListRef.el.children).map(e=>tp(e)),r=this.props.conditionalFormats.map((e,t)=>({id:e.id,size:n[t].height,position:n[t].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.id,initialMousePosition:t.clientY,items:r,scrollableContainerEl:this.cfListRef.el,onDragEnd:(e,t)=>this.onDragEnd(e,t)})}onDragEnd(e,t){let n=this.props.conditionalFormats.findIndex(t=>t.id===e)-t;n!==0&&this.env.model.dispatch(`CHANGE_CONDITIONAL_FORMAT_PRIORITY`,{cfId:e,delta:n,sheetId:this.env.model.getters.getActiveSheetId()})}},jH=class extends t.Component{static template=`o-spreadsheet-ConditionalFormattingEditor`;static props={editedCf:Object,onCancel:Function,onExit:Function,isNewCf:Boolean};static components={SelectionInput:kk,IconPicker:EH,ColorPickerWidget:vV,ConditionalFormatPreviewList:AH,Section:q,RoundColorPicker:bk,StandaloneComposer:fk,BadgeSelection:AV,ValidationMessages:IB,SelectMenu:Nk};icons=cj;iconSets=lj;getTextDecoration=lv;colorNumberToHex=Sr;state;setup(){switch(this.state=(0,t.useState)({errors:[],currentCFType:this.props.editedCf.rule.type,ranges:this.props.editedCf.ranges,rules:this.getDefaultRules(),hasEditedCf:this.props.isNewCf}),this.props.editedCf.rule.type){case`CellIsRule`:this.state.rules.cellIs=this.props.editedCf.rule;break;case`ColorScaleRule`:this.state.rules.colorScale=this.props.editedCf.rule;break;case`IconSetRule`:this.state.rules.iconSet=this.props.editedCf.rule;break;case`DataBarRule`:this.state.rules.dataBar=this.props.editedCf.rule;break}(0,t.useExternalListener)(window,`click`,this.closeMenus)}get isRangeValid(){return this.state.errors.includes(`EmptyRange`)}get errorMessages(){return this.state.errors.map(e=>Jp.Errors[e]||Jp.Errors.Unexpected)}get cfTypesValues(){return[{value:`CellIsRule`,label:k(`Single color`)},{value:`ColorScaleRule`,label:k(`Color scale`)},{value:`IconSetRule`,label:k(`Icon set`)},{value:`DataBarRule`,label:k(`Data bar`)}]}updateConditionalFormat(e){let t=e.ranges||this.state.ranges;if(this.state.ranges.some(e=>!e.match(Oc)))return e.suppressErrors||(this.state.errors=[`InvalidRange`]),[`InvalidRange`];let n=this.env.model.getters.getActiveSheetId(),r=this.env.model.getters.getLocale(),i=e.rule||this.getEditedRule(this.state.currentCFType),a=this.env.model.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{rule:ty(i,r),id:this.props.editedCf.id},ranges:t.map(e=>this.env.model.getters.getRangeDataFromXc(n,e)),sheetId:n});a.isSuccessful&&(this.state.hasEditedCf=!0);let o=a.reasons.filter(e=>e!==`NoChanges`);return e.suppressErrors||(this.state.errors=o),o}getEditedRule(e){switch(e){case`CellIsRule`:return this.state.rules.cellIs;case`ColorScaleRule`:return this.state.rules.colorScale;case`IconSetRule`:return this.state.rules.iconSet;case`DataBarRule`:return this.state.rules.dataBar}}onSave(){this.updateConditionalFormat({}).length===0&&this.props.onExit()}onCancel(){this.state.hasEditedCf?this.props.onCancel():this.props.onExit()}getDefaultRules(){return{cellIs:{type:`CellIsRule`,operator:`isNotEmpty`,values:[],style:{fillColor:`#b6d7a8`}},colorScale:{type:`ColorScaleRule`,minimum:{type:`value`,color:qj(`EFF7FF`)},midpoint:void 0,maximum:{type:`value`,color:6989903}},iconSet:{type:`IconSetRule`,icons:{upper:`arrowGood`,middle:`arrowNeutral`,lower:`arrowBad`},upperInflectionPoint:{type:`percentage`,value:`66`,operator:`gt`},lowerInflectionPoint:{type:`percentage`,value:`33`,operator:`gt`}},dataBar:{type:`DataBarRule`,color:14281427}}}changeRuleType(e){this.state.currentCFType!==e&&(this.state.errors=[],this.state.currentCFType=e,this.updateConditionalFormat({rule:this.getEditedRule(e),suppressErrors:!0}))}onRangeUpdate(e){this.state.ranges=e}onRangeConfirmed(){this.updateConditionalFormat({ranges:this.state.ranges})}toggleMenu(e){let t=this.state.openedMenu===e;this.closeMenus(),t||(this.state.openedMenu=e)}closeMenus(){this.state.openedMenu=void 0}get isValue1Invalid(){return this.state.errors.includes(`FirstArgMissing`)||this.state.errors.includes(`ValueCellIsInvalidFormula`)}get isValue2Invalid(){return this.state.errors.includes(`SecondArgMissing`)}toggleStyle(e){let t=this.state.rules.cellIs.style;t[e]=!t[e],this.updateConditionalFormat({rule:this.state.rules.cellIs}),this.closeMenus()}onKeydown(e){if(e.key===`F4`){let t=e.target,n=ik({start:t.selectionStart??0,end:t.selectionEnd??0},t.value,this.env.model.getters.getLocale());if(!n)return;t.value=n.content,t.setSelectionRange(n.selection.start,n.selection.end),t.dispatchEvent(new Event(`input`))}}setColor(e,t){this.state.rules.cellIs.style[e]=t,this.updateConditionalFormat({rule:this.state.rules.cellIs}),this.closeMenus()}editOperator(e){this.state.rules.cellIs.operator=e,e.includes(`date`)&&!this.state.rules.cellIs.dateValue&&(this.state.rules.cellIs.dateValue=`exactDate`),this.updateConditionalFormat({rule:this.state.rules.cellIs,suppressErrors:!0}),this.closeMenus()}get cfCriterionMenuItems(){return Mk(e=>this.editOperator(e),Nm)}get selectedCriterionName(){return W.get(this.state.rules.cellIs.operator).name}get criterionComponent(){return J.get(this.state.rules.cellIs.operator).component}get genericCriterion(){return{type:this.state.rules.cellIs.operator,values:this.state.rules.cellIs.values,dateValue:this.state.rules.cellIs.dateValue}}onRuleValuesChanged(e){this.state.rules.cellIs.values=e.values,this.state.rules.cellIs.dateValue=e.dateValue,this.updateConditionalFormat({rule:{...this.state.rules.cellIs,values:e.values,dateValue:e.dateValue}})}isValueInvalid(e){switch(e){case`minimum`:return this.state.errors.includes(`MinInvalidFormula`)||this.state.errors.includes(`MinBiggerThanMid`)||this.state.errors.includes(`MinBiggerThanMax`)||this.state.errors.includes(`MinNaN`);case`midpoint`:return this.state.errors.includes(`MidInvalidFormula`)||this.state.errors.includes(`MidNaN`)||this.state.errors.includes(`MidBiggerThanMax`);case`maximum`:return this.state.errors.includes(`MaxInvalidFormula`)||this.state.errors.includes(`MaxNaN`);default:return!1}}setColorScaleColor(e,t){if(!Tr(t))return;let n=this.state.rules.colorScale[e];n&&(n.color=Cr(t)),this.updateConditionalFormat({rule:this.state.rules.colorScale}),this.closeMenus()}getColorScalePreviewStyle(){let e=this.state.rules.colorScale,t=Sr(e.minimum.color),n=Sr(e.midpoint?.color||11982760),r=Sr(e.maximum.color),i=`linear-gradient(to right, `;return U({"background-image":e.midpoint===void 0?i+t+`, `+r+`)`:i+t+`, `+n+`, `+r+`)`,color:`#000`})}getThresholdColor(e){return Sr(e?e.color:se)}onMidpointChange(e){let t=e.target.value,n=this.state.rules.colorScale;t===`none`?n.midpoint=void 0:n.midpoint={color:se,value:``,...n.midpoint,type:t},this.updateConditionalFormat({rule:n,suppressErrors:!0})}updateThresholdType(e,t){this.state.rules.colorScale[e].type=t,this.updateConditionalFormat({rule:this.state.rules.colorScale,suppressErrors:!0})}updateThresholdValue(e,t){this.state.rules.colorScale[e].value=t,this.updateConditionalFormat({rule:this.state.rules.colorScale})}isInflectionPointInvalid(e){switch(e){case`lowerInflectionPoint`:return this.state.errors.includes(`ValueLowerInflectionNaN`)||this.state.errors.includes(`ValueLowerInvalidFormula`)||this.state.errors.includes(`LowerBiggerThanUpper`);case`upperInflectionPoint`:return this.state.errors.includes(`ValueUpperInflectionNaN`)||this.state.errors.includes(`ValueUpperInvalidFormula`)||this.state.errors.includes(`LowerBiggerThanUpper`);default:return!0}}reverseIcons(){let e=this.state.rules.iconSet.icons,t=e.upper;e.upper=e.lower,e.lower=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setIconSet(e){let t=this.state.rules.iconSet.icons;t.upper=this.iconSets[e].good,t.middle=this.iconSets[e].neutral,t.lower=this.iconSets[e].bad,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setIcon(e,t){this.state.rules.iconSet.icons[e]=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setInflectionOperator(e,t){this.state.rules.iconSet[e].operator=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setInflectionValue(e,t){this.state.rules.iconSet[e].value=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setInflectionType(e,t,n){this.state.rules.iconSet[e].type=t,this.updateConditionalFormat({rule:this.state.rules.iconSet,suppressErrors:!0})}getColorScaleComposerProps(e){let t=this.state.rules.colorScale[e];if(!t)throw Error(`Threshold not found`);let n=this.isValueInvalid(e);return{onConfirm:e=>{t.value=e,this.updateConditionalFormat({rule:this.state.rules.colorScale})},composerContent:t.value||``,placeholder:k(`Formula`),defaultStatic:!0,invalid:n,class:`o-sidePanel-composer`,defaultRangeSheetId:this.env.model.getters.getActiveSheetId()}}getColorIconSetComposerProps(e){let t=this.state.rules.iconSet[e],n=this.isInflectionPointInvalid(e);return{onConfirm:e=>{t.value=e,this.updateConditionalFormat({rule:this.state.rules.iconSet})},composerContent:t.value||``,placeholder:k(`Formula`),defaultStatic:!0,invalid:n,class:`o-sidePanel-composer`,defaultRangeSheetId:this.env.model.getters.getActiveSheetId()}}getRangeValues(){return[this.state.rules.dataBar.rangeValues||``]}updateDataBarColor(e){Tr(e)&&(this.state.rules.dataBar.color=Number.parseInt(e.slice(1),16),this.updateConditionalFormat({rule:this.state.rules.dataBar}))}onDataBarRangeUpdate(e){this.state.rules.dataBar.rangeValues=e[0]}onDataBarRangeChange(){this.updateConditionalFormat({rule:this.state.rules.dataBar})}},MH=class extends t.Component{static template=`o-spreadsheet-ConditionalFormattingPanel`;static props={selection:{type:Object,optional:!0},onCloseSidePanel:Function};static components={ConditionalFormatPreviewList:AH,ConditionalFormattingEditor:jH,Section:q};activeSheetId;originalEditedCf=void 0;state=(0,t.useState)({mode:`list`});setup(){this.activeSheetId=this.env.model.getters.getActiveSheetId();let e=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getRulesSelection(e,this.props.selection||[]);if(n.length===1){let e=this.conditionalFormats.find(e=>e.id===n[0]);e&&this.editConditionalFormat(e)}(0,t.onWillUpdateProps)(e=>{let t=this.env.model.getters.getActiveSheetId();if(t!==this.activeSheetId)this.activeSheetId=t,this.switchToList();else if(e.selection!==this.props.selection){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getRulesSelection(t,e.selection||[]);if(n.length===1){let e=this.conditionalFormats.find(e=>e.id===n[0]);e&&this.editConditionalFormat(e)}else this.switchToList()}else this.editedCF||this.switchToList()})}get conditionalFormats(){return this.env.model.getters.getConditionalFormats(this.env.model.getters.getActiveSheetId()).map(e=>({...e,rule:ny(e.rule,this.env.model.getters.getLocale())}))}switchToList(){this.state.mode=`list`,this.state.editedCfId=void 0,this.originalEditedCf=void 0}addConditionalFormat(){let e=this.env.model.uuidGenerator.smallUuid();this.env.model.dispatch(`ADD_CONDITIONAL_FORMAT`,{sheetId:this.activeSheetId,ranges:this.env.model.getters.getSelectedZones().map(e=>this.env.model.getters.getRangeDataFromZone(this.activeSheetId,e)),cf:{id:e,rule:{type:`CellIsRule`,operator:`isNotEmpty`,style:{fillColor:`#b6d7a8`},values:[]}}}),this.state.editedCfId=e,this.state.mode=`edit`,this.originalEditedCf=void 0}editConditionalFormat(e){this.state.mode=`edit`,this.state.editedCfId=e.id,this.originalEditedCf=e}cancelEdition(){this.originalEditedCf?this.env.model.dispatch(`ADD_CONDITIONAL_FORMAT`,{sheetId:this.activeSheetId,ranges:this.originalEditedCf.ranges.map(e=>this.env.model.getters.getRangeDataFromXc(this.activeSheetId,e)),cf:this.originalEditedCf}):this.state.editedCfId&&this.env.model.dispatch(`REMOVE_CONDITIONAL_FORMAT`,{sheetId:this.activeSheetId,id:this.state.editedCfId}),this.switchToList()}get editedCF(){return this.conditionalFormats.find(e=>e.id===this.state.editedCfId)}},NH=class extends t.Component{static template=`o-spreadsheet-DataValidationEditor`;static components={SelectionInput:kk,SelectMenu:Nk,Section:q,ValidationMessages:IB};static props={rule:{type:Object,optional:!0},onExit:Function,onCloseSidePanel:{type:Function,optional:!0}};state=(0,t.useState)({rule:this.defaultDataValidationRule,errors:[],isTypeUpdated:!1});editingSheetId;setup(){this.editingSheetId=this.env.model.getters.getActiveSheetId(),this.props.rule&&(this.state.rule={...this.props.rule,ranges:this.props.rule.ranges.map(e=>this.env.model.getters.getRangeString(e,this.editingSheetId))},this.state.rule.criterion.type=this.props.rule.criterion.type)}onCriterionTypeChanged(e){this.state.rule.criterion.type=e,this.state.isTypeUpdated=!0}onRangesChanged(e){this.state.rule.ranges=e}onCriterionChanged(e){this.state.rule.criterion=e}changeRuleIsBlocking(e){let t=e.target.value;this.state.rule.isBlocking=t===`true`}onSave(){if(this.state.rule){let e=this.env.model.dispatch(`ADD_DATA_VALIDATION_RULE`,this.dispatchPayload);e.isSuccessful?this.props.onExit():this.state.errors=e.reasons}}get dispatchPayload(){let e={...this.state.rule,ranges:void 0},t=this.env.model.getters.getLocale(),n=e.criterion,r=W.get(n.type),i=n.values.slice(0,r.numberOfValues(n)).filter(e=>e&&e.trim()!==``).map(e=>Gv(e,t));return e.criterion={...n,values:i},{sheetId:this.editingSheetId,ranges:this.state.rule.ranges.map(e=>this.env.model.getters.getRangeDataFromXc(this.editingSheetId,e)),rule:e}}get dvCriterionMenuItems(){return Mk(e=>this.onCriterionTypeChanged(e),Pm)}get selectedCriterionName(){let e=this.state.rule.criterion.type;return W.get(e).name}get defaultDataValidationRule(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones().map(t=>hn(this.env.model.getters.getUnboundedZone(e,t)));return{id:this.env.model.uuidGenerator.smallUuid(),criterion:{type:`containsText`,values:[``]},ranges:t}}get criterionComponent(){return J.get(this.state.rule.criterion.type).component}get errorMessages(){return this.state.errors.map(e=>H.Errors[e]||H.Errors.Unexpected)}},PH=class extends t.Component{static template=`o-spreadsheet-DataValidationPreview`;static props={onClick:Function,rule:Object};ref=(0,t.useRef)(`dvPreview`);setup(){DH(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=>({range:e,color:ee,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 W.get(this.props.rule.criterion.type).getPreview(this.props.rule.criterion,this.env.model.getters)}},FH=class extends t.Component{static template=`o-spreadsheet-DataValidationPanel`;static props={onCloseSidePanel:Function};static components={DataValidationPreview:PH,DataValidationEditor:NH};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&&ry(e,this.env.model.getters.getLocale())}get validationRules(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getDataValidationRules(e)}};let IH=`#8B008B`;var LH=class extends hr{mutators=[`updateSearchOptions`,`updateSearchContent`,`searchFormulas`,`selectPreviousMatch`,`selectNextMatch`,`replace`];allSheetsMatches=[];activeSheetMatches=[];specificRangeMatches=[];currentSearchRegex=null;initialShowFormulaState;preserveSelectedMatchIndex=!1;irreplaceableMatchCount=0;isSearchDirty=!1;shouldFinalizeUpdateSelection=!1;notificationStore=this.get(ck);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(sk);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,{jumpToMatchSheet:!0,updateSelection:!0})}selectNextMatch(){this.selectNextCell(1,{jumpToMatchSheet:!0,updateSelection:!0})}handle(e){switch(e.type){case`SET_FORMULA_VISIBILITY`:this.updateSearchOptions({searchFormulas:e.show});break;case`UNDO`:case`REDO`:case`REMOVE_TABLE`:case`UPDATE_FILTER`:case`REMOVE_COLUMNS_ROWS`:case`HIDE_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`ADD_COLUMNS_ROWS`:case`EVALUATE_CELLS`:case`UPDATE_CELL`:this.isSearchDirty=!0;break;case`ACTIVATE_SHEET`:this.isSearchDirty=!0,this.shouldFinalizeUpdateSelection=!0,this.searchOptions.specificRange&&(this.searchOptions.specificRange={...this.searchOptions.specificRange,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({jumpToMatchSheet:!1,updateSelection:this.shouldFinalizeUpdateSelection}),this.shouldFinalizeUpdateSelection=!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=Nt(this.toSearch,this.searchOptions),this.refreshSearch({jumpToMatchSheet:!0,updateSelection:!0})}refreshSearch(e){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&&En(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){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.jumpToMatchSheet&&this.getters.getActiveSheetId()!==i.sheetId&&(this.preserveSelectedMatchIndex=!0,this.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:i.sheetId}),this.preserveSelectedMatchIndex=!1,this.isSearchDirty=!1),this.model.selection.getBackToDefault(),t.updateSelection&&this.model.selection.selectCell(i.col,i.row)}replace(){this.selectedMatchIndex!==null&&(this.preserveSelectedMatchIndex=!0,this.shouldFinalizeUpdateSelection=!0,this.model.dispatch(`REPLACE_SEARCH`,{searchString:this.toSearch,replaceWith:this.toReplace,matches:[this.searchMatches[this.selectedMatchIndex]],searchOptions:this.searchOptions}),this.preserveSelectedMatchIndex=!1)}replaceAll(){this.model.dispatch(`REPLACE_SEARCH`,{searchString:this.toSearch,replaceWith:this.toReplace,matches:this.searchMatches,searchOptions:this.searchOptions})}showReplaceWarningMessage(e,t){let n=e-t;n===0?this.notificationStore.notifyUser({type:`warning`,sticky:!1,text:k(`Match(es) cannot be replaced as they are part of a formula.`)}):this.notificationStore.notifyUser({type:`warning`,sticky:!1,text:k(`%(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=Nt(t,r),o=new RegExp(a.source,a.flags+`g`),s=Wv(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=E(r),a=this.getters.expandZone(t,i),{width:o,height:s}=this.getters.getVisibleRect(a);o>0&&s>0&&e.push({range:this.model.getters.getRangeFromZone(t,a),color:IH,noBorder:n!==this.selectedMatchIndex,thinLine:!0,fillAlpha:.2})}if(this.searchOptions.searchScope===`specificRange`){let n=this.searchOptions.specificRange;n&&n.sheetId===t&&e.push({range:n,color:IH,noFill:!0,thinLine:!0})}return e}},RH=class extends t.Component{static template=`o-spreadsheet-FindAndReplacePanel`;static components={SelectionInput:kk,Section:q,Checkbox:Fk,ValidationMessages:IB};static props={onCloseSidePanel:Function};searchInput=(0,t.useRef)(`searchInput`);store;state;updateSearchContent;get hasSearchResult(){return this.store.selectedMatchIndex!==null}get searchOptions(){return this.store.searchOptions}get allSheetsMatchesCount(){return k(`%s matches in all sheets`,this.store.allSheetMatchesCount)}get currentSheetMatchesCount(){return k(`%(matches)s matches in %(sheetName)s`,{matches:this.store.activeSheetMatchesCount,sheetName:this.env.model.getters.getSheetName(this.env.model.getters.getActiveSheetId())})}get specificRangeMatchesCount(){let e=this.searchOptions.specificRange;if(!e)return``;let{sheetId:t,zone:n}=e;return k(`%(matches)s matches in range %(range)s of %(sheetName)s`,{matches:this.store.specificRangeMatchesCount,range:hn(n),sheetName:this.env.model.getters.getSheetName(t)})}get searchInfo(){return this.store.toSearch?[this.specificRangeMatchesCount,this.currentSheetMatchesCount,this.allSheetsMatchesCount]:[]}setup(){this.store=or(LH),this.state=(0,t.useState)({dataRange:``}),(0,t.onMounted)(()=>this.searchInput.el?.focus()),(0,t.onWillUnmount)(()=>this.updateSearchContent.stopDebounce()),this.updateSearchContent=dt(this.store.updateSearchContent,200),(0,t.useExternalListener)(window,`keydown`,e=>{let t=cp(e);(t===`Ctrl+F`||t===`Ctrl+H`)&&(this.searchInput.el?.focus(),e.preventDefault(),e.stopPropagation())},{capture:!0})}onFocusSearch(){this.updateDataRange()}onSearchInput(e){this.updateSearchContent(e.target.value)}onKeydownSearch(e){e.key===`Enter`&&(e.preventDefault(),e.stopPropagation(),e.shiftKey?this.store.selectPreviousMatch():this.store.selectNextMatch())}onKeydownReplace(e){e.key===`Enter`&&(e.preventDefault(),e.stopPropagation(),this.store.replace())}searchFormulas(e){this.store.searchFormulas(e)}searchExactMatch(e){this.store.updateSearchOptions({exactMatch:e})}searchMatchCase(e){this.store.updateSearchOptions({matchCase:e})}changeSearchScope(e){let t=e.target.value;this.store.updateSearchOptions({searchScope:t})}onSearchRangeChanged(e){this.state.dataRange=e[0]}updateDataRange(){if(!this.state.dataRange||this.searchOptions.searchScope!==`specificRange`)return;let e=this.env.model.getters.getRangeFromSheetXC(this.env.model.getters.getActiveSheetId(),this.state.dataRange);this.store.updateSearchOptions({specificRange:e})}get specificRange(){let e=this.store.searchOptions.specificRange;return e?this.env.model.getters.getRangeString(e,`forceSheetReference`):``}get pendingSearch(){return this.updateSearchContent.isDebouncePending()}get selectionInputKey(){return this.env.model.getters.getActiveSheetId()}};let zH=new B,BH={name:Xp.Custom,code:``,symbol:``,decimalPlaces:2,position:`after`};var VH=class extends hr{mutators=[`updateFormat`,`changeCategory`,`selectCurrency`,`changeCurrencyCode`,`changeCurrencySymbol`,`updateAvailableCurrencies`];invalidFormat=!1;isApplyingFormatFromPanel=!1;currentFormat=this.formatInSelection;category=this.detectFormatCategory(this.formatInSelection);selectedCurrencyIndex=0;currencyCode=``;currencySymbol=``;isAccountingFormat=!1;availableCurrencies=[BH,...zH.getAll()];lastFormatInSelection=this.currentFormat;usedFormatForCategory={};constructor(e,t){super(e),t&&(this.category=t),this.model.selection.observe(this,{handleEvent:this.handleSelectionEvent.bind(this)}),this.onDispose(()=>{this.model.selection.unobserve(this)})}handle(){this.isApplyingFormatFromPanel||this.syncActiveFormat()}handleSelectionEvent(){this.getters.isGridSelectionActive()&&this.syncActiveFormat()}syncActiveFormat(){let e=this.formatInSelection;e!==this.lastFormatInSelection&&(this.setActiveFormat(e),this.lastFormatInSelection=e)}setActiveFormat(e){this.currentFormat=e,this.invalidFormat=!Es(e||``),this.category=this.detectFormatCategory(e)}get categories(){return[{label:k(`Number`),value:`number`},{label:k(`Date`),value:`date`},{label:k(`Currency`),value:`currency`}]}get formatInSelection(){let e=this.getters.getActivePosition();return this.getters.getPivotCellFromPosition(e).type===`VALUE`?this.getters.getEvaluatedCell(e).format:this.getters.getCell(e)?.format}detectFormatCategory(e){return e?ns(e)?`date`:e.includes(`$`)||e.includes(`"`)?`currency`:`number`:`number`}get formatProposals(){return this.category===`date`?this.dateFormatProposals:this.category===`currency`?this.currencyFormatProposals:this.category===`number`?this.numberFormatProposals:[]}get numberFormatProposals(){let e=[`0.00`,`0`,`#,##0`,`#,##0.00`,`0%`,`0.00%`,`0.00e`,`0.00;(0.00);-`].map(e=>({label:z(-1234.56,{format:e,locale:this.getters.getLocale()}),format:e}));return[{label:k(`Automatic`),format:void 0},{label:k(`Plain text`),format:`@`},...e]}get dateFormatProposals(){let e=this.getters.getLocale();return[e.dateFormat,e.timeFormat,e.dateFormat+` `+e.timeFormat,`dddd d mmmm yyyy hh:mm:ss a`,`yyyy-mm-dd`,`yyyy-mm-dd hh:mm:ss`,`dddd d mmmm yyyy`,`d mmmm yyyy`,`ddd d mmm yyyy`,`d mmm yyyy`,`mmmm yyyy`,`mmm yyyy`,`hhhh:mm:ss`,`qq yyyy`,`qqqq yyyy`].map(t=>({label:z(WR,{format:t,locale:e}),format:t}))}get currencyFormatProposals(){let e=this.availableCurrencies[this.selectedCurrencyIndex],t=e.position,n=e.position===`before`?`after`:`before`,r=this.currencySymbol.trim()?this.currencySymbol:``,i=this.currencyCode.trim()?this.currencyCode:``,a=e.decimalPlaces;if(!r&&!i)return[];let o=[{symbol:r,position:t,decimalPlaces:0},{symbol:r,position:t,decimalPlaces:a},{symbol:r,position:t,decimalPlaces:0,code:i},{symbol:r,position:t,decimalPlaces:a,code:i},{symbol:r,position:n,decimalPlaces:0},{symbol:r,position:n,decimalPlaces:a},{symbol:r,position:n,decimalPlaces:0,code:i},{symbol:r,position:n,decimalPlaces:a,code:i}],s=new Set,c=this.getters.getLocale();return o.map(e=>{let t=this.isAccountingFormat?us(e):ls(e);if(!(!e.symbol&&!e.code||s.has(t)))return s.add(t),{format:t,label:z(1e3,{format:t,locale:c})}}).filter(C)}get formatExamples(){let e=this.currentFormat,t=this.getters.getLocale();if(!e||!Es(e))return[];if(this.category===`date`)return[{label:k(`Sample:`),value:z(WR,{format:e,locale:t})}];{let n=Ds(e),r=[{label:k(`Positive:`),value:z(1234.56,{format:e,locale:t})},{label:k(`Negative:`),value:z(-1234.56,{format:e,locale:t})},{label:k(`Zero:`),value:z(0,{format:e,locale:t})}];return n===4&&r.push({label:k(`Text:`),value:z(`Text`,{format:e,locale:t})}),r}}updateAvailableCurrencies(){this.availableCurrencies=[BH,...zH.getAll()]}updateFormat(e){this.currentFormat=e,this.invalidFormat=!Es(e),this.invalidFormat||(this.lastFormatInSelection=e,this.isApplyingFormatFromPanel=!0,this.model.dispatch(`SET_FORMATTING_WITH_PIVOT`,{sheetId:this.getters.getActiveSheetId(),target:this.getters.getSelectedZones(),format:e||``}),this.isApplyingFormatFromPanel=!1)}changeCategory(e){if(e===this.category)return`noStateChange`;this.usedFormatForCategory[this.category]=this.currentFormat,this.category=e;let t=this.usedFormatForCategory[e]||this.formatProposals[0]?.format||``;this.updateFormat(t)}selectCurrency(e){let t=this.formatProposals.findIndex(e=>e.format===this.currentFormat);this.selectedCurrencyIndex=e;let n=this.availableCurrencies[e];this.currencyCode=n.code,this.currencySymbol=n.symbol,this.updateFormat(this.formatProposals[t]?.format||this.formatProposals[0]?.format||``)}changeCurrencyCode(e){let t=this.formatProposals.findIndex(e=>e.format===this.currentFormat);this.currencyCode=e,this.selectedCurrencyIndex=0,this.updateFormat(this.formatProposals[t]?.format||this.formatProposals[0]?.format||``)}changeCurrencySymbol(e){let t=this.formatProposals.findIndex(e=>e.format===this.currentFormat);this.currencySymbol=e,this.selectedCurrencyIndex=0,this.updateFormat(this.formatProposals[t]?.format||this.formatProposals[0]?.format||``)}toggleAccountingFormat(){let e=this.formatProposals.findIndex(e=>e.format===this.currentFormat);this.isAccountingFormat=!this.isAccountingFormat,this.updateFormat(this.formatProposals[e]?.format||this.formatProposals[0]?.format||``)}get invalidFormatMessage(){return this.invalidFormat?k(`The format entered is not valid.`):void 0}},HH=class extends t.Component{static template=`o-spreadsheet-MoreFormatsPanel`;static props={onCloseSidePanel:Function,category:{type:String,optional:!0}};static components={BadgeSelection:AV,Section:q,TextInput:gV,Checkbox:Fk};store;setup(){this.store=or(VH,this.props.category),(0,t.onWillStart)(()=>this.loadCurrencies()),(0,t.onWillUpdateProps)(e=>{e.category&&e.category!==this.props.category&&this.store.changeCategory(e.category)})}async loadCurrencies(){zH.getAll().length===0&&((await(this.env.loadCurrencies?.()??Promise.resolve([]))).forEach((e,t)=>{zH.replace(t.toString(),e)}),this.store.updateAvailableCurrencies())}currencyDisplayName(e){return e.name+(e.code?` (${e.code})`:``)}updateSelectCurrency(e){let t=e.target,n=parseInt(t.value,10);this.store.selectCurrency(n)}isFormatSelected(e){return e===this.store.currentFormat}},UH=class extends hr{pivotId;initialMeasure;mutators=[`cancelMeasureDisplayEdition`,`updateMeasureDisplayType`,`updateMeasureDisplayField`,`updateMeasureDisplayValue`];measureDisplay;constructor(e,t,n){super(e),this.pivotId=t,this.initialMeasure=n,this.measureDisplay=n.display||{type:`no_calculations`}}updateMeasureDisplayType(e){this.updatePivotMeasureDisplay(this.getMeasureDisplay(e,this.measureDisplay.fieldNameWithGranularity,this.measureDisplay.value))}updateMeasureDisplayField(e){this.updatePivotMeasureDisplay(this.getMeasureDisplay(this.measureDisplay.type,e,this.measureDisplay.value))}updateMeasureDisplayValue(e){this.updatePivotMeasureDisplay(this.getMeasureDisplay(this.measureDisplay.type,this.measureDisplay.fieldNameWithGranularity,e))}updatePivotMeasureDisplay(e){let t=b(this.model.getters.getPivotCoreDefinition(this.pivotId)),n=this.getMeasureIndex(this.initialMeasure.id,t),r={...t.measures[n],display:e};t.measures[n]=r,this.model.dispatch(`UPDATE_PIVOT`,{pivot:t,pivotId:this.pivotId}).isSuccessful&&(this.measureDisplay=e)}getMeasureDisplay(e,t,n){switch(e){case`no_calculations`:case`%_of_grand_total`:case`%_of_col_total`:case`%_of_row_total`:case`%_of_parent_row_total`:case`%_of_parent_col_total`:case`index`:return{type:e};case`%_of_parent_total`:case`running_total`:case`%_running_total`:case`rank_asc`:case`rank_desc`:return t||=this.fields[0]?.nameWithGranularity,{type:e,fieldNameWithGranularity:t};case`%_of`:case`difference_from`:case`%_difference_from`:t||=this.fields[0]?.nameWithGranularity;let r=this.getPossibleValues(t);return(n===void 0||!r.find(e=>e.value===n))&&(n=Fm),{type:e,fieldNameWithGranularity:t,value:n??`(previous)`}}}getMeasureIndex(e,t){let n=t.measures.findIndex(t=>t.id===e);if(n===-1)throw Error(`Measure with id ${e} not found in pivot.`);return n}get doesDisplayNeedsField(){return[`%_of_parent_total`,`running_total`,`%_running_total`,`rank_asc`,`rank_desc`].includes(this.measureDisplay.type)||this.doesDisplayNeedsValue}get fields(){let e=this.getters.getPivot(this.pivotId).definition;return[...e.columns,...e.rows].map(e=>({...e,displayName:Ch(e)}))}get doesDisplayNeedsValue(){return this.isDisplayValueDependant(this.measureDisplay)}isDisplayValueDependant(e){return[`%_of`,`difference_from`,`%_difference_from`].includes(e.type)}get values(){let e=this.measureDisplay;return this.isDisplayValueDependant(e)?this.getPossibleValues(e.fieldNameWithGranularity):[]}getPossibleValues(e){let t=[{value:Fm,label:k(`(previous)`)},{value:`(next)`,label:k(`(next)`)}],n=this.fields.find(t=>t.nameWithGranularity===e);if(!n)return[];let r=this.getters.getPivot(this.pivotId).getPossibleFieldValues(n);return[...t,...r]}cancelMeasureDisplayEdition(){let e=b(this.model.getters.getPivotCoreDefinition(this.pivotId)),t=this.getMeasureIndex(this.initialMeasure.id,e);e.measures[t]={...e.measures[t],display:this.initialMeasure.display},this.model.dispatch(`UPDATE_PIVOT`,{pivot:e,pivotId:this.pivotId})}},WH=class extends t.Component{static template=`o-spreadsheet-PivotMeasureDisplayPanel`;static props={onCloseSidePanel:Function,pivotId:String,measure:Object};static components={Section:q,Checkbox:Fk,RadioSelection:NV};measureDisplayTypeLabels=nm.labels;measureDisplayDescription=nm.documentation;store;setup(){this.store=or(UH,this.props.pivotId,this.props.measure)}onSave(){this.env.replaceSidePanel(`PivotSidePanel`,`pivot_measure_display_${this.props.pivotId}_${this.props.measure.id}`,{pivotId:this.props.pivotId})}onCancel(){this.store.cancelMeasureDisplayEdition(),this.env.replaceSidePanel(`PivotSidePanel`,`pivot_measure_display_${this.props.pivotId}_${this.props.measure.id}`,{pivotId:this.props.pivotId})}get fieldChoices(){return this.store.fields.map(e=>({value:e.nameWithGranularity,label:e.displayName}))}};function GH(e,t){let n=e.getActiveSheetId();return Xn(KH(e,t).map(E)).map(t=>({range:e.getRangeFromZone(n,t),noFill:!0,color:ee}))}function KH(e,t){let n=[],r=e.getActiveSheetId();for(let i of e.getSheetViewVisibleCols())for(let a of e.getSheetViewVisibleRows()){let o={sheetId:r,col:i,row:a};e.getPivotIdsFromPosition(o).includes(t)&&n.push(o)}return n}var qH=class extends t.Component{static template=`o-spreadsheet-PivotDeferUpdate`;static props={deferUpdate:Boolean,isDirty:Boolean,toggleDeferUpdate:Function,discard:Function,apply:Function};static components={Section:q,Checkbox:Fk};get deferUpdatesLabel(){return k(`Defer updates`)}get deferUpdatesTooltip(){return k(`Changing the pivot definition requires to reload the data. It may take some time.`)}},JH=class extends t.Component{static template=`o-spreadsheet-PivotCustomGroupsCollapsible`;static props={pivotId:String,customField:Object,onCustomFieldUpdated:Function};static components={SidePanelCollapsible:Vv,TextInput:gV,Checkbox:Fk};get groups(){return this.props.customField.groups.sort((e,t)=>!e.isOtherGroup&&!t.isOtherGroup?0:e.isOtherGroup?1:-1)}get hasOthersGroup(){return this.props.customField.groups.some(e=>e.isOtherGroup)}addOthersGroup(){if(this.hasOthersGroup)return;let e={name:Eh(k(`Others`),this.props.customField),values:[],isOtherGroup:!0},t=[...this.props.customField.groups,e];this.updateCustomField({...this.props.customField,groups:t})}onDeleteGroup(e){let t=[...this.props.customField.groups];t.splice(e,1),this.updateCustomField({...this.props.customField,groups:t})}onRenameGroup(e,t){let n=b(this.props.customField.groups),r=n[e];r&&(r.name=Eh(t,this.props.customField),this.updateCustomField({...this.props.customField,groups:n}))}updateCustomField(e){let t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);this.props.onCustomFieldUpdated({customFields:{...t.customFields,[e.name]:e}})}};function YH(e,t,n,r){let i=[];e=e.toLowerCase();for(let a of e){let e=t.toLocaleLowerCase().indexOf(a);e!==-1&&(i.push({value:t.slice(0,e),color:``},{value:t[e],color:n,classes:[r]}),t=t.slice(e+1))}return i.push({value:t}),i.filter(e=>e.value)}var XH=class extends t.Component{static template=`o-spreadsheet-AddDimensionButton`;static components={Popover:Cv,TextValueProvider:wO};static props={onFieldPicked:Function,fields:Array,slots:{type:Object,optional:!0}};buttonRef=(0,t.useRef)(`button`);popover=(0,t.useState)({isOpen:!1});search=(0,t.useState)({input:``});autoComplete;setup(){this.autoComplete=or(lk),this.autoComplete.useProvider(this.getProvider()),(0,t.useExternalListener)(window,`click`,e=>{e.target!==this.buttonRef.el&&(this.popover.isOpen=!1)}),mV({refName:`autofocus`})}getProvider(){return{proposals:this.proposals,autoSelectFirstProposal:!1,selectProposal:e=>{let t=this.props.fields.find(t=>t.string===e);t&&this.pickField(t)}}}get proposals(){let e;return e=this.search.input?fl(this.search.input,this.props.fields,e=>e.string===e.name?e.string:e.string+e.name):this.props.fields,e.map(e=>{let t=e.string;return{text:t,fuzzySearchKey:t,htmlContent:YH(this.search.input,t,le,`o-semi-bold`)}})}get popoverProps(){let{x:e,y:t,width:n,height:r}=this.buttonRef.el.getBoundingClientRect();return{anchorRect:{x:e,y:t,width:n,height:r},positioning:`bottom-left`}}updateSearch(e){this.search.input=e,this.autoComplete.useProvider(this.getProvider())}pickField(e){this.props.onFieldPicked(e.name),this.togglePopover()}togglePopover(){this.popover.isOpen=!this.popover.isOpen,this.search.input=``,this.autoComplete.useProvider(this.getProvider())}onKeyDown(e){switch(e.key){case`Enter`:let t=this.autoComplete.provider?.proposals;t?.length===1&&this.autoComplete.provider?.selectProposal(t[0].text||``);let n=this.autoComplete.selectedProposal;this.autoComplete.provider?.selectProposal(n?.text||``);break;case`ArrowUp`:case`ArrowDown`:this.autoComplete.moveSelection(e.key===`ArrowDown`?`next`:`previous`);break;case`Escape`:this.popover.isOpen=!1;break;default:break}}},ZH=class extends t.Component{static template=`o-spreadsheet-PivotDimension`;static props={dimension:Object,onRemoved:{type:Function,optional:!0},onNameUpdated:{type:Function,optional:!0},slots:{type:Object,optional:!0}};static components={CogWheelMenu:SV,TextInput:gV};updateName(e){this.props.onNameUpdated?.(this.props.dimension,e===``||e.startsWith(`=`)?void 0:e)}get dimensionDisplayName(){let e=this.props.dimension.displayName;return Ph(e)}},QH=class extends t.Component{static template=`o-spreadsheet-PivotDimensionGranularity`;static props={dimension:Object,onUpdated:Function,availableGranularities:Set,allGranularities:Array};periods=uh},$H=class extends t.Component{static template=`o-spreadsheet-PivotDimensionOrder`;static props={dimension:Object,onUpdated:Function}},eU=class{scope;code=``;constructor(e=new nU){this.scope=e}append(...e){this.code+=e.map(e=>e.toString()).join(`
|
|
112
112
|
`)+`
|
|
113
113
|
`}return(e){return new tU(this.scope,this.code,e)}toString(){return iU(this.code)}},tU=class{scope;returnExpression;code;constructor(e,t,n){this.scope=e,this.returnExpression=n,this.code=iU(t)}toString(){return this.code}assignResultToVariable(){if(this.scope.isAlreadyDeclared(this.returnExpression))return this;let e=this.scope.nextVariableName(),t=new eU(this.scope);return t.append(this.code),t.append(`const ${e} = ${this.returnExpression};`),t.return(e)}},nU=class{nextId=1;declaredVariables=new Set;nextVariableName(){let e=`_${this.nextId++}`;return this.declaredVariables.add(e),e}isAlreadyDeclared(e){return this.declaredVariables.has(e)}};function rU(e){return e.split(`
|
|
114
114
|
`).map(e=>e.trim()).filter(e=>e!==``)}function iU(e){let t=``,n=0,r=rU(e);for(let e of r)e.startsWith(`}`)&&n--,t+=` `.repeat(n)+e+`
|
|
115
|
-
`,e.endsWith(`{`)&&n++;return t.trim()}let aU=yO.content,oU={"=":`EQ`,"+":`ADD`,"-":`MINUS`,"*":`MULTIPLY`,"/":`DIVIDE`,">=":`GTE`,"<>":`NE`,">":`GT`,"<=":`LTE`,"<":`LT`,"^":`POWER`,"&":`CONCATENATE`},sU={"-":`UMINUS`,"+":`UPLUS`,"%":`UNARY.PERCENT`},cU={};function lU(e){return uU(Uu(e))}function uU(e){try{return dU(e)}catch(t){return{tokens:e,dependencies:[],execute:function(){return t},isBadExpression:!0,normalizedFormula:e.map(e=>e.value).join(``)}}}function dU(e){let{dependencies:t,literalValues:n,symbols:r}=pU(e),i=fU(e);if(!cU[i]){let t=qO([...e]),n=new nU,s=0,c=0,l=0;if(t.type===`BIN_OPERATION`&&t.value===`:`||t.type===`EMPTY`)throw new fa(k(`Invalid formula`));let u=o(t),d=new eU;d.append(u),d.append(`return ${u.returnExpression};`),cU[i]=Function(`deps`,`ref`,`range`,`getSymbolValue`,`ctx`,d.toString());function a(e){let{args:t}=e,n=aU[e.value.toUpperCase()];if(!n)throw new ga(k(`Unknown function: "%s"`,e.value));mU(e);let r=[],i=_y(n,t.length);for(let e=0;e<t.length;e++){let a=n.args[i(e).index??-1],s=t[e],c=a.type||[],l=c.includes(`META`)||c.includes(`RANGE<META>`),u=c.some(e=>hU(e));r.push(o(s,l,u))}return r}function o(e,t=!1,i=!1){let u=new eU(n);if(e.type!==`REFERENCE`&&!(e.type===`BIN_OPERATION`&&e.value===`:`)&&t)throw new fa(k(`Argument must be a reference to a cell or range.`));switch(e.debug&&(u.append(`debugger;`),u.append(`ctx["debug"] = true;`)),e.type){case`BOOLEAN`:return u.return(`{ value: ${e.value} }`);case`NUMBER`:return u.return(`this.literalValues.numbers[${c++}]`);case`STRING`:return u.return(`this.literalValues.strings[${s++}]`);case`REFERENCE`:return u.return(`${e.value.includes(`:`)||i?`range`:`ref`}(deps[${l++}], ${t?`true`:`false`})`);case`FUNCALL`:let n=a(e).map(e=>e.assignResultToVariable());u.append(...n);let d=e.value.toUpperCase();return u.return(`ctx['${d}'](${n.map(e=>e.returnExpression)})`);case`ARRAY`:return o({type:`FUNCALL`,value:`ARRAY.LITERAL`,args:e.value.map(e=>({type:`FUNCALL`,value:`ARRAY.ROW`,args:e,tokenStartIndex:0,tokenEndIndex:0})),tokenStartIndex:0,tokenEndIndex:0});case`UNARY_OPERATION`:{let t=sU[e.value],n=o(e.operand,!1,!1).assignResultToVariable();return u.append(n),u.return(`ctx['${t}'](${n.returnExpression})`)}case`BIN_OPERATION`:{let t=oU[e.value],n=o(e.left,!1,!1).assignResultToVariable(),r=o(e.right,!1,!1).assignResultToVariable();return u.append(n),u.append(r),u.return(`ctx['${t}'](${n.returnExpression}, ${r.returnExpression})`)}case`SYMBOL`:let f=r.indexOf(e.value);return u.return(`getSymbolValue(this.symbols[${f}])`);case`EMPTY`:return u.return(`undefined`)}}}return{execute:cU[i],dependencies:t,literalValues:n,symbols:r,tokens:e,isBadExpression:!1,normalizedFormula:i}}function fU(e){let t=``;for(let n of e)switch(n.type){case`STRING`:t+=`|S|`;break;case`NUMBER`:t+=`|N|`;break;case`REFERENCE`:case`INVALID_REFERENCE`:n.value.includes(`:`)?t+=`|R|`:t+=`|C|`;break;case`SPACE`:break;default:t+=n.value;break}return t}function pU(e){let t={numbers:[],strings:[]},n=[],r=[];for(let i of e)switch(i.type){case`INVALID_REFERENCE`:case`REFERENCE`:n.push(i.value);break;case`STRING`:let e=Je(i.value);t.strings.push({value:e});break;case`NUMBER`:{let e=ta(i.value,R);t.numbers.push({value:e});break}case`SYMBOL`:r.push(Je(i.value,`'`))}return{dependencies:n,literalValues:t,symbols:r}}function mU(e){let t=e.args.length,n=e.value.toUpperCase(),r=aU[n],{nbrArgRepeating:i,minArgRequired:a}=r;if(t<a)throw new fa(k(`Invalid number of arguments for the %(functionName)s function. Expected %(minArgRequired)s minimum, but got %(nbrArgSupplied)s instead.`,{functionName:n,minArgRequired:a,nbrArgSupplied:t}));if(t>r.maxArgPossible)throw new fa(k(`Invalid number of arguments for the %(functionName)s function. Expected %(maxArgPossible)s maximum, but got %(nbrArgSupplied)s instead.`,{functionName:n,maxArgPossible:r.maxArgPossible,nbrArgSupplied:t}));if(i>1){let e=i*Math.floor((t-a)/i),o=t-a-e-r.nbrOptionalNonRepeatingArgs;if(o>0)throw new fa(k(`Invalid number of arguments for the %(functionName)s function. Repeatable arguments should be supplied in groups of %(nbrArgRepeating)s, with up to %(nbrArgOptional)s optional. Got %(nbrValueRemaining)s too many.`,{functionName:n,nbrArgRepeating:i,nbrArgOptional:r.nbrOptionalNonRepeatingArgs,nbrValueRemaining:o}))}}function hU(e){return e.startsWith(`RANGE`)}function gU(e,t){return{sequence:0,autoSelectFirstProposal:!0,getProposals(n){let r=e.measures.filter(e=>e!==t).map(e=>{let t=Ye(e.id);return{text:t,description:e.displayName,htmlContent:[{value:t,color:ge}],fuzzySearchKey:e.displayName+t+e.fieldName}}),i=e.rows.concat(e.columns).map(e=>{let t=Ye(e.nameWithGranularity);return{text:t,description:e.displayName,htmlContent:[{value:t,color:ge}],fuzzySearchKey:e.displayName+t+e.fieldName}});return r.concat(i)},selectProposal(e,t){let n=e.end;e.type===`SYMBOL`&&(n=e.start);let r=e.end;this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t)}}}var _U=class extends t.Component{static template=`o-spreadsheet-PivotMeasureEditor`;static components={PivotDimension:ZH,StandaloneComposer:fk};static props={definition:Object,measure:Object,onMeasureUpdated:Function,onRemoved:Function,generateMeasureId:Function,aggregators:Object,pivotId:String};getMeasureAutocomplete(){return gU(this.props.definition,this.props.measure)}updateMeasureFormula(e){this.props.onMeasureUpdated({...this.props.measure,computedBy:{sheetId:this.env.model.getters.getActiveSheetId(),formula:e[0]===`=`?e:`=`+e}})}updateAggregator(e){this.props.onMeasureUpdated({...this.props.measure,aggregator:e,id:this.props.generateMeasureId(this.props.measure.fieldName,e)})}updateName(e,t){this.props.measure.computedBy&&t?this.props.onMeasureUpdated({...this.props.measure,userDefinedName:t,id:this.props.generateMeasureId(t,this.props.measure.aggregator),fieldName:t}):this.props.onMeasureUpdated({...this.props.measure,userDefinedName:t})}toggleMeasureVisibility(){this.props.onMeasureUpdated({...this.props.measure,isHidden:!this.props.measure.isHidden})}openShowValuesAs(){this.env.replaceSidePanel(`PivotMeasureDisplayPanel`,`pivot_key_${this.props.pivotId}`,{pivotId:this.props.pivotId,measure:this.props.measure})}getColoredSymbolToken(e){if(e.type!==`SYMBOL`)return;let t=Je(e.value,`'`);if(this.props.definition.columns.some(e=>e.nameWithGranularity===t)||this.props.definition.rows.some(e=>e.nameWithGranularity===t)||this.props.definition.measures.some(e=>e.id===t&&e.id!==this.props.measure.id))return ge}get isCalculatedMeasureInvalid(){return lU(this.props.measure.computedBy?.formula??``).isBadExpression}},vU=class extends t.Component{static template=`o-spreadsheet-PivotSortSection`;static components={Section:q};static props={definition:Object,pivotId:String};get hasValidSort(){let e=this.env.model.getters.getPivot(this.props.pivotId);return!!this.props.definition.sortedColumn&&Th(this.props.definition.sortedColumn,e)}get sortDescription(){return k(`Sorted on column (%(ascOrDesc)s):`,{ascOrDesc:this.props.definition.sortedColumn?.order===`asc`?k(`ascending`):k(`descending`)})}get sortValuesAndFields(){let e=this.props.definition.sortedColumn;if(!e)return[];let t=this.env.model.getters.getPivot(this.props.pivotId),n=this.env.model.getters.getLocale(),r=[],i=[];for(let a of e.domain){r.push(a);let{value:e,format:o}=t.getPivotHeaderValueAndFormat(r),s=z(e,{format:o,locale:n}),c=t.definition.getDimension(a.field);i.push({field:Ch(c),value:s})}e.domain.length===0&&i.push({value:k(`Total`)});let a=t.getMeasure(e.measure).displayName;return i.push({value:a,field:k(`Measure`)}),i}},yU=class extends t.Component{static template=`o-spreadsheet-PivotLayoutConfigurator`;static components={AddDimensionButton:XH,PivotDimension:ZH,PivotDimensionOrder:$H,PivotDimensionGranularity:QH,PivotMeasureEditor:_U,PivotSortSection:vU,PivotCustomGroupsCollapsible:JH};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=Sk();AGGREGATORS=sh;composerFocus;isDateOrDatetimeField=ph;setup(){this.composerFocus=D(_r)}startDragAndDrop(e,t){if(t.button!==0||t.target.tagName===`SELECT`)return;let n=this.getDimensionElementsRects(),{columns:r,rows:i}=this.props.definition,a=[...r.map(e=>e.nameWithGranularity),`__rows_title__`,...i.map(e=>e.nameWithGranularity)],o=r.concat(i),s=a.map((e,t)=>({id:e,size:n[t+1].height,position:n[t+1].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.nameWithGranularity,initialMousePosition:t.clientY,items:s,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{let n=a.findIndex(t=>t===e);if(n===t)return;let r=[...a];r.splice(n,1),r.splice(t,0,e);let i=r.slice(0,r.indexOf(`__rows_title__`)),s=r.slice(r.indexOf(`__rows_title__`)+1);this.props.onDimensionsUpdated({columns:i.map(e=>o.find(t=>t.nameWithGranularity===e)).filter(C),rows:s.map(e=>o.find(t=>t.nameWithGranularity===e)).filter(C)})}})}getGranularitiesFor(e){return ph(e)?e.type===`date`?this.props.dateGranularities:this.props.datetimeGranularities:[]}startDragAndDropMeasures(e,t){if(t.button!==0||t.target.tagName===`SELECT`||t.target.tagName===`INPUT`||this.composerFocus.focusMode!==`inactive`)return;let n=this.getDimensionElementsRects(),{measures:r,columns:i,rows:a}=this.props.definition,o=r.map(e=>e.id),s=3+i.length+a.length,c=o.map((e,t)=>({id:e,size:n[t+s].height,position:n[t+s].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.id,initialMousePosition:t.clientY,items:c,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{let n=o.findIndex(t=>t===e);if(n===t)return;let i=[...o];i.splice(n,1),i.splice(t,0,e),this.props.onDimensionsUpdated({measures:i.map(e=>r.find(t=>t.id===e)).filter(C)})}})}getDimensionElementsRects(){return Array.from(this.dimensionsRef.el.children).map(e=>{let t=getComputedStyle(e),n=e.getBoundingClientRect();return{x:n.x,y:n.y,width:n.width+parseInt(t.marginLeft||`0`)+parseInt(t.marginRight||`0`),height:n.height+parseInt(t.marginTop||`0`)+parseInt(t.marginBottom||`0`)}})}removeDimension(e){let{columns:t,rows:n}=this.props.definition;this.props.onDimensionsUpdated({columns:t.filter(t=>t.nameWithGranularity!==e.nameWithGranularity),rows:n.filter(t=>t.nameWithGranularity!==e.nameWithGranularity)})}removeMeasureDimension(e){let{measures:t}=this.props.definition;this.props.onDimensionsUpdated({measures:t.filter(t=>t.id!==e.id)})}addColumnDimension(e){let{columns:t}=this.props.definition;this.props.onDimensionsUpdated({columns:t.concat([{fieldName:e,order:`asc`}])})}addRowDimension(e){let{rows:t}=this.props.definition;this.props.onDimensionsUpdated({rows:t.concat([{fieldName:e,order:`asc`}])})}addMeasureDimension(e){let{measures:t}=this.props.definition,n=this.getDefaultMeasureAggregator(e);this.props.onDimensionsUpdated({measures:t.concat([{id:this.getMeasureId(e,n),fieldName:e,aggregator:n}])})}updateMeasure(e,t){let{measures:n}=this.props.definition,r={measures:n.map(n=>n.id===e.id?t:n)};this.props.definition.sortedColumn?.measure===e.id&&(r.sortedColumn={...this.props.definition.sortedColumn,measure:t.id}),this.props.onDimensionsUpdated(r)}getMeasureId(e,t){let n=e.replaceAll(`'`,``)+(t?`:${t}`:``),r=n,i=2;for(;this.props.definition.measures.some(e=>e.id===r);)r=`${n}:${i}`,i++;return r}getDefaultMeasureAggregator(e){let t=this.props.measureFields.find(t=>t.name===e);return t?.aggregator?t.aggregator:`count`}addCalculatedMeasure(){let{measures:e}=this.props.definition,t=this.env.model.getters.generateNewCalculatedMeasureName(e);this.props.onDimensionsUpdated({measures:e.concat([{id:this.getMeasureId(t,`sum`),fieldName:t,aggregator:`sum`,computedBy:{sheetId:this.env.model.getters.getActiveSheetId(),formula:`=0`}}])})}getCustomField(e){return this.env.model.getters.getPivotCoreDefinition(this.props.pivotId).customFields?.[e.nameWithGranularity]}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?Ch(r):``;return nm.descriptions[t.type](i)}getHugeDimensionErrorMessage(e){let t=this.env.model.getters.getPivot(this.props.pivotId).getPossibleFieldValues(e);return t.length>100?k(`This dimension contains a lot of values (%s), and might slow down the pivot table.`,t.length):void 0}},bU=class extends t.Component{static template=`o-spreadsheet-PivotTitleSection`;static components={CogWheelMenu:SV,Section:q,TextInput:gV};static props={pivotId:String,flipAxis:Function};get cogWheelMenuItems(){return[{name:k(`Flip axes`),icon:`o-spreadsheet-Icon.EXCHANGE`,execute:this.props.flipAxis},{name:k(`Duplicate`),icon:`o-spreadsheet-Icon.COPY`,execute:()=>this.duplicatePivot()},{name:k(`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?k(`Pivot duplicated.`):n.isCancelledBecause(`PivotInError`)?k(`Cannot duplicate a pivot in error.`):k(`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(k(`Are you sure you want to delete this pivot?`),()=>{this.env.model.dispatch(`REMOVE_PIVOT`,{pivotId:this.props.pivotId})})}onNameChanged(e){let t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);this.env.model.dispatch(`UPDATE_PIVOT`,{pivotId:this.props.pivotId,pivot:{...t,name:e}})}};let xU=yO.content;function SU(e){try{return YO(qO(e)).filter(e=>e.type===`FUNCALL`&&!xU[e.value.toUpperCase()]?.isExported).length===0}catch{return!1}}function CU(e,t){if(!e.some(e=>e.type===`SYMBOL`&&t.includes(e.value.toUpperCase())))return[];let n;try{n=qO(e)}catch{return[]}return wU(n,t)}function wU(e,t){return YO(e).filter(e=>e.type===`FUNCALL`&&t.includes(e.value.toUpperCase())).map(e=>({functionName:e.value.toUpperCase(),args:e.args}))}let TU=[`PIVOT.VALUE`,`PIVOT.HEADER`,`PIVOT`];function EU(e){return CU(e,TU)[0]}function DU(e){return CU(e,TU).length}function OU(e,t){let n=`"${t?`${e.name}:${t}`:e.name}"`,r=e.string===e.name?n:e.string+n;return{text:n,description:e.string+(e.help?` (${e.help})`:``),htmlContent:[{value:n,color:He.STRING}],fuzzySearchKey:r}}function kU(e){let t=`"${e.id}"`,n=e.displayName+e.fieldName+t;return{text:t,description:e.displayName,htmlContent:[{value:t,color:He.STRING}],fuzzySearchKey:n}}function AU(e,t){let n=e.end,r=e.end;e.type!==`ARG_SEPARATOR`&&(n=e.start),this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t)}function jU(e,t){let n=e.end,r=e.end;e.type!==`LEFT_PAREN`&&(n=e.start),this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t)}function MU(e){let t=e.functionContext?.args[0];if(!(!t||![`STRING`,`NUMBER`].includes(t.type)))return t.value}var NU=class extends hr{pivotId;updateMode;mutators=[`reset`,`deferUpdates`,`applyUpdate`,`discardPendingUpdate`,`update`];_updatesAreDeferred;draft=null;notification=this.get(ck);alreadyNotified=!1;alreadyNotifiedForPivotSize=!1;constructor(e,t,n=`canDefer`){super(e),this.pivotId=t,this.updateMode=n,this._updatesAreDeferred=this.getters.getPivotCoreDefinition(this.pivotId).deferUpdates??!1}handle(e){switch(e.type){case`UPDATE_PIVOT`:e.pivotId===this.pivotId&&this.getters.getPivot(this.pivotId).init()}}get updatesAreDeferred(){return this.updateMode===`neverDefer`?!1:this._updatesAreDeferred}get fields(){return this.pivot.getFields()}get pivot(){return this.getters.getPivot(this.pivotId)}get definition(){let e=ZL.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:k(`Count`),type:`integer`,aggregator:`sum`}],t=this.fields;for(let n in t){let r=t[n];r&&ZL.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&&ZL.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=>ph(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 ZL.get(this.pivot.type).datetimeGranularities}get dateGranularities(){return ZL.get(this.pivot.type).dateGranularities}get unusedGranularities(){return this.getUnusedGranularities(this.fields,this.draft??this.getters.getPivotCoreDefinition(this.pivotId))}reset(e){this.pivotId=e,this._updatesAreDeferred=!0,this.draft=null}deferUpdates(e){e===!1&&this.draft?(this.draft.deferUpdates=!1,this.applyUpdate()):this.update({deferUpdates:e}),this._updatesAreDeferred=e}applyUpdate(){if(this.draft){if(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:k(`Pivot updates only work with dynamic pivot tables. Use the formula '%s' or re-insert the static pivot from the Data menu.`,e),sticky:!0})}let e=this.getters.getPivot(this.pivotId),t=e.isValid()?e.getExpandedTableStructure().numberOfCells:0;!this.alreadyNotifiedForPivotSize&&t>5e5&&(this.alreadyNotifiedForPivotSize=!0,this.notification.notifyUser({type:`warning`,text:rm(t,this.getters.getLocale()),sticky:!0}))}}discardPendingUpdate(){this.draft=null}update(e){let t=this.getters.getPivotCoreDefinition(this.pivotId),n={...t,...this.draft,...e},r={...n,columns:n.columns.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),rows:n.rows.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),measures:n.measures.map(e=>({id:e.id,fieldName:e.fieldName,aggregator:e.aggregator,userDefinedName:e.userDefinedName,computedBy:e.computedBy,isHidden:e.isHidden,format:e.format,display:e.display})),sortedColumn:this.shouldKeepSortedColumn(n)?n.sortedColumn:void 0};if(r.collapsedDomains){let{COL:e,ROW:t}=r.collapsedDomains;r.collapsedDomains={COL:e.filter(e=>this.areDomainFieldsValid(e,r.columns)),ROW:t.filter(e=>this.areDomainFieldsValid(e,r.rows))}}if(!this.draft&&w(t,r))return;let i=this.addDefaultDateTimeGranularity(this.fields,r);this.draft=i,this.updatesAreDeferred||this.applyUpdate()}isUpdatedPivotVisibleInViewportOnlyAsStaticPivot(){let e=0,t=this.getters.getPivotFormulaId(this.pivotId);for(let n of this.getters.getVisibleCellPositions()){let r=this.getters.getCell(n);if(r?.isFormula){let n=EU(r.compiledFormula.tokens),i=n?.args[0]?.value;if(n&&t===i.toString()){if(n.functionName===`PIVOT`)return!1;e++}}}return e>0}addDefaultDateTimeGranularity(e,t){let{columns:n,rows:r}=t,i=b(n),a=b(r),o=this.getUnusedGranularities(e,t);for(let t of i.concat(a)){let n=e[t.fieldName]?.type;if((n===`date`||n===`datetime`)&&!t.granularity){let e=o[t.fieldName]?.values().next().value;o[t.fieldName]?.delete(e),t.granularity=e}}return{...t,columns:i,rows:a}}getUnusedGranularities(e,t){let{columns:n,rows:r,measures:i}=t,a=n.concat(r).concat(i).filter(t=>{let n=e[t.fieldName]?.type;return n===`date`||n===`datetime`}),o={};for(let t of a)o[t.fieldName]=new Set(e[t.fieldName]?.type===`date`?this.dateGranularities:this.datetimeGranularities);for(let e of a)o[e.fieldName].delete(e.granularity);return o}shouldKeepSortedColumn(e){let{sortedColumn:t}=e;if(!t)return!0;let n=this.getters.getPivotCoreDefinition(this.pivotId);return e.measures.find(e=>e.id===t.measure)&&w(n.columns,e.columns)}areDomainFieldsValid(e,t){let n=t.map(({fieldName:e,granularity:t})=>e+(t?`:${t}`:``));for(let t=0;t<e.length;t++)if(e[t].field!==n[t])return!1;return!0}},PU=class extends t.Component{static template=`o-spreadsheet-PivotSpreadsheetSidePanel`;static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:yU,Section:q,SelectionInput:kk,Checkbox:Fk,PivotDeferUpdate:qH,PivotTitleSection:bU};store;state;pivotSidePanelRef=(0,t.useRef)(`pivotSidePanel`);setup(){this.store=or(NU,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 FU=new B;FU.add(`SPREADSHEET`,{editor:PU});var IU=class extends t.Component{static template=`o-spreadsheet-PivotDesignPanel`;static props={pivotId:String};static components={Section:q,Checkbox:Fk,NumberInput:LV};store;setup(){this.store=or(NU,this.props.pivotId,`neverDefer`)}updatePivotStyleNumberProperty(e,t){let n=parseInt(e);this.store.update({style:{...this.pivotStyle,[t]:isNaN(n)?void 0:n}})}updatePivotStyleProperty(e,t){this.store.update({style:{...this.pivotStyle,[e]:t}})}get pivotStyle(){return this.env.model.getters.getPivotCoreDefinition(this.props.pivotId).style||{}}get defaultStyle(){return rh}},LU=class extends t.Component{static template=`o-spreadsheet-PivotSidePanel`;static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:yU,Section:q,PivotDesignPanel:IU};state=(0,t.useState)({panel:`configuration`});setup(){OH(this)}get sidePanelEditor(){let e=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);if(!e)throw Error(`pivotId does not correspond to a pivot.`);return FU.get(e.type).editor}get highlights(){return GH(this.env.model.getters,this.props.pivotId)}switchPanel(e){this.state.panel=e}},RU=class extends t.Component{static template=`o-spreadsheet-RemoveDuplicatesPanel`;static components={ValidationMessages:IB,Section:q,Checkbox:Fk};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=k(`Column %s`,Ht(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)}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(em.Errors[n]||em.Errors.Unexpected);return Array.from(t)}get selectionStatisticalInformation(){let e=On(this.env.model.getters.getSelectedZone());return k(`%(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))}},zU=class extends t.Component{static template=`o-spreadsheet-SettingsPanel`;static components={Section:q,ValidationMessages:IB,BadgeSelection:AV};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=Uv(e);return t||console.warn(`Invalid locale: ${e.code} ${e}`),t}).sort((e,t)=>e.name.localeCompare(t.name))}get numberFormatPreview(){return z(1234567.89,{format:`#,##0.00`,locale:this.env.model.getters.getLocale()})}get dateFormatPreview(){let e=this.env.model.getters.getLocale();return z(1.6,{format:e.dateFormat,locale:e})}get dateTimeFormatPreview(){let e=this.env.model.getters.getLocale();return z(1.6,{format:oy(e),locale:e})}get firstDayOfWeek(){return Vo[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(!w(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 BU={SplitIsDestructive:k(`This will overwrite data in the subsequent columns. Split anyway?`)};function VU(e,t,n){let r=e.model.dispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:t,addNewColumns:n});return r.isCancelledBecause(`SplitWillOverwriteContent`)&&e.askConfirmation(BU.SplitIsDestructive,()=>{r=e.model.dispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:t,addNewColumns:n,force:!0})}),r}let HU=[{name:k(`Detect automatically`),value:`auto`},{name:k(`Custom separator`),value:`custom`},{name:k(`Space`),value:` `},{name:k(`Comma`),value:`,`},{name:k(`Semicolon`),value:`;`},{name:k(`Line Break`),value:`
|
|
116
|
-
`}];var UU=class extends t.Component{static template=`o-spreadsheet-SplitIntoColumnsPanel`;static components={ValidationMessages:IB,Section:q,Checkbox:Fk};static props={onCloseSidePanel:Function};state=(0,t.useState)({separatorValue:`auto`,addNewColumns:!1,customSeparator:``});setup(){let e=D(_r);(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(){VU(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($p.Errors[n]||$p.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($p.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 HU}get isConfirmDisabled(){return!this.separatorValue||this.errorMessages.length>0}};function WU(e,t){return e.model.getters.isTableStyleEditable(t)?p([{id:`editTableStyle`,name:k(`Edit table style`),execute:e=>e.openSidePanel(`TableStyleEditorPanel`,{styleId:t}),isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.EDIT`},{id:`deleteTableStyle`,name:k(`Delete table style`),execute:e=>e.model.dispatch(`REMOVE_TABLE_STYLE`,{tableStyleId:t}),icon:`o-spreadsheet-Icon.TRASH`}]):[]}function GU(e,t,n,r){e.resetTransform(),KU(e,t,n,r),qU(e,t,n,r),JU(e,t,n,r)}function KU(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 qU(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 JU(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()}var YU=class extends t.Component{static template=`o-spreadsheet-TableStylePreview`;static components={MenuPopover:Dv};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,anchorRect:null,menuItems:[]});setup(){(0,t.onWillUpdateProps)(e=>{(!w(this.props.tableConfig,e.tableConfig)||!w(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,GU(t,nI(e.tableConfig,e.tableStyle,5,5),(n-1)/5,(r-1)/5)}onContextMenu(e){this.props.styleId&&(this.menu.menuItems=WU(this.env,this.props.styleId),this.menu.isOpen=!0,this.menu.anchorRect={x:e.clientX,y:e.clientY,width:0,height:0})}closeMenu(){this.menu.isOpen=!1,this.menu.anchorRect=null,this.menu.menuItems=[]}get styleName(){return this.props.styleId?this.env.model.getters.getTableStyle(this.props.styleId).displayName:``}get isStyleEditable(){return this.props.styleId?this.env.model.getters.isTableStyleEditable(this.props.styleId):!1}editTableStyle(){this.env.openSidePanel(`TableStyleEditorPanel`,{styleId:this.props.styleId})}},XU=class extends t.Component{static template=`o-spreadsheet-TableStylesPopover`;static components={Popover:Cv,TableStylePreview:YU};static props={tableConfig:Object,popoverProps:{type:Object,optional:!0},closePopover:Function,onStylePicked:Function,selectedStyleId:{type:String,optional:!0}};categories=xA;tableStyleListRef=(0,t.useRef)(`tableStyleList`);state=(0,t.useState)({selectedCategory:this.initialSelectedCategory});setup(){(0,t.useExternalListener)(window,`click`,this.onExternalClick,{capture:!0})}onExternalClick(e){this.tableStyleListRef.el&&!Zf(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})}},ZU=class extends t.Component{static template=`o-spreadsheet-TableStylePicker`;static components={TableStylesPopover:XU,TableStylePreview:YU};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:`top-right`,verticalOffset:0}}closePopover(){this.state.popoverProps=void 0}},QU=class extends t.Component{static template=`o-spreadsheet-TablePanel`;static components={TableStylePicker:ZU,SelectionInput:kk,ValidationMessages:IB,Checkbox:Fk,Section:q,NumberInput:LV};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($F(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:this.env.model.getters.getRangeData(n.range),tableType:t}),a=this.env.model.getters.getCoreTable($F(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=parseInt(e);this.updateNumberOfHeaders(t)}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(Vn(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:this.env.model.getters.getRangeData(t),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=$F(s);this.env.model.selection.selectZone({zone:E(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=>tm.Errors[e]||tm.Errors.Unexpected)}getCheckboxLabel(e){return tm.Checkboxes[e]}get canHaveFilters(){return this.tableConfig.numberOfHeaders>0}get hasFilterCheckboxTooltip(){return this.canHaveFilters?void 0:tm.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 tm.Tooltips.isDynamic}};let $U=`#3C78D8`;var eW=class extends t.Component{static template=`o-spreadsheet-TableStyleEditorPanel`;static components={Section:q,RoundColorPicker:bk,TableStylePreview:YU};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||$U,selectedTemplateName:e?.templateName||`lightColoredText`,styleName:e?.displayName||this.env.model.getters.getNewCustomTableStyleName()}}togglePicker(){this.state.pickerOpened=!this.state.pickerOpened}onColorPicked(e){this.state.primaryColor=Tr(e)?e:$U,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(LA).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 RA(this.state.styleName,e,this.state.primaryColor)}};let tW=new B;tW.add(`ConditionalFormatting`,{title:k(`Conditional formatting`),Body:MH}),tW.add(`ChartPanel`,{title:k(`Chart`),Body:TH,computeState:(e,t)=>{let n=e.getSelectedFigureId(),r=n?e.getChartIdFromFigureId(n):t.chartId;return!r||!e.isChartDefined(r)?{isOpen:!1}:{isOpen:!0,props:{chartId:r}}}}),tW.add(`FindAndReplace`,{title:k(`Find and Replace`),Body:RH}),tW.add(`SplitToColumns`,{title:k(`Split text into columns`),Body:UU}),tW.add(`Settings`,{title:k(`Spreadsheet settings`),Body:zU}),tW.add(`RemoveDuplicates`,{title:k(`Remove duplicates`),Body:RU}),tW.add(`DataValidation`,{title:k(`Data validation`),Body:FH}),tW.add(`DataValidationEditor`,{title:k(`Data validation`),Body:NH}),tW.add(`MoreFormats`,{title:k(`More formats`),Body:HH}),tW.add(`TableSidePanel`,{title:k(`Edit table`),Body:QU,computeState:e=>{let t=e.getFirstTableInSelection();return t?{isOpen:!0,props:{table:e.getCoreTable($F(t))},key:t.id}:{isOpen:!1}}}),tW.add(`TableStyleEditorPanel`,{title:k(`Create custom table style`),Body:eW,computeState:(e,t)=>({isOpen:!0,props:{...t},key:t.styleId??`new`})}),tW.add(`PivotSidePanel`,{title:(e,t)=>k(`Pivot #%s`,e.model.getters.getPivotFormulaId(t.pivotId)),Body:LU,computeState:(e,t)=>({isOpen:e.isExistingPivot(t.pivotId),props:t,key:`pivot_key_${t.pivotId}`})}),tW.add(`PivotMeasureDisplayPanel`,{title:(e,t)=>k(`Measure "%s" options`,e.model.getters.getPivot(t.pivotId).getMeasure(t.measure.id).displayName),Body:WH,computeState:(e,t)=>{try{return e.getPivot(t.pivotId).getMeasure(t.measure.id),{isOpen:!0,props:t,key:`pivot_measure_display_${t.pivotId}_${t.measure.id}`}}catch{return{isOpen:!1}}}}),tW.add(`CarouselPanel`,{title:k(`Carousel`),Body:CV,computeState:(e,t)=>{let n=t.figureId||e.getSelectedFigureId();return!n||!e.doesCarouselExist(n)?{isOpen:!1}:{isOpen:!0,props:{figureId:n}}}});var nW=class{mutators=[`setSmallThreshhold`];_isSmallCallback=()=>!1;get isSmall(){return this._isSmallCallback()}setSmallThreshhold(e){this._isSmallCallback=e}},rW=class extends hr{mutators=[`open`,`replace`,`toggle`,`close`,`changePanelSize`,`resetPanelSize`,`togglePinPanel`,`closeMainPanel`,`changeSpreadsheetWidth`,`toggleCollapsePanel`];mainPanel=void 0;secondaryPanel;availableWidth=0;screenWidthStore=this.get(nW);get isMainPanelOpen(){return this.mainPanel&&this.mainPanel.componentTag?this.computeState(this.mainPanel).isOpen:!1}get isSecondaryPanelOpen(){return this.secondaryPanel&&this.secondaryPanel.componentTag?this.computeState(this.secondaryPanel).isOpen:!1}get mainPanelProps(){return this.mainPanel?this.getPanelProps(this.mainPanel):void 0}get mainPanelKey(){return this.mainPanel?this.getPanelKey(this.mainPanel):void 0}get secondaryPanelProps(){return this.secondaryPanel?this.getPanelProps(this.secondaryPanel):void 0}get secondaryPanelKey(){return this.secondaryPanel?this.getPanelKey(this.secondaryPanel):void 0}get totalPanelSize(){return(this.mainPanel?.size||0)+(this.secondaryPanel?.size??0)}getPanelProps(e){let t=this.computeState(e);return t.isOpen?(e.currentPanelProps=t.props??e.currentPanelProps,t.props??{}):{}}getPanelKey(e){let t=this.computeState(e);if(t.isOpen)return t.key}open(e,t={}){if(this.screenWidthStore.isSmall)return;let n={currentPanelProps:t,componentTag:e,size:350},r=this.computeState(n);if(!r.isOpen)return;if(!this.mainPanel||!this.mainPanel.isPinned||this.mainPanelKey===r.key){this._openPanel(`mainPanel`,n,r);return}let i=this.mainPanel.isCollapsed?350:this.mainPanel.size;if(!this.secondaryPanel&&i+350>this.availableWidth){this.get(ck).notifyUser({sticky:!1,type:`warning`,text:k(`The window is too small to display multiple side panels.`)});return}this._openPanel(`secondaryPanel`,n,r)}replace(e,t,n={}){let r={currentPanelProps:n,componentTag:e,size:350},i=this.computeState(r);if(!i.isOpen)return;let a=()=>{this.mainPanel?.isCollapsed&&this.toggleCollapsePanel(`mainPanel`)},o=this.mainPanelKey===i.key,s=this.secondaryPanelKey===i.key;if(o&&this.secondaryPanel){this.close(),a();return}if(s){this.closeMainPanel(),this.togglePinPanel(),a();return}let c=this.mainPanelKey===t?`mainPanel`:`secondaryPanel`;this._openPanel(c,r,i)}_openPanel(e,t,n){let r=this[e];r&&t.componentTag!==r.componentTag&&r.currentPanelProps?.onCloseSidePanel?.(),this[e]={currentPanelProps:n.props??{},componentTag:t.componentTag,size:r?.size||350,isCollapsed:r?.isCollapsed||!1,isPinned:r&&`isPinned`in r?r.isPinned:!1},this[e].isCollapsed&&this.toggleCollapsePanel(e)}toggle(e,t){let n=this.mainPanel?.isPinned?this.secondaryPanel:this.mainPanel;n&&e===n.componentTag?this.close():this.open(e,t)}close(){if(this.mainPanel?.isPinned){this.secondaryPanel&&=(this.secondaryPanel.currentPanelProps.onCloseSidePanel?.(),void 0);return}this.mainPanel?.currentPanelProps.onCloseSidePanel?.(),this.mainPanel=void 0}closeMainPanel(){this.mainPanel?.currentPanelProps.onCloseSidePanel?.(),this.mainPanel=this.secondaryPanel||void 0,this.secondaryPanel=void 0}changePanelSize(e,t){let n=this[e];if(!n||`isCollapsed`in n&&n.isCollapsed)return;t=Math.max(t,350);let r=e===`mainPanel`?this.secondaryPanel?.size||0:this.mainPanel?.size||0;t>this.availableWidth-r&&(e===`mainPanel`&&this.secondaryPanel&&(this.secondaryPanel.size=Math.max(this.availableWidth-t,350),r=this.secondaryPanel.size),t=Math.max(this.availableWidth-r,350)),n.size=t}resetPanelSize(e){this[e]&&(this[e].size=350)}togglePinPanel(){this.mainPanel&&(this.mainPanel.isPinned=!this.mainPanel.isPinned,!this.mainPanel.isPinned&&this.secondaryPanel&&(this.secondaryPanel?.currentPanelProps.onCloseSidePanel?.(),this.mainPanel=this.secondaryPanel,this.secondaryPanel=void 0))}toggleCollapsePanel(e){let t=this[e];t&&(t.isCollapsed?(t.isCollapsed=!1,this.changePanelSize(e,350)):(t.isCollapsed=!0,t.size=45))}computeState({componentTag:e,currentPanelProps:t}){let n=tW.get(e).computeState,r=n?n(this.getters,t):{isOpen:!0,props:t};return r.isOpen?{...r,key:r.key||e}:r}changeSpreadsheetWidth(e){this.availableWidth=e-150,this.secondaryPanel&&e-this.totalPanelSize<150&&(this.secondaryPanel?.currentPanelProps.onCloseSidePanel?.(),this.secondaryPanel=void 0),this.mainPanel&&e-this.totalPanelSize<150&&(this.mainPanel.size=Math.max(e-150,350))}},iW=class extends t.Component{static template=`o-spreadsheet-TableResizer`;static props={table:Object};state=(0,t.useState)({highlightZone:void 0});dragNDropGrid=Xz(this.env);setup(){OH(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`;let r=yp(this.env,e);this.dragNDropGrid.start(r,(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?[{range:this.env.model.getters.getRangeFromZone(this.props.table.range.sheetId,this.state.highlightZone),color:`#777`,noFill:!0}]:[]}};let aW={ROW:qz,COL:Bz,CELL:SR,GROUP_HEADERS:Gz,UNGROUP_HEADERS:Kz};var oW=class extends t.Component{static template=`o-spreadsheet-Grid`;static props={exposeFocus:Function,getGridSize:Function};static components={GridComposer:TB,GridOverlay:KB,GridPopover:qB,HeadersOverlay:$B,MenuPopover:Dv,Autofill:Qz,ClientTag:eB,Highlight:cV,Popover:Cv,VerticalScrollBar:fV,HorizontalScrollBar:dV,TableResizer:iW,Selection:pV};HEADER_HEIGHT=26;HEADER_WIDTH=48;menuState;gridRef;highlightStore;cellPopovers;composerFocusStore;DOMFocusableElementStore;paintFormatStore;clientFocusStore;dragNDropGrid=Xz(this.env);onMouseWheel;hoveredCell;sidePanel;setup(){this.highlightStore=D(sk),this.menuState=(0,t.useState)({isOpen:!1,anchorRect:null,menuItems:[]}),this.gridRef=(0,t.useRef)(`grid`),this.hoveredCell=D(Pv),this.composerFocusStore=D(_r),this.DOMFocusableElementStore=D(xO),this.sidePanel=D(rW),this.paintFormatStore=D(HB),this.clientFocusStore=D(Yz),D(Jz),(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()),tV(`canvas`,this.env.model,()=>this.env.model.getters.getSheetViewDimensionWithHeaders()),this.onMouseWheel=iV((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=D(Bk),(0,t.useEffect)((e,t)=>{!e&&!t&&this.DOMFocusableElementStore.focus()},()=>[this.sidePanel.isMainPanelOpen,this.sidePanel.isSecondaryPanelOpen]),rV(this.gridRef,this.moveCanvas.bind(this),()=>{let{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0},()=>{let{maxOffsetY:e}=this.env.model.getters.getMaximumSheetOffset(),{scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo();return t<e})}get highlights(){return this.highlightStore.highlights}get gridOverlayDimensions(){let e=this.env.model.getters.getScrollBarWidth();return U({top:`26px`,left:`48px`,height:`calc(100% - ${26+e}px)`,width:`calc(100% - ${48+e}px)`})}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_UNFILTERED_CONTENT`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Backspace:()=>{this.env.model.dispatch(`DELETE_UNFILTERED_CONTENT`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Escape:()=>{this.cellPopovers.isOpen?this.cellPopovers.close():this.menuState.isOpen?this.closeMenu():this.paintFormatStore.isActive?this.paintFormatStore.cancel():this.env.model.dispatch(`CLEAN_CLIPBOARD_HIGHLIGHT`)},"Ctrl+A":()=>this.env.model.selection.loopSelection(),"Ctrl+Z":()=>this.env.model.dispatch(`REQUEST_UNDO`),"Ctrl+Y":()=>this.env.model.dispatch(`REQUEST_REDO`),F4:()=>this.env.model.dispatch(`REQUEST_REDO`),"Ctrl+B":()=>this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{bold:!this.env.model.getters.getCurrentStyle().bold}}),"Ctrl+I":()=>this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{italic:!this.env.model.getters.getCurrentStyle().italic}}),"Ctrl+U":()=>this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{underline:!this.env.model.getters.getCurrentStyle().underline}}),"Ctrl+O":()=>iF(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&&$s(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+H":()=>this.sidePanel.open(`FindAndReplace`,{}),"Ctrl+F":()=>this.sidePanel.open(`FindAndReplace`,{}),"Ctrl+Shift+E":()=>this.setHorizontalAlign(`center`),"Ctrl+Shift+L":()=>this.setHorizontalAlign(`left`),"Ctrl+Shift+R":()=>this.setHorizontalAlign(`right`),"Ctrl+Shift+V":()=>NP(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?YP(this.env):i&&!r&&qP(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(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:`COL`,elements:e}):t.length>0&&e.length===0&&this.env.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:this.env.model.getters.getActiveSheetId(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:`ROW`,elements:t})},"Shift+PageDown":()=>{this.env.model.dispatch(`ACTIVATE_NEXT_SHEET`)},"Shift+PageUp":()=>{this.env.model.dispatch(`ACTIVATE_PREVIOUS_SHEET`)},PageDown:()=>this.env.model.dispatch(`SHIFT_VIEWPORT_DOWN`),PageUp:()=>this.env.model.dispatch(`SHIFT_VIEWPORT_UP`),"Ctrl+K":()=>sF(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{x:t.x+t.width-8/2,y: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(){let{height:e,width:t}=this.props.getGridSize();this.env.model.dispatch(`RESIZE_SHEETVIEW`,{width:t-48,height:e-26,gridOffsetX:48,gridOffsetY:26})}moveCanvas(e,t){let{scrollX:n,scrollY:r}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:n+e,offsetY:r+t})}processSpaceKey(e){this.env.model.getters.hasBooleanValidationInZones(this.env.model.getters.getSelectedZones())&&(e.preventDefault(),e.stopPropagation(),this.env.model.dispatch(`TOGGLE_CHECKBOX`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()}))}getClientPositionKey(e){return`${e.id}-${e.position?.sheetId}-${e.position?.col}-${e.position?.row}`}isCellHovered(e,t){return this.hoveredCell.col===e&&this.hoveredCell.row===t}get focusedClients(){return this.clientFocusStore.focusedClients}getGridRect(){let e=this.env.model.getters.getViewportZoomLevel(),{width:t,height:n}=this.env.model.getters.getSheetViewDimensionWithHeaders();return{...ep(this.gridRef),width:t*e,height:n*e}}onCellClicked(e,t,n,r){if(r.ev.preventDefault(),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),this.env.isMobile())return;let i=e,a=t;this.dragNDropGrid.start(r,(e,t,n)=>{n.preventDefault(),(e!==i&&e!==-1||t!==a&&t!==-1)&&(i=e===-1?i:e,a=t===-1?a:t,this.env.model.selection.setAnchorCorner(i,a))},()=>{this.env.model.selection.commitSelection(),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(),CO(e,this.env.model.selection),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())}onKeydown(e){let t=cp(e),n=this.keyDownMapping[t];if(n){e.preventDefault(),e.stopPropagation(),n();return}if(t===` `){this.processSpaceKey(e);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.getVisibleRectWithZoom(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`;En(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.anchorRect={x:t,y:n,width:0,height:0},this.menuState.menuItems=aW[e].getMenuItems()}async copy(e,t){if(!this.gridEl.contains(document.activeElement)||this.composerFocusStore.activeComposer.editionMode!==`inactive`)return;e?cI(this.env):this.env.model.dispatch(`COPY`);let n=await this.env.model.getters.getClipboardTextAndImageContent();await this.env.clipboard.write(n),t.preventDefault()}async paste(e){if(!this.gridEl.contains(document.activeElement))return;e.preventDefault();let t=e.clipboardData;if(!t)return;let n=[...t.files]?.find(e=>eA.includes(e.type)),r={content:{"text/plain":t?.getData(`text/plain`),"text/html":t?.getData(`text/html`)}};n&&(r.content[n.type]=n);let i=this.env.model.getters.getSelectedZones(),a=this.env.model.getters.isCutOperation(),o=this.env.model.getters.getClipboardId(),s=iA(r.content);o===s.data?.clipboardId?DP(this.env,i):await OP(this.env,i,s),a&&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.getVisibleRectWithZoom(n),i=this.getGridRect();this.toggleContextMenu(`GROUP_HEADERS`,e+r+i.x,t+i.y);break}case`left`:{if(!XF(this.env,`COL`)&&!XF(this.env,`ROW`))return;let{x:e,y:t,width:r}=this.env.model.getters.getVisibleRectWithZoom(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(tI)}get displaySelectionHandler(){return this.env.isMobile()&&this.composerFocusStore.activeComposer.editionMode===`inactive`}};let sW=new B;sW.add(`SPREADSHEET`,!1);var cW=class extends t.Component{static template=`o-spreadsheet-ClickableCellSortIcon`;static props={position:Object,sortDirection:String};hoveredTableStore;setup(){this.hoveredTableStore=D(UB)}get style(){let e=this.env.model.getters.getCellComputedStyle(this.props.position);return U({color:e.textColor||`#374151C2`,"background-color":this.getBackgroundColor(e)})}get verticalJustifyClass(){switch(this.env.model.getters.getCellComputedStyle(this.props.position).verticalAlign){case`top`:return`justify-content-start`;case`middle`:return`justify-content-center`;default:return`justify-content-end`}}getBackgroundColor(e){let t=this.hoveredTableStore.overlayColors.get(this.props.position);return t?Lr(e.fillColor||`#FFFFFF`,t):e.fillColor||`#FFFFFF`}},lW=class extends t.Component{static template=`o-spreadsheet-FullScreenFigure`;static props={};static components={ChartFigure:Av};fullScreenFigureStore;ref=(0,t.useRef)(`fullScreenFigure`);spreadsheetRect=xv();figureRegistry=Mv;setup(){this.fullScreenFigureStore=D(cv);let e=D(Zl),n;(0,t.onWillUpdateProps)(()=>{n!==this.figureUI?.id&&e.enableAnimationForChart(this.chartId+`-fullscreen`),n=this.figureUI?.id}),(0,t.useEffect)(e=>e?.focus(),()=>[this.ref.el])}get figureUI(){return this.fullScreenFigureStore.fullScreenFigure}get chartId(){if(this.figureUI)return this.env.model.getters.getChartIdFromFigureId(this.figureUI?.id)}exitFullScreen(){this.figureUI&&this.fullScreenFigureStore.toggleFullScreenFigure(this.figureUI.id)}onKeyDown(e){e.key===`Escape`&&this.exitFullScreen()}get figureComponent(){if(this.figureUI)return Mv.get(this.figureUI.tag).Component}},uW=class extends t.Component{static template=`o_spreadsheet.PivotHTMLRenderer`;static components={Checkbox:Fk};static props={pivotId:String,onCellClicked:Function};pivot=this.env.model.getters.getPivot(this.props.pivotId);data={columns:[],rows:[],values:[]};state=(0,t.useState)({showMissingValuesOnly:!1});setup(){let e=this.pivot.getExpandedTableStructure(),t=this.env.model.getters.getPivotFormulaId(this.props.pivotId);this.data={columns:this._buildColHeaders(t,e),rows:this._buildRowHeaders(t,e),values:this._buildValues(t,e)}}get tracker(){return this.env.model.getters.getPivotPresenceTracker(this.props.pivotId)}getTableData(){if(!this.state.showMissingValuesOnly)return this.data;let e=this.getColumnsIndexes(),t=this.getRowsIndexes();return{columns:this.buildColumnsMissing(e),rows:this.buildRowsMissing(t),values:this.buildValuesMissing(e,t)}}addRecursiveRow(e){let t=this.pivot.getExpandedTableStructure().rows,n=[...t[e].values];if(n.length<=1)return[e];n.pop();let r=t.findIndex(e=>JSON.stringify(e.values)===JSON.stringify(n));return[e].concat(this.addRecursiveRow(r))}buildColumnsMissing(e){let t=[];for(let e of this.data.columns){let n=[];for(let t in e)for(let r=0;r<e[t].span;r++)n.push(parseInt(t,10));t.push(n)}for(let n=t[t.length-1].length;n>=0;n--)if(!e.includes(n))for(let e of t)e.splice(n,1);let n=[];for(let e in t){let r=[],i,a=1;for(let n=0;n<t[e].length;n++)i===t[e][n]?a++:(i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),i=t[e][n],a=1);i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),n.push(r)}return n}buildRowsMissing(e){return e.map(e=>this.data.rows[e])}buildValuesMissing(e,t){let n=e.map(()=>[]);for(let r of t)for(let t in e)n[t].push(this.data.values[e[t]][r]);return n}getColumnsIndexes(){let e=new Set;for(let t=0;t<this.data.columns.length;t++){let n=[];for(let e=0;e<this.data.columns[t].length;e++)for(let r=0;r<this.data.columns[t][e].span;r++)n.push(this.data.columns[t][e]);for(let t=0;t<n.length;t++)n[t].isMissing&&e.add(t)}for(let t=0;t<this.data.columns[this.data.columns.length-1].length;t++)this.data.values[t].find(e=>e.isMissing)&&e.add(t);return Array.from(e).sort((e,t)=>e-t)}getRowsIndexes(){let e=new Set;for(let t=0;t<this.data.rows.length;t++){this.data.rows[t].isMissing&&e.add(t);for(let n of this.data.values)n[t].isMissing&&this.addRecursiveRow(t).forEach(t=>e.add(t))}return Array.from(e).sort((e,t)=>e-t)}_buildColHeaders(e,t){let n=[];for(let r of t.columns){let t=[];for(let n of r){let r=[];for(let e=0;e<n.fields.length;e++)r.push({value:n.fields[e]},{value:n.values[e]});let i=this.pivot.parseArgsToPivotDomain(r),a=this.env.model.getters.getLocale();if(i.at(-1)?.field===`measure`){let{value:r,format:o}=this.pivot.getPivotMeasureValue(P(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${mh(e,i).join(`,`)})`,value:z(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(${mh(e,i).join(`,`)})`,value:z(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(${mh(e,i).join(`,`)})`,value:z(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=P(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(${mh(e,o,a).join(`,`)})`,value:z(s,{format:c,locale:l}),isMissing:!this.tracker?.isValuePresent(a,o)})}n.push(i)}return n}},dW=class extends sb{getters;dispatch;canDispatch;constructor({getters:e,stateObserver:t,range:n,dispatch:r,canDispatch:i}){super(t),n.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.dispatch=r,this.canDispatch=i}import(e){}export(e){}adaptRanges(e,t,n){}},fW=class extends dW{static getters=[`getCellBorder`,`getBordersColors`];borders={};allowDispatch(e){switch(e.type){case`SET_BORDER`:return this.checkBordersUnchanged(e);default:return`Success`}}handle(e){switch(e.type){case`ADD_MERGE`:for(let t of e.target)this.addBordersToMerge(e.sheetId,t);break;case`DUPLICATE_SHEET`:let t=this.borders[e.sheetId];if(t){let n=t.slice().map(e=>e?.slice().map(e=>b(e)));this.history.update(`borders`,e.sheetIdTo,n)}break;case`DELETE_SHEET`:let n={...this.borders};delete n[e.sheetId],this.history.update(`borders`,n);break;case`SET_BORDER`:this.setBorder(e.sheetId,e.col,e.row,e.border);break;case`SET_BORDERS_ON_TARGET`:for(let t of e.target)for(let n=t.top;n<=t.bottom;n++)for(let r=t.left;r<=t.right;r++)this.setBorder(e.sheetId,r,n,e.border);break;case`SET_ZONE_BORDERS`:if(e.border){let t=e.target.map(t=>this.getters.expandZone(e.sheetId,t));this.setBorders(e.sheetId,t,e.border.position,e.border.color===``?void 0:{style:e.border.style||Te.style,color:e.border.color||Te.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 Ze(r))if(e.dimension===`COL`){let n=this.getters.getColsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersHorizontally(e.sheetId,t[0]+1,-t.length)}else{let n=this.getters.getRowsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersVertically(e.sheetId,t[0]+1,-t.length)}break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumns(e):this.handleAddRows(e);break}}handleAddColumns(e){let t,n;e.position===`before`?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity),t=e.base,n=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,n)}handleAddRows(e){let t,n;e.position===`before`?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity),t=e.base,n=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,n)}getCellBorder({sheetId:e,col:t,row:n}){let r=this.borders[e]?.[t]?.[n];return r?.top||r?.bottom||r?.left||r?.right?b(r):null}getBordersColors(e){let t=[],n=this.borders[e];if(n){for(let e of n.filter(C))for(let n of e)if(n)for(let e of[`top`,`bottom`,`left`,`right`]){let r=n[e]?.color;r&&t.push(r)}}return t}ensureColumnBorderContinuity(e,t,n){let r=S(t+1,n);for(let i=0;i<this.getters.getNumberRows(e);i++){let a=this.getCellBorder({sheetId:e,col:t,row:i}),o=this.getCellBorder({sheetId:e,col:n,row:i});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,n,i,t)}}}ensureRowBorderContinuity(e,t,n){let r=S(t+1,n);for(let i=0;i<this.getters.getNumberCols(e);i++){let a=this.getCellBorder({sheetId:e,col:i,row:t}),o=this.getCellBorder({sheetId:e,col:i,row:n});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,i,n,t)}}}getCommonSides(e,t){let n={};for(let r of[`top`,`bottom`,`left`,`right`])e[r]&&w(e[r],t[r])&&(n[r]=e[r]);return n}getColumnsWithBorders(e){let t=this.borders[e];return t?Object.keys(t).map(e=>parseInt(e,10)):[]}getRowsWithBorders(e){let t=this.borders[e]?.filter(C);if(!t)return[];let n=new Set;for(let e of t)for(let t in e)n.add(parseInt(t,10));return Array.from(n)}getRowsRange(e){return this.borders[e]?S(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,n){this.borders[e]&&this.getColumnsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(t=>{this.moveBordersOfColumn(e,t,n)})}shiftBordersVertically(e,t,n){this.borders[e]&&(n<0&&this.moveBordersOfRow(e,t,n,{destructive:!1}),this.getRowsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(t=>{this.moveBordersOfRow(e,t,n)}))}moveBordersOfRow(e,t,n,{destructive:r}={destructive:!0}){let i=this.borders[e];i&&this.getColumnsWithBorders(e).forEach(a=>{let o=i[a]?.[t+n],s=i[a]?.[t];this.history.update(`borders`,e,a,t+n,r?s:s||o),this.history.update(`borders`,e,a,t,void 0)})}moveBordersOfColumn(e,t,n,{destructive:r}={destructive:!0}){let i=this.borders[e];i&&this.getRowsRange(e).forEach(a=>{let o=i[t+n]?.[a],s=i[t]?.[a];this.history.update(`borders`,e,t+n,a,r?s:s||o),r&&this.history.update(`borders`,e,t,a,void 0)})}setBorder(e,t,n,r,i=!0){let a=this.getters.getNumberCols(e)-1,o=this.getters.getNumberRows(e)-1;(i||!this.borders[e]?.[t]?.[n]?.left)&&(this.history.update(`borders`,e,t,n,`left`,r?.left),r?.left&&t>0&&!w(this.borders[e]?.[t-1]?.[n]?.right,r?.left)&&this.history.update(`borders`,e,t-1,n,`right`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.top)&&(this.history.update(`borders`,e,t,n,`top`,r?.top),r?.top&&n>0&&!w(this.borders[e]?.[t]?.[n-1]?.bottom,r?.top)&&this.history.update(`borders`,e,t,n-1,`bottom`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.right)&&(this.history.update(`borders`,e,t,n,`right`,r?.right),r?.right&&t<a&&!w(this.borders[e]?.[t+1]?.[n]?.left,r?.right)&&this.history.update(`borders`,e,t+1,n,`left`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.bottom)&&(this.history.update(`borders`,e,t,n,`bottom`,r?.bottom),r?.bottom&&n<o&&!w(this.borders[e]?.[t]?.[n+1]?.top,r?.bottom)&&this.history.update(`borders`,e,t,n+1,`top`,void 0))}clearBorders(e,t,n=!1){let r=this.getters.getNumberCols(e)-1,i=this.getters.getNumberRows(e)-1;for(let a of Qt(t))for(let t=a.top;t<=a.bottom;t++){n&&(a.left>0&&this.history.update(`borders`,e,a.left-1,t,`right`,void 0),a.right<r&&this.history.update(`borders`,e,a.right+1,t,`left`,void 0));for(let r=a.left;r<=a.right;r++)this.history.update(`borders`,e,r,t,void 0),n&&(a.top>0&&this.history.update(`borders`,e,r,a.top-1,`bottom`,void 0),a.bottom<i&&this.history.update(`borders`,e,r,a.bottom+1,`top`,void 0))}}clearInsideBorders(e,t){for(let n of t)for(let t=n.top;t<=n.bottom;t++)for(let r=n.left;r<=n.right;r++)this.history.update(`borders`,e,r,t,void 0)}addBorder(e,t,n,r){this.setBorder(e,t,n,{...this.getCellBorder({sheetId:e,col:t,row:n}),...r})}setBorders(e,t,n,r){if(n===`clear`)return this.clearBorders(e,t,!0);for(let i of Qt(t)){if(n===`all`)for(let t=i.top;t<=i.bottom;t++)for(let n=i.left;n<=i.right;n++)this.addBorder(e,n,t,{top:r,right:r,bottom:r,left:r});if(n===`h`||n===`hv`){if(i.top===i.bottom)continue;for(let t=i.left;t<=i.right;t++){this.addBorder(e,t,i.top,{bottom:r});for(let n=i.top+1;n<i.bottom;n++)this.addBorder(e,t,n,{top:r,bottom:r});this.addBorder(e,t,i.bottom,{top:r})}}if(n===`v`||n===`hv`){if(i.left===i.right)continue;for(let t=i.top;t<=i.bottom;t++){this.addBorder(e,i.left,t,{right:r});for(let n=i.left+1;n<i.right;n++)this.addBorder(e,n,t,{left:r,right:r});this.addBorder(e,i.right,t,{left:r})}}if(n===`left`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.left,t,{left:r});if(n===`right`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.right,t,{right:r});if(n===`top`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.top,{top:r});if(n===`bottom`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.bottom,{bottom:r})}}addBordersToMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t,o=this.getCellBorder({sheetId:e,col:n,row:i}),s=this.getCellBorder({sheetId:e,col:r,row:a});this.clearBorders(e,[t]),o?.top&&this.setBorders(e,[{...t,bottom:i}],`top`,o.top),o?.left&&this.setBorders(e,[{...t,right:n}],`left`,o.left),s?.bottom?this.setBorders(e,[{...t,top:a}],`bottom`,s.bottom):o?.bottom&&this.setBorders(e,[{...t,top:a}],`bottom`,o.bottom),s?.right?this.setBorders(e,[{...t,left:r}],`right`,s.right):o?.right&&this.setBorders(e,[{...t,left:r}],`right`,o.right)}checkBordersUnchanged(e){let t=this.getCellBorder(e),n=!e.border?.bottom&&!e.border?.left&&!e.border?.right&&!e.border?.top;return!t&&n||w(t,e.border)?`NoChanges`:`Success`}import(e){if(Object.keys(e.borders||{}).length)for(let t of e.sheets)for(let[n,r]of yc(t.id,t.borders)){let{sheetId:t,col:i,row:a}=n,o=e.borders[r];this.setBorder(t,i,a,o,!1)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,un(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=_c(a,t),s={sheetId:n.id,col:r,row:i};e[o]??=[],e[o].push(s)}}n.borders=vc(e)}e.borders=t}exportForExcel(e){this.export(e)}},pW=class extends dW{static getters=[`getCarousel`,`doesCarouselExist`];carousels={};allowDispatch(e){switch(e.type){case`CREATE_CAROUSEL`:return this.getters.getFigure(e.sheetId,e.figureId)?`DuplicatedFigureId`:`Success`;case`UPDATE_CAROUSEL`:return this.carousels[e.sheetId]?.[e.figureId]?`Success`:`InvalidFigureId`}return`Success`}handle(e){switch(e.type){case`CREATE_CAROUSEL`:this.getters.getFigure(e.sheetId,e.figureId)||this.dispatch(`CREATE_FIGURE`,{...e,tag:`carousel`}),this.history.update(`carousels`,e.sheetId,e.figureId,e.definition);break;case`UPDATE_CAROUSEL`:this.removeDeletedCharts(e,this.getters.getCarousel(e.figureId).items),this.history.update(`carousels`,e.sheetId,e.figureId,e.definition);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`carousel`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.getCarousel(n.id);if(i){let t={width:n.width,height:n.height};this.dispatch(`CREATE_CAROUSEL`,{sheetId:e.sheetIdTo,figureId:r,offset:n.offset,col:n.col,row:n.row,size:t,definition:{items:i.items.map(t=>{if(t.type===`carouselDataView`)return{...t};let n=t.chartId.split(`??`).pop(),r=`${e.sheetIdTo}??${n}`;return{...t,chartId:r}})}})}}break}case`DELETE_FIGURE`:this.history.update(`carousels`,e.sheetId,e.figureId,void 0);break;case`DELETE_SHEET`:this.history.update(`carousels`,e.sheetId,void 0);break}}doesCarouselExist(e){for(let t in this.carousels)if(this.carousels[t]?.[e])return!0;return!1}getCarousel(e){for(let t in this.carousels)if(this.carousels[t]?.[e])return this.carousels[t][e];throw Error(`There is no carousel with the given figureId: ${e}`)}removeDeletedCharts(e,t){let n=new Set(e.definition.items.filter(e=>e.type===`chart`).map(e=>e.chartId));for(let r of t)r.type===`chart`&&!n.has(r.chartId)&&this.dispatch(`DELETE_CHART`,{chartId:r.chartId,sheetId:e.sheetId})}import(e){for(let t of e.sheets){let e=(t.figures||[]).filter(e=>e.tag===`carousel`);for(let n of e)this.history.update(`carousels`,t.id,n.id,{items:n.data.items,title:n.data.title})}}export(e){for(let t of e.sheets){let e=t.figures.filter(e=>e.tag===`carousel`);for(let n of e)this.carousels[t.id]?.[n.id]&&(n.data={...n.data,...this.carousels[t.id]?.[n.id]})}}},mW=class extends dW{static getters=[`zoneToXC`,`getCells`,`getTranslatedCellFormula`,`getCellById`,`getFormulaString`,`getFormulaMovedInSheet`];nextId=1;cells={};adaptRanges({applyChange:e},t,n){for(let r of Object.keys(this.cells))for(let i of Object.values(this.cells[r]||{}))if(i.isFormula){for(let a of i.compiledFormula.dependencies)if(a.sheetId===t||a.invalidSheetName===n.old){let t=e(a);t.changeType!==`NONE`&&this.history.update(`cells`,r,i.id,`compiledFormula`,`dependencies`,i.compiledFormula.dependencies.indexOf(a),t.range)}}}allowDispatch(e){switch(e.type){case`UPDATE_CELL`:return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessUpdateCell);case`CLEAR_CELL`:return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessClearCell);case`UPDATE_CELL_POSITION`:return!e.cellId||this.cells[e.sheetId]?.[e.cellId]?`Success`:`InvalidCellId`;default:return`Success`}}handle(e){switch(e.type){case`SET_FORMATTING`:`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.copyColumnFormat.bind(this)):this.handleAddColumnsRows(e,this.copyRowFormat.bind(this));break;case`UPDATE_CELL`:this.updateCell(e.sheetId,e.col,e.row,e);break;case`CLEAR_CELL`:this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col,row:e.row,content:``,format:``});break;case`CLEAR_CELLS`:this.clearCells(e.sheetId,e.target);break;case`DELETE_CONTENT`:this.clearZones(e.sheetId,e.target);break;case`DELETE_SHEET`:this.history.update(`cells`,e.sheetId,void 0)}}clearZones(e,t){for(let n of Qt(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++){let n=this.getters.getCell({sheetId:e,col:t,row:r});(n?.isFormula||n?.content)&&this.dispatch(`UPDATE_CELL`,{sheetId:e,content:``,col:t,row:r})}}setFormatter(e,t,n){for(let r of Qt(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 Qt(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,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:``,format:``})}handleAddColumnsRows(e,t){let n,r;e.position===`before`?(n=S(e.base,e.base+e.quantity),r=e.base+e.quantity):(n=S(e.base+1,e.base+e.quantity+1),r=e.base),t(e.sheetId,r,n)}import(e){for(let t of e.sheets){let n=t.id,r=new bF;for(let e in t.cells)if(t.cells[e]){let{col:n,row:i}=Zt(e),a={sheetId:t.id,col:n,row:i};r.set(a,{content:t.cells[e]})}for(let[e,n]of yc(t.id,t.formats)){let t=r.get(e);t?t.format=n:r.set(e,{format:n})}for(let i of r.keysForSheet(n)){let n=r.get(i);if(n?.content||n?.format){let r=this.importCell(t.id,n?.content,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={};for(let n of e.sheets){let e=[],r={},i=Object.keys(this.cells[n.id]||{}).map(e=>this.getters.getCellPosition(e)).sort((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col);for(let n of i){let i=this.getters.getCell(n),a=T(n.col,n.row);if(i.format){let r=_c(i.format,t);e[r]??=[],e[r].push(n)}i.content&&(r[a]=i.content)}n.formats=vc(e),n.cells=r}e.formats=t}importCell(e,t,n){let r=this.getNextUid();return this.createCell(r,t||``,n,e)}exportForExcel(e){this.export(e);let t=[];for(let n in e.formats||[])Cs(e.formats[n])||(t.push(Number(n)),delete e.formats[n]);if(t.length)for(let n of e.sheets)for(let e in n.formats){let r=n.formats[e];r&&t.includes(r)&&delete n.formats[e]}}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 pt(t.map(e=>e.value));let i=0;return pt(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(uU(r).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),t,n,e);return this.getFormulaString(e,r,i)}getFormulaMovedInSheet(e,t,n){let r=uU(n).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),i=this.getters.removeRangesSheetPrefix(t,r);return this.getFormulaString(t,n,i)}zoneToXC(e,t,n=[{colFixed:!1,rowFixed:!1}]){t=this.getters.expandZone(e,t);let r=T(t.left,t.top,n[0]),i=T(t.right,t.bottom,n.length>1?n[1]:n[0]),a=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),o=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),s=a.col===o.col&&a.row===o.row;return r!==i&&!s?r+`:`+i:r}copyColumnFormat(e,t,n){for(let r=0;r<this.getters.getNumberRows(e);r++){let i=this.getFormat(e,t,r);if(i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,...i})}}copyRowFormat(e,t,n){for(let r=0;r<this.getters.getNumberCols(e);r++){let i=this.getFormat(e,r,t);if(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.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?Tt(r?.content):i?.content||``,s=r.format===void 0?i&&i.format:r.format;if((a&&!o&&!r.formula||!a&&(!i||i.content===``))&&!s){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 c=i?.id||this.getNextUid(),l=this.createCell(c,o,s,e);this.history.update(`cells`,e,l.id,l),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:l.id,col:t,row:n,sheetId:e})}createCell(e,t,n,r){return t.startsWith(`=`)?this.createFormulaCell(e,t,n,r):this.createLiteralCell(e,t,n)}createLiteralCell(e,t,n){let r=this.getters.getLocale(),i=nc(t,r);return n||=typeof i==`number`?ss(t,r)||cs(t):void 0,!ws(n)&&!t.startsWith(`'`)&&!M(t)&&(t=P(i)),{id:e,content:t,format:n,isFormula:!1,parsedValue:i}}createFormulaCell(e,t,n,r){let i=lU(t);return i.dependencies.length?this.createFormulaCellWithDependencies(e,i,n,r):{id:e,content:t,format:n,isFormula:!0,compiledFormula:{...i,dependencies:[]}}}createFormulaCellWithDependencies(e,t,n,r){let i=[];for(let e of t.dependencies)i.push(this.getters.getRangeFromSheetXC(r,e));return new hW(e,t,n,i,r,this.getters.getRangeString)}checkCellOutOfSheet(e){let{sheetId:t,col:n,row:r}=e;return this.getters.tryGetSheet(t)?En(n,r,this.getters.getSheetZone(t))?`Success`:`TargetOutOfSheet`:`InvalidSheetId`}checkUselessClearCell(e){let t=this.getters.getCell(e),n=this.getters.getCellStyle(e);return!t||!t.content&&!n&&!t.format?`NoChanges`:`Success`}checkUselessUpdateCell(e){let t=this.getters.getCell(e),n=`content`in e||`formula`in e,r=`style`in e,i=r&&this.getters.getCellStyle(e),a=`format`in e;return(!n||t?.content===e.content)&&(!r||w(i,e.style))&&(!a||t?.format===e.format)?`NoChanges`:`Success`}},hW=class{id;format;sheetId;getRangeString;isFormula=!0;compiledFormula;constructor(e,t,n,r,i,a){this.id=e,this.format=n,this.sheetId=i,this.getRangeString=a;let o=0,s=t.tokens.map(e=>e.type===`REFERENCE`?new gW(r,o++,this.sheetId,this.getRangeString):e);this.compiledFormula={...t,dependencies:r,tokens:s}}get content(){return pt(this.compiledFormula.tokens.map(e=>e.value))}get contentWithFixedReferences(){let e=0;return pt(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}))}},gW=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)}},_W=class extends dW{static getters=[`isChartDefined`,`getChartDefinition`,`getChartType`,`getChartIds`,`getChart`,`getFigureIdFromChartId`,`getContextCreationChart`];charts={};createChart=m_(this.getters);validateChartDefinition=e=>g_(this,e.definition);adaptRanges(e){for(let[t,n]of Object.entries(this.charts)){if(!n)continue;let r=n.chart.updateRanges(e);this.history.update(`charts`,t,r?{figureId:n.figureId,chart:r}:void 0)}}allowDispatch(e){switch(e.type){case`CREATE_CHART`:return this.checkValidations(e,this.chainValidations(this.checkFigureArguments,this.validateChartDefinition,this.checkChartDuplicate));case`UPDATE_CHART`:return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartExists,this.checkChartChanged));case`DELETE_CHART`:return this.checkChartExists(e);default:return`Success`}}handle(e){switch(e.type){case`CREATE_CHART`:let{col:t,row:n,offset:r,size:i,sheetId:a,figureId:o}=e;!this.getters.getFigure(a,o)&&r!==void 0&&t!==void 0&&n!==void 0&&this.addFigure(o,a,t,n,r,i),this.addChart(e.figureId,e.chartId,e.definition);break;case`UPDATE_CHART`:this.addChart(e.figureId,e.chartId,e.definition);break;case`DUPLICATE_SHEET`:for(let t of this.getChartIds(e.sheetId)){let{chart:n,figureId:r}=this.charts[t]||{};if(!n||!r)continue;let i=this.getters.getFigure(e.sheetId,r);if(!i)continue;let a=r.split(`??`).pop(),o=`${e.sheetIdTo}??${a}`,s=t.split(`??`).pop(),c=`${e.sheetIdTo}??${s}`,l=n.duplicateInDuplicatedSheet(e.sheetIdTo);l&&this.dispatch(`CREATE_CHART`,{figureId:o,chartId:c,col:i.col,row:i.row,offset:i.offset,size:{width:i.width,height:i.height},definition:l.getDefinition(),sheetId:e.sheetIdTo})}break;case`DELETE_FIGURE`:for(let t in this.charts)this.charts[t]?.figureId===e.figureId&&this.dispatch(`DELETE_CHART`,{chartId:t,sheetId:e.sheetId});break;case`DELETE_CHART`:this.isChartDefined(e.chartId)&&this.history.update(`charts`,e.chartId,void 0);break;case`DELETE_SHEET`:for(let t of this.getChartIds(e.sheetId))this.history.update(`charts`,t,void 0);break}}getContextCreationChart(e){return this.charts[e]?.chart.getContextCreation()}getChart(e){return this.charts[e]?.chart}getFigureIdFromChartId(e){if(!this.charts[e])throw Error(`Chart with id ${e} does not exist.`);return this.charts[e].figureId}getChartType(e){let t=this.charts[e]?.chart.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?.chart.sheetId===e).map(([e])=>e)}getChartDefinition(e){let t=this.charts[e]?.chart.getDefinition();if(!t)throw Error(`There is no chart with the given id: ${e}`);return t}import(e){for(let t of e.sheets)if(t.figures){for(let e of t.figures)if(e.tag===`chart`){let n=e.data.chartId,r=this.createChart(e.id,e.data,t.id);this.charts[n]={chart:r,figureId:e.id}}else if(e.tag===`carousel`)for(let n in e.data.chartDefinitions||{}){let r=e.data.chartDefinitions[n],i=this.createChart(e.id,r,t.id);this.charts[n]={chart:i,figureId:e.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,r=Object.keys(this.charts).find(e=>this.charts[e]?.figureId===t.id);if(e&&e.tag===`chart`&&r){let t=this.charts[r]?.chart.getDefinition();t&&(e.data={...t,chartId:r},n.push(e))}else if(e&&e.tag===`carousel`){let r=Object.keys(this.charts).filter(e=>this.charts[e]?.figureId===t.id),i={};for(let e of r)i[e]=this.charts[e]?.chart.getDefinition();e.data={chartDefinitions:i},n.push(e)}else n.push(e)}t.figures=n}}addFigure(e,t,n,r,i,a={width:536,height:335}){this.dispatch(`CREATE_FIGURE`,{sheetId:t,figureId:e,col:n,row:r,offset:i,size:a,tag:`chart`})}addChart(e,t,n){let r=this.getters.getFigureSheetId(e);if(r){let i=this.createChart(e,n,r);this.history.update(`charts`,t,{figureId:e,chart:i})}}checkChartDuplicate(e){return this.isChartDefined(e.chartId)?`DuplicatedChartId`:`Success`}checkChartExists(e){return this.isChartDefined(e.chartId)?`Success`:`ChartDoesNotExist`}checkChartChanged(e){return e.figureId===this.charts[e.chartId]?.figureId&&w(this.getChartDefinition(e.chartId),e.definition)?`NoChanges`:`Success`}checkFigureArguments(e){return this.getters.getFigure(e.sheetId,e.figureId)||e.offset!==void 0&&e.col!==void 0&&e.row!==void 0?`Success`:`MissingFigureArguments`}};function vW(e){return e===``?NaN:Number(e)}var yW=class extends dW{static getters=[`getConditionalFormats`,`getRulesSelection`,`getRulesByCell`,`getAdaptedCfRanges`];cfRules={};adaptCFFormulas({applyChange:e,adaptFormulaString:t}){for(let n in this.cfRules)for(let r of this.cfRules[n])if(r.rule.type===`DataBarRule`&&r.rule.rangeValues){let t=e(r.rule.rangeValues);switch(t.changeType){case`REMOVE`:this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`rangeValues`,void 0);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`rangeValues`,t.range);break}}else if(r.rule.type===`CellIsRule`)for(let e=0;e<r.rule.values.length;e++)this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`values`,e,t(n,r.rule.values[e]));else if(r.rule.type===`IconSetRule`)for(let e of[`lowerInflectionPoint`,`upperInflectionPoint`])r.rule[e].type===`formula`&&this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,e,`value`,t(n,r.rule[e].value));else if(r.rule.type===`ColorScaleRule`)for(let e of[`minimum`,`maximum`,`midpoint`]){let i=r.rule[e];i?.type===`formula`&&i?.value&&this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,e,`value`,t(n,i.value))}}adaptCFRanges(e,{applyChange:t}){for(let n of this.cfRules[e])for(let r of n.ranges){let i=t(r);switch(i.changeType){case`REMOVE`:let t=n.ranges.slice();t.splice(n.ranges.indexOf(r),1),t.length>=1?this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,t):this.removeConditionalFormatting(n.id,e);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,n.ranges.indexOf(r),i.range);break}}}adaptRanges(e,t){let n=t?[t]:Object.keys(this.cfRules);for(let t of n)this.adaptCFRanges(t,e);this.adaptCFFormulas(e)}allowDispatch(e){switch(e.type){case`ADD_CONDITIONAL_FORMAT`:return e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkValidations(e,this.checkCFRule,this.checkEmptyRange,this.checkCFHasChanged);case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:return this.checkValidPriorityChange(e.cfId,e.delta,e.sheetId)}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.cfRules[e.sheetId]=[];break;case`DUPLICATE_SHEET`:this.history.update(`cfRules`,e.sheetIdTo,[]);for(let t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case`DELETE_SHEET`:let t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update(`cfRules`,t);break;case`ADD_CONDITIONAL_FORMAT`:let n={...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))};this.addConditionalFormatting(n,e.sheetId);break;case`REMOVE_CONDITIONAL_FORMAT`:this.removeConditionalFormatting(e.id,e.sheetId);break;case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:this.changeCFPriority(e.cfId,e.delta,e.sheetId);break}}import(e){for(let t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map(e=>this.mapToConditionalFormatInternal(t.id,e))}export(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e)))}exportForExcel(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e,{useBoundedReference:!0})))}getConditionalFormats(e){return this.cfRules[e]?.map(t=>this.mapToConditionalFormat(e,t))||[]}getRulesSelection(e,t){let n=new Set;return t.forEach(t=>{this.getRulesByZone(e,t).forEach(e=>{n.add(e)})}),Array.from(n)}getRulesByZone(e,t){let n=new Set;for(let r=t.top;r<=t.bottom;r++)for(let i=t.left;i<=t.right;i++)this.getRulesByCell(e,i,r).forEach(e=>{n.add(e.id)});return n}getRulesByCell(e,t,n){let r=[];for(let i of this.cfRules[e])for(let e of i.ranges)En(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(ln));let s=Qt(o,r);return Qt([...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 Nm.has(t.operator)?this.checkValidations(t,this.checkOperatorArgsNumber,this.checkCFValues):`InvalidConditionalFormatType`;case`ColorScaleRule`:return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case`IconSetRule`:return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)));case`DataBarRule`:return`Success`}return`InvalidConditionalFormatType`}checkCFHasChanged(e){let t=this.mapToConditionalFormatInternal(e.sheetId,{...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))}),n=this.cfRules[e.sheetId]?.find(t=>t.id===e.cf.id);return n&&w(t,n)?`NoChanges`:`Success`}checkOperatorArgsNumber(e){let t=W.get(e.operator).numberOfValues({type:e.operator,values:e.values});if(t===void 0||t>2)throw Error(`Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.`);let n=[],r=e=>e===void 0||e===``;return t>=1&&r(e.values[0])&&n.push(`FirstArgMissing`),t>=2&&r(e.values[1])&&n.push(`SecondArgMissing`),n.length?n:`Success`}checkNaN(e,t){if([`number`,`percentage`,`percentile`].includes(e.type)&&(e.value===``||isNaN(e.value)))switch(t){case`min`:return`MinNaN`;case`max`:return`MaxNaN`;case`mid`:return`MidNaN`;case`upperInflectionPoint`:return`ValueUpperInflectionNaN`;case`lowerInflectionPoint`:return`ValueLowerInflectionNaN`}return`Success`}checkFormulaCompilation(e,t){if(e.type!==`formula`)return`Success`;if(lU(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&&vW(t)>=vW(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&&vW(t)>=vW(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&&vW(t)>=vW(n)?`MinBiggerThanMid`:`Success`}checkCFValues(e){for(let t of e.values)if(t.startsWith(`=`)&&lU(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)}},bW=class extends dW{static getters=[`cellHasListDataValidationIcon`,`getDataValidationRule`,`getDataValidationRules`,`getValidationRuleForCell`];rules={};adaptRanges(e,t){this.adaptDVRanges(t,e),this.adaptDVFormulas(e)}adaptDVFormulas({adaptFormulaString:e}){for(let t in this.rules){let n=this.rules[t];for(let r=n.length-1;r>=0;r--){let n=this.rules[t][r];for(let i=0;i<n.criterion.values.length;i++){let a=e(t,n.criterion.values[i]);this.history.update(`rules`,t,r,`criterion`,`values`,i,a)}}}}adaptDVRanges(e,{applyChange:t}){let n=this.rules[e];for(let r=n.length-1;r>=0;r--){let n=this.rules[e][r];for(let i=n.ranges.length-1;i>=0;i--){let a=n.ranges[i],o=t(a);switch(o.changeType){case`REMOVE`:if(n.ranges.length===1)this.removeDataValidationRule(e,n.id);else{let t=n.ranges.slice();t.splice(i,1),this.history.update(`rules`,e,r,`ranges`,t)}break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`rules`,e,r,`ranges`,i,o.range);break}}}}allowDispatch(e){switch(e.type){case`ADD_DATA_VALIDATION_RULE`:return!this.getters.tryGetSheet(e.sheetId)||e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkValidations(e,this.chainValidations(this.checkEmptyRange,this.checkValidRange,this.checkCriterionTypeIsValid,this.checkCriterionHasValidNumberOfValues,this.checkCriterionValuesAreValid));case`REMOVE_DATA_VALIDATION_RULE`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;if(!this.rules[e.sheetId].find(t=>t.id===e.id))return`UnknownDataValidationRule`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`rules`,e.sheetId,[]);break;case`DUPLICATE_SHEET`:{let t=b(this.rules[e.sheetId]).map(t=>({...t,ranges:t.ranges.map(t=>Xc(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=Qt(e.target),n=e.sheetId;for(let e of t)for(let t=e.top;t<=e.bottom;t++)for(let r=e.left;r<=e.right;r++){let e=this.getValidationRuleForCell({sheetId:n,col:r,row:t});if(e&&(e.criterion.type===`isBoolean`||e.criterion.type===`isValueInList`&&!this.getters.getCell({sheetId:n,col:r,row:t})?.content)){let e=this.rules[n],i=[this.getters.getRangeFromSheetXC(n,T(r,t))],a=this.removeRangesFromRules(n,i,e);this.history.update(`rules`,n,a)}}}}}getDataValidationRules(e){return this.rules[e]}getDataValidationRule(e,t){return this.rules[e].find(e=>e.id===t)}getValidationRuleForCell({sheetId:e,col:t,row:n}){if(this.rules[e]){for(let r of this.rules[e])for(let e of r.ranges)if(En(t,n,e.zone))return r}}cellHasListDataValidationIcon(e){let t=this.getValidationRuleForCell(e);return t?(t.criterion.type===`isValueInList`||t.criterion.type===`isValueInRange`)&&(t.criterion.displayStyle===`arrow`||t.criterion.displayStyle===`chip`):!1}addDataValidationRule(e,t){let n=this.rules[e];t.criterion.type===`isBoolean`?this.setCenterStyleToBooleanCells(t):t.criterion.type===`isValueInList`&&(t.criterion.values=Array.from(new Set(t.criterion.values)));let r=this.removeRangesFromRules(e,t.ranges,n,t.id),i=r.findIndex(e=>e.id===t.id);i===-1?this.history.update(`rules`,e,[...r,t]):(r[i]=t,this.history.update(`rules`,e,r))}removeRangesFromRules(e,t,n,r){n=b(n);for(let e of n)e.id!==r&&(e.ranges=this.getters.recomputeRanges(e.ranges,t));return n.filter(e=>e.ranges.length>0)}removeDataValidationRule(e,t){let n=this.rules[e].filter(e=>e.id!==t);this.history.update(`rules`,e,n)}setCenterStyleToBooleanCells(e){for(let t of Qc(e.ranges)){let e=this.getters.getCellStyle(t),n={...e,align:e?.align??`center`,verticalAlign:e?.verticalAlign??`middle`};this.dispatch(`UPDATE_CELL`,{...t,style:n})}}checkEmptyRange(e){return e.ranges.length?`Success`:`EmptyRange`}import(e){for(let t of e.sheets)if(this.rules[t.id]=[],t.dataValidationRules)for(let e of t.dataValidationRules)this.rules[t.id].push({...e,ranges:e.ranges.map(e=>this.getters.getRangeFromSheetXC(t.id,e))})}export(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id])t.dataValidationRules.push({...e,ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id))})}}exportForExcel(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id]){let n={...b(e),ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id,{useBoundedReference:!0}))};e.criterion.type===`isValueInRange`&&(n.criterion.values=e.criterion.values.map(e=>{let n=this.getters.getRangeFromSheetXC(t.id,e);return this.getters.getRangeString(n,t.id,{useBoundedReference:!0,useFixedReference:!0})})),t.dataValidationRules.push(n)}}}checkCriterionTypeIsValid(e){return W.contains(e.rule.criterion.type)?`Success`:`UnknownDataValidationCriterionType`}checkCriterionHasValidNumberOfValues(e){let t=e.rule.criterion,n=W.get(t.type).numberOfValues(t);return n!==void 0&&t.values.length!==n?`InvalidNumberOfCriterionValues`:`Success`}checkCriterionValuesAreValid(e){let t=e.rule.criterion,n=W.get(t.type);return t.values.some(e=>n.allowedValues===`onlyFormulas`&&!e.startsWith(`=`)?!0:e.startsWith(`=`)?n.allowedValues===`onlyLiterals`||lU(e).isBadExpression:!n.isCriterionValueValid(e))?`InvalidDataValidationCriterionValue`:`Success`}checkValidRange(e){return e.ranges.map(e=>this.getters.getRangeFromRangeData(e)).map(t=>this.getters.getRangeString(t,e.sheetId)).some(e=>!this.getters.isRangeValid(e))?`InvalidRange`:`Success`}},xW=class extends dW{static getters=[`getFigures`,`getFigure`,`getFigureSheetId`];figures={};insertionOrders=[];adaptRanges({applyChange:e},t){for(let n of this.getFigures(t)){let r=e(this.getters.getRangeFromZone(t,{left:n.col,right:n.col,top:n.row,bottom:n.row}));if(r.changeType===`MOVE`)this.history.update(`figures`,t,n.id,`col`,r.range.zone.right),this.history.update(`figures`,t,n.id,`row`,r.range.zone.bottom);else if(r.changeType===`REMOVE`){let r=e(this.getters.getRangeFromZone(t,{left:0,right:n.col-1,top:0,bottom:n.row-1})),{offset:i,col:a,row:o}=n;r.changeType!==`NONE`&&(a=r.range.zone.right+1,o=r.range.zone.bottom+1),{offset:i,col:a,row:o}=this.getPositionInSheet(t,{...n,col:a,row:o}),this.history.update(`figures`,t,n.id,`offset`,i),this.history.update(`figures`,t,n.id,`col`,a),this.history.update(`figures`,t,n.id,`row`,o)}}}allowDispatch(e){switch(e.type){case`CREATE_FIGURE`:return this.checkValidations(e,this.checkFigureDuplicate,this.checkFigureAnchorOffset);case`UPDATE_FIGURE`:return this.checkValidations(e,this.checkFigureExists,this.checkFigureAnchorOffset);case`DELETE_FIGURE`:return this.checkFigureExists(e);default:return`Success`}}beforeHandle(e){switch(e.type){case`DELETE_SHEET`:this.getters.getFigures(e.sheetId).forEach(t=>{this.dispatch(`DELETE_FIGURE`,{figureId:t.id,sheetId:e.sheetId})});break}}handle(e){switch(e.type){case`CREATE_SHEET`:this.figures[e.sheetId]={};break;case`DELETE_SHEET`:this.deleteSheet(e.sheetId);break;case`CREATE_FIGURE`:let t={id:e.figureId,col:e.col,row:e.row,offset:e.offset,width:e.size.width,height:e.size.height,tag:e.tag};this.addFigure(t,e.sheetId);break;case`UPDATE_FIGURE`:this.updateFigure(e);break;case`DELETE_FIGURE`:this.removeFigure(e.figureId,e.sheetId);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.onColRemove(e.sheetId):this.onRowRemove(e.sheetId);break;case`DUPLICATE_SHEET`:for(let t of this.getFigures(e.sheetId)){let n=t.id,r=this.figures[e.sheetId]?.[n];if(!r)continue;let i=n.split(`??`).pop(),a=`${e.sheetIdTo}??${i}`;this.dispatch(`CREATE_FIGURE`,{figureId:a,...r,size:{width:r.width,height:r.height},sheetId:e.sheetIdTo})}break}}onColRemove(e){let t=this.getters.getNumberCols(e),n=Array(t+1);n[t]=0;for(let r=t-1;r>=0;r--)n[r]=n[r+1]+this.getters.getColSize(e,r);for(let t of this.getFigures(e))if(t.offset.x+t.width>n[t.col]){let r=t.offset.x,i=t.col;for(r=Math.min(r,n[i]-t.width);r<0&&i>0;)i--,r=n[i]-t.width;r!==t.offset.x&&this.history.update(`figures`,e,t.id,`offset`,{x:Math.max(r,0),y:t.offset.y}),i!==t.col&&this.history.update(`figures`,e,t.id,`col`,i)}}onRowRemove(e){let t=this.getters.getNumberRows(e),n=Array(t+1);n[t]=0;for(let r=t-1;r>=0;r--)n[r]=n[r+1]+(this.getters.getUserRowSize(e,r)??23);for(let t of this.getFigures(e))if(t.offset.y+t.height>n[t.row]){let r=t.offset.y,i=t.row;for(let t=this.getters.getUserRowSize(e,i)??23;t<r;t=this.getters.getUserRowSize(e,i)??23)i+=1,r-=t;for(r=Math.min(r,n[i]-t.height);r<0&&i>0;)i--,r=n[i]-t.height;r!==t.offset.y&&this.history.update(`figures`,e,t.id,`offset`,{x:t.offset.x,y:Math.max(0,r)}),i!==t.row&&this.history.update(`figures`,e,t.id,`row`,i)}else t.offset.y+t.height>n[0]&&this.history.update(`figures`,e,t.id,`offset`,{x:t.offset.x,y:Math.max(n[0]-t.height,0)})}getPositionInSheet(e,t){let{numberOfRows:n,numberOfCols:r}=this.getters.getSheetSize(e),i=0,a=0,o,s,{col:c,row:l}=t,u={...t.offset};for(o=n;i<t.height&&o>0;o--)i+=this.getters.getUserRowSize(e,o-1)??23;for(l>o?(l=o,u.y=Math.max(i-t.height,0)):l===o&&(u.y=x(u.y,0,Math.max(i-t.height,0))),s=r;a<t.width&&s>0;s--)a+=this.getters.getColSize(e,s-1);return c>s?(c=s,u.x=Math.max(a-t.width,0)):s===c&&(u.x=x(u.x,0,Math.max(a-t.width,0))),{col:c,row:l,offset:u}}updateFigure(e){if(!(`figureId`in e)||!(`sheetId`in e))return;let{figureId:t,sheetId:n,...r}=e,i={...this.getFigure(n,t),...r};for(let[e,t]of Object.entries(r))switch(e){case`tag`:this.history.update(`figures`,n,i.id,e,t);break;case`offset`:this.history.update(`figures`,n,i.id,e,t);break;case`col`:case`row`:case`width`:case`height`:t!==void 0&&this.history.update(`figures`,n,i.id,e,t);break}}addFigure(e,t){this.history.update(`figures`,t,e.id,e),this.history.update(`insertionOrders`,this.insertionOrders.length,e.id)}deleteSheet(e){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>!this.figures[e]?.[t])),this.history.update(`figures`,e,void 0)}removeFigure(e,t){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>t!==e)),this.history.update(`figures`,t,e,void 0)}checkFigureExists(e){return this.figures[e.sheetId]?.[e.figureId]===void 0?`FigureDoesNotExist`:`Success`}checkFigureDuplicate(e){return Object.values(this.figures).find(t=>t?.[e.figureId])?`DuplicatedFigureId`:`Success`}checkFigureAnchorOffset(e){return e.col<0||e.row<0||e.offset&&(e.offset.x<0||e.offset.y<0)?`WrongSheetPosition`:`Success`}getFigures(e){let t=[];for(let n of this.insertionOrders){let r=this.figures[e]?.[n];r&&t.push(r)}return t}getFigure(e,t){return this.figures[e]?.[t]}getFigureSheetId(e){return Object.keys(this.figures).find(t=>this.figures[t]?.[e]!==void 0)}import(e){for(let t of e.sheets)for(let e of t.figures)this.addFigure(e,t.id)}export(e){for(let t of e.sheets)for(let e of this.getFigures(t.id))t.figures.push({...e,data:void 0})}exportForExcel(e){return this.export(e)}},SW=class extends dW{static getters=[`getHeaderGroups`,`getGroupsLayers`,`getVisibleGroupLayers`,`getHeaderGroup`,`getHeaderGroupsInZone`,`isGroupFolded`,`isRowFolded`,`isColFolded`];groups={};allowDispatch(e){switch(e.type){case`GROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;if(this.findGroupWithStartEnd(e.sheetId,e.dimension,t,n))return`HeaderGroupAlreadyExists`;break}case`UNGROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;break}case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUP`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);if(!t)return`UnknownHeaderGroup`;if(S(0,this.getters.getNumberHeaders(e.sheetId,e.dimension)).every(n=>n>=t.start&&n<=t.end||this.getters.isHeaderHiddenByUser(e.sheetId,e.dimension,n)))return`NotEnoughElements`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`groups`,e.sheetId,{ROW:[],COL:[]});break;case`GROUP_HEADERS`:this.groupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`UNGROUP_HEADERS`:this.unGroupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`DUPLICATE_SHEET`:{let t=b(this.groups[e.sheetId]);this.history.update(`groups`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.groups};delete t[e.sheetId],this.history.update(`groups`,t);break}case`ADD_COLUMNS_ROWS`:let t=gt(e.position,e.base);this.moveGroupsOnHeaderInsertion(e.sheetId,e.dimension,t,e.quantity);break;case`REMOVE_COLUMNS_ROWS`:this.moveGroupsOnHeaderDeletion(e.sheetId,e.dimension,e.elements);break;case`UNFOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.unfoldHeaderGroup(e.sheetId,e.dimension,t);break}case`FOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.foldHeaderGroup(e.sheetId,e.dimension,t);break}case`UNFOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.unfoldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.foldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:{let t=e.type===`UNFOLD_HEADER_GROUPS_IN_ZONE`?`unfold`:`fold`,n=this.getGroupsLayers(e.sheetId,e.dimension);t===`fold`&&n.reverse();let r=n.flat(),i=e.dimension===`ROW`?e.zone.top:e.zone.left,a=e.dimension===`ROW`?e.zone.bottom:e.zone.right,o=new Set;for(let e=i;e<=a;e++){let n=r.filter(t=>t.start-1<=e&&e<=t.end);for(let e of n)if(!(t===`fold`&&e.isFolded||t===`unfold`&&!e.isFolded)){o.add(e);break}}for(let n of o)t===`unfold`?this.unfoldHeaderGroup(e.sheetId,e.dimension,n):this.foldHeaderGroup(e.sheetId,e.dimension,n);break}}}getHeaderGroups(e,t){return this.groups[e][t]}getHeaderGroup(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}getHeaderGroupsInZone(e,t,n){return this.getHeaderGroups(e,t).filter(e=>{let r=t===`ROW`?n.top:n.left,i=t===`ROW`?n.bottom:n.right;return this.doGroupOverlap(e,r,i)})}getGroupsLayers(e,t){let n=this.getHeaderGroups(e,t);return this.bricksFallingAlgorithm(n,0,0)}getVisibleGroupLayers(e,t){let n=this.getGroupsLayers(e,t);for(let r of n)for(let n=r.length-1;n>=0;n--){let i=r[n];i.start!==0&&S(i.start-1,i.end+1).every(n=>this.getters.isHeaderHiddenByUser(e,t,n))&&r.splice(n,1)}return n.filter(e=>e.length>0)}isGroupFolded(e,t,n,r){return this.getHeaderGroup(e,t,n,r)?.isFolded||!1}isRowFolded(e,t){return this.getters.getHeaderGroups(e,`ROW`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}isColFolded(e,t){return this.getters.getHeaderGroups(e,`COL`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}getGroupId(e){return`${e.start}-${e.end}}`}bricksFallingAlgorithm(e,t,n,r=0){let i={};for(let t of e)i[this.getGroupId(t)]=t.isFolded;let a={};for(let t of e)for(let e=t.start;e<=t.end;e++)a[e]=a[e]?a[e]+1:1;for(let e=t;e<=n;e++)a[e]=a[e]?a[e]+r:r;let o=Math.max(...Object.values(a),0),s=Array.from({length:o},()=>[]),c=Math.max(n,...e.map(e=>e.end)),l=Math.min(t,...e.map(e=>e.start));for(let e=l;e<=c;e++){let t=a[e]||0;for(let n=0;n<t;n++){let t=s[n].at(-1);if(t&&Et([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]=ml(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=hl(n,S(e.start,e.end+1));t.length!==0&&i.push({...e,start:Math.min(...t),end:Math.max(...t)})}this.history.update(`groups`,e,t,this.bricksFallingAlgorithm(i,0,0).flat())}doGroupOverlap(e,t,n){return e.start<=n&&e.end>=t}removeDuplicateGroups(e){let t={};for(let n of e)t[this.getGroupId(n)]=n;return Object.values(t)}findGroupWithStartEnd(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}foldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!0);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end<=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!0)}}unfoldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!1);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end>=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!1)}}getGroupIndex(e,t,n,r){let i=this.groups[e][t].findIndex(e=>e.start===n&&e.end===r);return i===-1?void 0:i}import(e){for(let t of e.sheets)if(this.groups[t.id]={ROW:[],COL:[]},t.headerGroups)for(let e of[`ROW`,`COL`])for(let n of t.headerGroups[e]||[])this.groups[t.id][e].push({...n})}export(e){for(let t of e.sheets)t.headerGroups=this.groups[t.id]}exportForExcel(e){for(let t of e.sheets)for(let e of[`ROW`,`COL`]){let n=this.getGroupsLayers(t.id,e);for(let r=0;r<n.length;r++){let i=n[r];for(let n of i){for(let i=n.start;i<=n.end;i++){let a=hj(t,e,i);a.outlineLevel=r+1,n.isFolded&&(a.isHidden=!0)}if(n.isFolded){let r=hj(t,e,n.end+1);r.collapsed=!0}}}}}},CW=class extends dW{static getters=[`getUserRowSize`,`getColSize`];sizes={};handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`sizes`,e.sheetId,{COL:Array(this.getters.getNumberCols(e.sheetId)).fill(void 0),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(void 0)});break;case`DUPLICATE_SHEET`:this.history.update(`sizes`,e.sheetIdTo,b(this.sizes[e.sheetId]));break;case`DELETE_SHEET`:let t={...this.sizes};delete t[e.sheetId],this.history.update(`sizes`,t);break;case`REMOVE_COLUMNS_ROWS`:{let t=this.sizes[e.sheetId][e.dimension],n=Ot(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=gt(e.position,e.base),r=t[e.base],i=kt(t,Array(e.quantity).fill(r),n);this.history.update(`sizes`,e.sheetId,e.dimension,i);break}case`RESIZE_COLUMNS_ROWS`:if(e.dimension===`ROW`)for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);else for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);break}}getColSize(e,t){return Math.round(this.sizes[e]?.COL[t]||96)}getUserRowSize(e,t){let n=this.sizes[e]?.ROW[t];return n?Math.round(n):void 0}import(e){for(let t of e.sheets){let e={COL:Array(t.colNumber).fill(void 0),ROW:Array(t.rowNumber).fill(void 0)};for(let[n,r]of Object.entries(t.rows))r.size&&(e.ROW[n]=r.size);for(let[n,r]of Object.entries(t.cols))r.size&&(e.COL[n]=r.size);this.sizes[t.id]=e}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e of S(0,this.getters.getNumberRows(n.id)))(t||this.sizes[n.id].ROW[e])&&(n.rows[e]={...n.rows[e],size:this.getUserRowSize(n.id,e)??23});n.cols===void 0&&(n.cols={});for(let e of S(0,this.getters.getNumberCols(n.id)))(t||this.sizes[n.id].COL[e])&&(n.cols[e]={...n.cols[e],size:this.getColSize(n.id,e)})}}},wW=class extends dW{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`:Ft(e.elements)<0||Pt(e.elements)>n?`InvalidHeaderIndex`:`Success`}case`REMOVE_COLUMNS_ROWS`:return this.getters.tryGetSheet(e.sheetId)?this.checkElementsIncludeAllVisibleHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`:`InvalidSheetId`}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:let t={COL:Array(this.getters.getNumberCols(e.sheetId)).fill(!1),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(!1)};this.history.update(`hiddenHeaders`,e.sheetId,t);break;case`DUPLICATE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetIdTo,b(this.hiddenHeaders[e.sheetId]));break;case`DELETE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetId,void 0);break;case`REMOVE_COLUMNS_ROWS`:{let t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(let n of[...e.elements].sort((e,t)=>t-e))t.splice(n,1);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t);break}case`ADD_COLUMNS_ROWS`:{let t=gt(e.position,e.base),n=kt([...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 yt(n,this.getAllVisibleHeaders(e,t))}isHeaderHiddenByUser(e,t,n){return t===`COL`?this.isColHiddenByUser(e,n):this.isRowHiddenByUser(e,n)}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]||this.getters.isRowFolded(e,t)}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]||this.getters.isColFolded(e,t)}getHiddenColsGroups(e){let t=[[]],n=this.hiddenHeaders[e].COL;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getHiddenRowsGroups(e){let t=[[]],n=this.hiddenHeaders[e].ROW;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getAllVisibleHeaders(e,t){let n=S(0,this.getters.getNumberHeaders(e,t)),r=[];return this.getters.getHeaderGroups(e,t).forEach(e=>{e.isFolded&&r.push(...S(e.start,e.end+1))}),n.filter(n=>!this.hiddenHeaders[e][t][n]&&!r.includes(n))}import(e){for(let t of e.sheets){this.hiddenHeaders[t.id]={COL:[],ROW:[]};for(let e=0;e<t.rowNumber;e++)this.hiddenHeaders[t.id].ROW[e]=!!t.rows[e]?.isHidden;for(let e=0;e<t.colNumber;e++)this.hiddenHeaders[t.id].COL[e]=!!t.cols[e]?.isHidden}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e=0;e<this.getters.getNumberRows(n.id);e++)(t||this.hiddenHeaders[n.id].ROW[e])&&(n.rows[e]===void 0&&(n.rows[e]={}),n.rows[e].isHidden||=this.hiddenHeaders[n.id].ROW[e]);n.cols===void 0&&(n.cols={});for(let e=0;e<this.getters.getNumberCols(n.id);e++)(t||this.hiddenHeaders[n.id].COL[e])&&(n.cols[e]===void 0&&(n.cols[e]={}),n.cols[e].isHidden||=this.hiddenHeaders[n.id].COL[e])}}},TW=class extends dW{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.getters.getFigure(e.sheetId,e.figureId)||this.addFigure(e.figureId,e.sheetId,e.col,e.row,e.offset,e.size),this.history.update(`images`,e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`image`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.getImage(n.id);if(i){let t={width:n.width,height:n.height};this.dispatch(`CREATE_IMAGE`,{sheetId:e.sheetIdTo,figureId:r,offset:n.offset,col:n.col,row:n.row,size:t,definition:b(i)})}}break}case`DELETE_FIGURE`:this.history.update(`images`,e.sheetId,e.figureId,void 0);break;case`DELETE_SHEET`:this.history.update(`images`,e.sheetId,void 0);break}}getImage(e){for(let t of Object.values(this.images))if(t&&t[e])return t[e];throw Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addFigure(e,t,n,r,i,a){this.dispatch(`CREATE_FIGURE`,{sheetId:t,figureId:e,col:n,row:r,offset:i,size:a,tag:`image`})}import(e){for(let t of e.sheets){let e=(t.figures||[]).filter(e=>e.tag===`image`);for(let n of e)this.history.update(`images`,t.id,n.id,n.data),this.syncedImages.add(n.data.path)}}export(e){for(let t of e.sheets){let e=t.figures.filter(e=>e.tag===`image`);for(let n of e)n.data=this.images[t.id]?.[n.id]}}exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let t of e)if(t?.tag===`image`){let e=this.getImage(t.id);e&&n.push({...t,data:b(e)})}t.images=[...t.images,...n]}}},EW=class extends dW{static getters=[`isInMerge`,`isInSameMerge`,`isMergeHidden`,`getMainCellPosition`,`expandZone`,`doesIntersectMerge`,`doesColumnsHaveCommonMerges`,`doesRowsHaveCommonMerges`,`getMerges`,`getMerge`,`getMergesInZone`,`isSingleCellOrMerge`,`getSelectionRangeString`,`isMainCellPosition`];nextId=1;merges={};mergeCellMap={};allowDispatch(e){let t=`force`in e?!!e.force:!1;switch(e.type){case`ADD_MERGE`:return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case`UPDATE_CELL`:return this.checkMergedContentUpdate(e);case`REMOVE_MERGE`:return this.checkMergeExists(e);default:return`Success`}}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DELETE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DUPLICATE_SHEET`:let t=this.merges[e.sheetId];if(!t)break;for(let n of Object.values(t).filter(C))this.addMerge(e.sheetIdTo,n.zone);break;case`ADD_MERGE`:for(let t of e.target)this.addMerge(e.sheetId,t);break;case`REMOVE_MERGE`:for(let t of e.target)this.removeMerge(e.sheetId,t);break}}adaptRanges(e,t){this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map(t=>this.getMergeById(e,parseInt(t,10))).filter(C)}getMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e],i=r?t in r&&r[t]?.[n]:void 0;return i?this.getMergeById(e,i):void 0}getMergesInZone(e,t){let n=this.mergeCellMap[e];if(!n)return[];let r=new Set;for(let e=t.left;e<=t.right;e++)for(let i=t.top;i<=t.bottom;i++){let t=n[e]?.[i];t&&r.add(t)}return Array.from(r).map(t=>this.getMergeById(e,t)).filter(C)}getSelectionRangeString(e,t){let n=this.getters.expandZone(e.sheetId,e.zone),r=Wc({...e,zone:{...n,bottom:qc(e)?void 0:n.bottom,right:Jc(e)?void 0:n.right}},this.getters.getSheetSize),i=this.getters.getRangeString(r,t);if(this.isSingleCellOrMerge(e.sheetId,e.zone)){let{sheetName:e,xc:t}=Pc(i);return Fc(e,t.split(`:`)[0])}return i}doesIntersectMerge(e,t){for(let n of this.getMerges(e))if(wn(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&&wn(n,o)&&(o=bn(n,o))}return Cn(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:Cn(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 Cn(t,n);let{numberOfCols:r,numberOfRows:i}=On(t);return r===1&&i===1}isMainCellPosition(e){return w(this.getMainCellPosition(e),e)}isMergeDestructive(e,t){let{left:n,right:r,top:i,bottom:a}=t;r=x(r,0,this.getters.getNumberCols(e)-1),a=x(a,0,this.getters.getNumberRows(e)-1);for(let t=i;t<=a;t++)for(let a=n;a<=r;a++)if(a!==n||t!==i){let n=this.getters.getCell({sheetId:e,col:a,row:t});if(n&&n.content!==``)return!0}return!1}getMergeById(e,t){let n=this.merges[e]?.[t];return n===void 0?void 0:OW(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&&wn(t,n))return`MergeOverlap`;return`Success`}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return`Success`;let{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(e);return Un(t,n,r)?`FrozenPaneOverlap`:`Success`}checkMergedContentUpdate(e){let{col:t,row:n,content:r}=e;if(r===void 0)return`Success`;let{col:i,row:a}=this.getMainCellPosition(e);return i===t&&a===n?`Success`:`CellIsMerged`}checkMergeExists(e){let{sheetId:t,target:n}=e;for(let e of n){let{left:n,top:r}=e,i=this.getMerge({sheetId:t,col:n,row:r});if(i===void 0||!Cn(e,i))return`InvalidTarget`}return`Success`}addMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t;if(r=x(r,0,this.getters.getNumberCols(e)-1),a=x(a,0,this.getters.getNumberRows(e)-1),T(n,i)===T(r,a))return;let o=this.nextId++;this.history.update(`merges`,e,o,this.getters.getRangeFromSheetXC(e,hn({left:n,top:i,right:r,bottom:a})));let s=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,content:``});let r=this.getMerge({sheetId:e,col:a,row:t});r&&s.add(r.id),this.history.update(`mergeCellMap`,e,a,t,o)}for(let t of s){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!==o)&&(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||!Cn(t,o))){this.history.update(`merges`,e,o.id,void 0);for(let t=r;t<=i;t++)for(let r=n;r<=a;r++)this.history.update(`mergeCellMap`,e,r,t,void 0)}}applyRangeChangeOnSheet(e,{applyChange:t}){let n=Object.entries(this.merges[e]||{});for(let[r,i]of n)if(i){let n=i.zone,a=t(i);switch(a.changeType){case`NONE`:break;case`REMOVE`:this.removeMerge(e,n);break;default:let{numberOfCols:t,numberOfRows:i}=On(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 jn(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,un(n))}export(e){for(let t of e.sheets){let e=this.merges[t.id];e&&t.merges.push(...DW(e))}}exportForExcel(e){this.export(e)}};function DW(e){return Object.entries(e).map(([e,t])=>t?OW(parseInt(e,10),t):void 0).filter(C).map(e=>T(e.left,e.top)+`:`+T(e.right,e.bottom))}function OW(e,t){return{...t.zone,id:e}}var kW=class extends dW{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 e.pivotId in this.pivots?`PivotIdTaken`:this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid);case`UPDATE_PIVOT`:return e.pivotId in this.pivots?w(e.pivot,this.pivots[e.pivotId]?.definition)?`NoChanges`:e.pivot.name===``?`EmptyName`:this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid):`PivotIdNotFound`;case`RENAME_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;if(e.name===``)return`EmptyName`;break;case`REMOVE_PIVOT`:case`DUPLICATE_PIVOT`:case`INSERT_PIVOT`: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 zL(s,c,l,u||{}),f=this.getPivotFormulaId(i);this.insertPivot(o,f,d);break}case`RENAME_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,`name`,e.name);break;case`REMOVE_PIVOT`:{let t={...this.pivots};delete t[e.pivotId];let n=this.getPivotFormulaId(e.pivotId);this.history.update(`formulaIds`,n,void 0),this.history.update(`pivots`,t);break}case`DUPLICATE_PIVOT`:{let{pivotId:t,newPivotId:n}=e,r=b(this.getPivotCore(t).definition);r.name=e.duplicatedPivotName??r.name+` (copy)`,this.addPivot(n,r);break}case`UPDATE_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,b(e.pivot)),this.compileCalculatedMeasures(e.pivotId,e.pivot.measures);break}}adaptRanges({applyChange:e,adaptFormulaString:t}){for(let t in this.pivots){let n=b(this.pivots[t]?.definition);if(!n)continue;let r=ZL.get(n.type)?.adaptRanges?.(this.getters,n,e);r&&!w(n,r)&&this.history.update(`pivots`,t,`definition`,r)}for(let n in this.compiledMeasureFormulas)for(let r in this.compiledMeasureFormulas[n]){let i=this.pivots[n]?.definition.measures.find(e=>e.id===r);if(!i||!i.computedBy)continue;let a=i.computedBy.sheetId,{formula:o,dependencies:s}=this.compiledMeasureFormulas[n][r];this.history.update(`compiledMeasureFormulas`,n,r,`formula`,`dependencies`,o.dependencies.map(t=>e(t).range)),this.history.update(`compiledMeasureFormulas`,n,i.id,`dependencies`,s.map(t=>e(t).range));let c=i.computedBy.formula,l=t(a,c);l!==c&&this.replaceMeasureFormula(n,i,l)}}getPivotDisplayName(e){return`(#${this.getPivotFormulaId(e)}) ${this.getPivotName(e)}`}getPivotName(e){return this.getPivotCore(e).definition.name}getPivotCoreDefinition(e){return this.getPivotCore(e).definition}getPivotId(e){return this.formulaIds[e]}getPivotFormulaId(e){return this.getPivotCore(e).formulaId}getPivotIds(){return Object.keys(this.pivots)}isExistingPivot(e){return e in this.pivots}getMeasureCompiledFormula(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].formula}getMeasureFullDependencies(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].dependencies}addPivot(e,t,n=this.nextFormulaId.toString()){this.history.update(`pivots`,e,{definition:b(t),formulaId:n}),this.compileCalculatedMeasures(e,t.measures),this.history.update(`formulaIds`,n,e),this.history.update(`nextFormulaId`,this.nextFormulaId+1)}compileCalculatedMeasures(e,t){for(let n of t)if(n.computedBy){let t=this.compileMeasureFormula(n.computedBy.sheetId,n.computedBy.formula);this.history.update(`compiledMeasureFormulas`,e,n.id,`formula`,t)}for(let n of t)if(n.computedBy){let t=this.computeMeasureFullDependencies(e,n);this.history.update(`compiledMeasureFormulas`,e,n.id,`dependencies`,t)}}computeMeasureFullDependencies(e,t,n=new Set){let r=[],i=this.getPivotCoreDefinition(e),a=this.getMeasureCompiledFormula(e,t);n.add(t.id);for(let o of a.tokens){if(o.type!==`SYMBOL`)continue;let a=i.measures.find(e=>Ye(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:gh(t,a)})}}resizeSheet(e,{col:t,row:n},r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:s-l,position:`after`})}getPivotCore(e){let t=this.pivots[e];if(!t)throw Error(`Pivot with id ${e} not found`);return t}compileMeasureFormula(e,t){let n=lU(t),r=n.dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t));return{...n,dependencies:r}}replaceMeasureFormula(e,t,n){let r=this.pivots[e];if(!r)return;let i=r.definition.measures.indexOf(t);this.history.update(`pivots`,e,`definition`,`measures`,i,`computedBy`,{formula:n,sheetId:t.computedBy.sheetId})}checkSortedColumnInMeasures(e){let t=e.measures.map(e=>e.id);return e.sortedColumn&&!t.includes(e.sortedColumn.measure)?`InvalidDefinition`:`Success`}checkDuplicatedMeasureIds(e){let t=new Set(e.measures.map(e=>e.id));return e.measures.length===t.size?`Success`:`InvalidDefinition`}checkCustomFieldsAreValid(e){for(let t in e.customFields){let n=e.customFields[t],r=new Set,i=new Set,a=!1;for(let e of n.groups){if(!e.name||i.has(e.name)||e.values.some(e=>r.has(e))||e.isOtherGroup&&a)return`InvalidPivotCustomField`;e.values.forEach(e=>r.add(e)),i.add(e.name),a||=!!e.isOtherGroup}}return`Success`}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||lh(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}},AW=class extends dW{static getters=[`getLocale`];locale=R;allowDispatch(e){switch(e.type){case`UPDATE_LOCALE`:return Uv(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===oy(e)&&(n=oy(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??R}export(e){e.settings={locale:this.locale}}},jW=class extends dW{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||Tr(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=Ft(e.elements),n=Pt(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`}}beforeHandle(e){switch(e.type){case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break}}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`,vl(t.name),t.id);break;case`MOVE_SHEET`:this.moveSheet(e.sheetId,e.delta);break;case`RENAME_SHEET`:this.renameSheet(this.sheets[e.sheetId],e.newName);break;case`COLOR_SHEET`:this.history.update(`sheets`,e.sheetId,`color`,e.color);break;case`HIDE_SHEET`:this.hideSheet(e.sheetId);break;case`SHOW_SHEET`:this.showSheet(e.sheetId);break;case`DUPLICATE_SHEET`:this.duplicateSheet(e.sheetId,e.sheetIdTo,e.sheetNameTo);break;case`DELETE_SHEET`:this.deleteSheet(this.sheets[e.sheetId]);break;case`ADD_COLUMNS_ROWS`: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[vl(t.name)]=t.id;for(let t of e.sheets){let e=t.name||`Sheet`+(Object.keys(this.sheets).length+1),{colNumber:n,rowNumber:r}=this.getImportedSheetSize(t),i={id:t.id,name:e,numberOfCols:n,rows:pl(r),areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,panes:{xSplit:t.panes?.xSplit||0,ySplit:t.panes?.ySplit||0},color:t.color};this.orderedSheetIds.push(i.id),this.sheets[i.id]=i}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(C).map(e=>{let t=this.sheets[e],n={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},styles:{},formats:{},borders:{},conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,color:t.color};return(t.panes.xSplit||t.panes.ySplit)&&(n.panes=t.panes),n})}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){let t=this.sheets[e];if(!t)throw Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){return this.tryGetSheet(e)?.name}getSheetIdByName(e){if(e)return this.sheetIdsMapName[vl(e)]}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}doesHeaderExist(e,t,n){return t===`COL`?n>=0&&n<this.getNumberCols(e):n>=0&&n<this.getNumberRows(e)}doesHeadersExist(e,t,n){return n.every(n=>this.doesHeaderExist(e,t,n))}getCell({sheetId:e,col:t,row:n}){let r=this.tryGetSheet(e)?.rows[n]?.cells[t];if(r!==void 0)return this.getters.getCellById(r)}getColsZone(e,t,n){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:n}}getRowCells(e,t){return Object.values(this.getSheet(e).rows[t]?.cells).filter(C)}getRowsZone(e,t,n){return{top:t,bottom:n,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){let t=this.cellPosition[e];if(!t)throw Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return t===`COL`?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e=`Sheet`){return gl(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?yt(n,S(i,a)):!1}getCommandZones(e){let t=[];return`zone`in e&&t.push(e.zone),`target`in e&&t.push(...e.target),`ranges`in e&&t.push(...e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone)),`col`in e&&e.col!==void 0&&`row`in e&&e.row!==void 0&&t.push({top:e.row,left:e.col,bottom:e.row,right:e.col}),t}checkZonesExistInSheet(e,t){if(!t.every(pn))return`InvalidRange`;if(t.length){let n=this.getSheetZone(e);return t.every(e=>Dn(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:pl(r),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0}},o=this.orderedSheetIds.slice();o.splice(i,0,a.id);let s=this.sheets;return this.history.update(`orderedSheetIds`,o),this.history.update(`sheets`,Object.assign({},s,{[a.id]:a})),a}moveSheet(e,t){let n=this.orderedSheetIds.slice(),r=n.findIndex(t=>t===e),i=n.splice(r,1),a=this.findIndexOfTargetSheet(r,t);n.splice(a,0,i[0]),this.history.update(`orderedSheetIds`,n)}findIndexOfTargetSheet(e,t){for(;t!==0&&0<=e&&e<=this.orderedSheetIds.length;)t>0?(e++,this.isSheetVisible(this.orderedSheetIds[e])&&t--):t<0&&(e--,this.isSheetVisible(this.orderedSheetIds[e])&&t++);if(t===0)return e;throw Error(`There is not enough visible sheets`)}checkSheetName(e){let t=this.getters.tryGetSheetName(e.sheetId),n=e.type===`RENAME_SHEET`?e.newName:e.name;if(t!==void 0&&n===t)return`UnchangedSheetName`;let{orderedSheetIds:r,sheets:i}=this,a=n&&n.trim().toLowerCase();return r.find(t=>yl(i[t]?.name,a)&&t!==e.sheetId)?`DuplicatedSheetName`:Me.test(a)?`ForbiddenCharactersInSheetName`:`Success`}checkSheetPosition(e){let{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?`WrongSheetPosition`:`Success`}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkRowFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.top<e.quantity&&e.quantity<=n.bottom)return`MergeOverlap`;return`Success`}checkColFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.left<e.quantity&&e.quantity<=n.right)return`MergeOverlap`;return`Success`}isRenameAllowed(e){return e.newName&&e.newName.trim().toLowerCase()?this.checkSheetName(e):`MissingSheetName`}renameSheet(e,t){let n=e.name;this.history.update(`sheets`,e.id,`name`,t.trim());let r=Object.assign({},this.sheetIdsMapName);delete r[vl(n)],r[vl(t)]=e.id,this.history.update(`sheetIdsMapName`,r)}hideSheet(e){this.history.update(`sheets`,e,`isVisible`,!1)}showSheet(e){this.history.update(`sheets`,e,`isVisible`,!0)}duplicateSheet(e,t,n){let r=b(this.getSheet(e));r.id=t,r.name=n;for(let e=0;e<=r.numberOfCols;e++)for(let t=0;t<=r.rows.length;t++)r.rows[t]&&(r.rows[t].cells[e]=void 0);let i=this.orderedSheetIds.slice(),a=i.indexOf(e);i.splice(a+1,0,r.id),this.history.update(`orderedSheetIds`,i),this.history.update(`sheets`,Object.assign({},this.sheets,{[r.id]:r}));for(let t of Object.values(this.getters.getCells(e))){let{sheetId:e,col:n,row:i}=this.getCellPosition(t.id),a=this.getters.getCellStyle({sheetId:e,col:n,row:i});this.dispatch(`UPDATE_CELL`,{sheetId:r.id,col:n,row:i,content:t.content,format:t.format,style:a})}let o=Object.assign({},this.sheetIdsMapName);o[vl(r.name)]=r.id,this.history.update(`sheetIdsMapName`,o)}getDuplicateSheetName(e){return _l(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[vl(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 Ze(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(Zt),n=e.rowNumber,r=e.colNumber;for(let{col:e,row:i}of t)n=Math.max(n,i+1),r=Math.max(r,e+1);return{rowNumber:n,colNumber:r}}checkSheetExists(e){return e.type!==`CREATE_SHEET`&&`sheetId`in e&&this.sheets[e.sheetId]===void 0?`InvalidSheetId`:e.type===`CREATE_SHEET`&&this.sheets[e.sheetId]!==void 0?`DuplicatedSheetId`:`Success`}checkZonesAreInSheet(e){return`sheetId`in e?`ranges`in e&&e.ranges.some(e=>e._sheetId!==``&&!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkZonesExistInSheet(e.sheetId,this.getCommandZones(e)):`Success`}},MW=class extends dW{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||!pn(t)?`InvalidDataSet`:this.getters.checkZonesExistInSheet(n,[t])}return`Success`}};let NW={verticalAlign:`bottom`,wrapping:`overflow`,bold:!1,italic:!1,strikethrough:!1,underline:!1,fontSize:10,fillColor:``,textColor:``};var PW=class extends dW{static getters=[`getCellStyle`,`getCellStyleInZone`,`getZoneStyles`,`getStyleColors`];styles={};allowDispatch(e){switch(e.type){case`SET_FORMATTING`:return this.checkUselessSetFormatting(e)}return`Success`}handle(e){switch(e.type){case`ADD_MERGE`:for(let t of e.target)this.onMerge(e.sheetId,t);break;case`SET_FORMATTING`:e.style!==void 0&&(e.style===null?this.clearStyle(e.sheetId,e.target):this.setStyles(e.sheetId,e.target,e.style));break;case`CLEAR_FORMATTING`:this.clearStyle(e.sheetId,e.target);break;case`UPDATE_CELL`:e.style!==void 0&&(e.style===null?this.clearStyle(e.sheetId,[E(e)]):this.setStyles(e.sheetId,[E(e)],e.style,{force:!0}));break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumnn(e):this.handleAddRows(e);break;case`CLEAR_CELL`:this.clearStyle(e.sheetId,[E(e)]);break;case`CLEAR_CELLS`:this.clearStyle(e.sheetId,e.target);break;case`DELETE_SHEET`:this.history.update(`styles`,e.sheetId,void 0);break}}adaptRanges({applyChange:e},t){let n=[];for(let r of this.styles[t]??[]){let i=e(this.getters.getRangeFromZone(t,r.zone));switch(i.changeType){case`RESIZE`:case`CHANGE`:case`MOVE`:n.push({style:r.style,zone:i.range.unboundedZone});break;case`NONE`:n.push(r);break}}this.history.update(`styles`,t,n)}handleAddColumnn(e){let t=this.styles[e.sheetId]??[];for(let n=0;n<t.length;n++){let r=t[n];r.zone.left-e.quantity===e.base&&e.position===`before`?this.history.update(`styles`,e.sheetId,n,`zone`,`left`,r.zone.left-e.quantity):r.zone.right===e.base&&e.position===`after`&&this.history.update(`styles`,e.sheetId,n,`zone`,`right`,r.zone.right+e.quantity)}}handleAddRows(e){let t=this.styles[e.sheetId]??[];for(let n=0;n<t.length;n++){let r=t[n];r.zone.top-e.quantity===e.base&&e.position===`before`?this.history.update(`styles`,e.sheetId,n,`zone`,`top`,r.zone.top-e.quantity):r.zone.bottom===e.base&&e.position===`after`&&this.history.update(`styles`,e.sheetId,n,`zone`,`bottom`,r.zone.bottom+e.quantity)}}styleIsDefault(e){for(let t in e)if(NW[t]!==e[t])return!1;return!0}removeDefaultStyleValues(e){let t={...e};for(let n in e)(t[n]===void 0||t[n]===NW[n])&&delete t[n];return Object.keys(t).length>0?t:void 0}onMerge(e,t){this.setStyle(e,t,this.getCellStyle({sheetId:e,col:t.left,row:t.top}),{force:!0})}setStyles(e,t,n,r={force:!1}){for(let i of t)this.setStyle(e,i,n,r)}setStyle(e,t,n,r={force:!1}){let i=[],a=[this.getters.expandZone(e,t)];for(let o of this.styles[e]??[]){let e=Sn(o.zone,t);if(!e){i.push(o);continue}let s=r.force?n:{...o.style,...n};if(s=this.removeDefaultStyleValues(s),w(o.style,s))i.push(o);else{s&&!this.styleIsDefault(s)&&i.push({zone:e,style:s});for(let t of Qt([o.zone],[e]))i.push({zone:t,style:o.style})}a=Qt(a,[e])}n=this.removeDefaultStyleValues(n),n&&i.push(...a.map(e=>({zone:e,style:n}))),this.history.update(`styles`,e,i)}clearStyle(e,t){this.setStyles(e,t,void 0,{force:!0})}getCellStyle(e){return this.styles[e.sheetId]?.find(t=>En(e.col,e.row,t.zone))?.style}getCellStyleInZone(e,t){let n=new bF;for(let{zone:r,style:i}of this.styles[e]??[]){let a=Sn(r,t);if(a)for(let t=a.left;t<=a.right;t++)for(let r=a.top;r<=a.bottom;r++)n.set({sheetId:e,col:t,row:r},i)}return n}getZoneStyles(e,t){let n=[];for(let r of this.styles[e]??[]){let e=Sn(r.zone,t);e&&n.push({zone:e,style:r.style})}return n}getStyleColors(e){let t=new Set;for(let n of this.styles[e]??[])n.style.textColor&&t.add(n.style.textColor),n.style.fillColor&&t.add(n.style.fillColor);return[...t]}import(e){if(Object.keys(e.styles||{}).length){for(let t of e.sheets)for(let n in t.styles){let r=t.styles[n];this.setStyle(t.id,un(n),e.styles[r])}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.onMerge(t.id,un(e))}}export(e){let t={};for(let n of e.sheets){n.styles={};for(let e of this.styles[n.id]??[])n.styles[hn(e.zone)]=_c(e.style,t)}e.styles=t}exportForExcel(e){this.export(e)}checkUselessSetFormatting(e){let{sheetId:t,target:n}=e,r=`style`in e,i=`format`in e;if(!r&&!i)return`NoChanges`;for(let a of Qt(n))for(let n=a.left;n<=a.right;n++)for(let o=a.top;o<=a.bottom;o++){let a={sheetId:t,col:n,row:o},s=this.getters.getCell(a),c=this.getCellStyle(a);if(r&&!w(c,e.style)||i&&s?.format!==e.format)return`Success`}return`NoChanges`}},FW=class extends dW{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(!LA[e.templateName])return`InvalidTableStyle`;try{wr(e.primaryColor)}catch{return`InvalidTableStyle`}break}return`Success`}handle(e){switch(e.type){case`CREATE_TABLE_STYLE`:let t=RA(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:SA.styleId}});break}}getTableStyle(e){if(!this.styles[e])throw Error(`Table style ${e} does not exist`);return this.styles[e]}getTableStyles(){return this.styles}getNewCustomTableStyleName(){return zt(k(`Custom Table Style`),Object.values(this.styles).map(e=>e.displayName),{compute:(e,t)=>`${e} ${t}`,start:2})}isTableStyleEditable(e){return!IA[e]}import(e){for(let e in IA)this.styles[e]=IA[e];for(let t in e.customTableStyles){let n=e.customTableStyles[t];this.styles[t]=RA(n.displayName,n.templateName,n.primaryColor)}}export(e){let t={};for(let e in this.styles)IA[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}},IW=class extends dW{static getters=[`getCoreTable`,`getCoreTables`,`getCoreTableMatchingTopLeft`];tables={};nextTableId=1;adaptRanges({applyChange:e},t){for(let n of this.getCoreTables(t))this.applyRangeChangeOnTable(t,n,e)}allowDispatch(e){switch(e.type){case`CREATE_TABLE`:if(e.ranges.some(t=>!this.getters.tryGetSheet(t._sheetId)||t._sheetId!==e.sheetId))return`InvalidSheetId`;let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone);return Gn(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(wn(n,t))return`MergeInTable`}break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`tables`,e.sheetId,{});break;case`DELETE_SHEET`:{let t={...this.tables};delete t[e.sheetId],this.history.update(`tables`,t);break}case`DUPLICATE_SHEET`:{let t={};for(let n of this.getCoreTables(e.sheetId))t[n.id]=n.type===`dynamic`?this.copyDynamicTableForSheet(e.sheetIdTo,n):this.copyStaticTableForSheet(e.sheetIdTo,n);this.history.update(`tables`,e.sheetIdTo,t);break}case`CREATE_TABLE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e)),n=this.getters.getRangesUnion(t),r=this.getters.getMergesInZone(e.sheetId,n.zone);r.length&&this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:r});let i=this.consumeNextId(),a=e.config||SA,o=e.tableType===`dynamic`?this.createDynamicTable(i,n,a):this.createStaticTable(i,e.tableType,n,a);this.history.update(`tables`,e.sheetId,o.id,o);break}case`REMOVE_TABLE`:{let t={};for(let n of this.getCoreTables(e.sheetId))e.target.every(e=>!Sn(n.range.zone,e))&&(t[n.id]=n);this.history.update(`tables`,e.sheetId,t);break}case`UPDATE_TABLE`:this.updateTable(e);break;case`UPDATE_CELL`:{let t=e.sheetId;for(let n of this.getCoreTables(t)){if(n.type===`dynamic`)continue;let r=this.canUpdateCellCmdExtendTable(e,n);r===`down`?this.extendTableDown(t,n):r===`right`&&this.extendTableRight(t,n)}break}case`DELETE_CONTENT`:{let t={...this.tables[e.sheetId]};for(let n in t){let r=t[n];r&&e.target.some(e=>Dn(r.range.zone,e))&&this.dispatch(`REMOVE_TABLE`,{sheetId:e.sheetId,target:[r.range.zone]})}break}}}getCoreTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(C):[]}getCoreTable({sheetId:e,col:t,row:n}){return this.getCoreTables(e).find(e=>En(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter(e=>t.some(t=>wn(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,[E(r)]).length)return`none`}return o}getCoreTableMatchingTopLeft(e,t){for(let n of this.getCoreTables(e)){let e=n.range.zone;if(e.left===t.left&&e.top===t.top)return n}}checkUpdatedTableZoneIsValid(e){if(!e.newTableRange)return`Success`;let t=this.getters.getRangeFromRangeData(e.newTableRange).zone,n=this.getters.checkZonesExistInSheet(e.sheetId,[t]);if(n!==`Success`)return n;let r=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);return r?this.getTablesOverlappingZones(e.sheetId,[t]).filter(e=>e.id!==r.id).length?`TableOverlap`:`Success`:`TableNotFound`}checkTableConfigUpdateIsValid(e){return e&&(e.numberOfHeaders!==void 0&&e.numberOfHeaders<0||e.hasFilters&&e.numberOfHeaders===0)?`InvalidTableConfig`:`Success`}createStaticTable(e,t,n,r,i){let a=n.zone;if(!i){i=[];for(let e of S(a.left,a.right+1)){let t={...a,left:e,right:e},o=this.consumeNextId();i.push(this.createFilterFromZone(o,n.sheetId,t,r))}}return{id:e,range:n,filters:i,config:r,type:t}}createDynamicTable(e,t,n){let r=Rn(t.zone);return{id:e,range:this.getters.getRangeFromZone(t.sheetId,r),config:n,type:`dynamic`}}updateTable(e){let t=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return;let n=e.newTableRange?this.getters.getRangeFromRangeData(e.newTableRange):void 0;if(n){let t=this.getters.getMergesInZone(e.sheetId,n.zone);this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:t})}let r=n||t.range,i=this.updateTableConfig(e.config,t.config),a=e.tableType??t.type;if(a===`dynamic`&&t.type!==`dynamic`||a!==`dynamic`&&t.type===`dynamic`){let n=a===`dynamic`?this.createDynamicTable(t.id,r,i):this.createStaticTable(t.id,a,r,i);this.history.update(`tables`,e.sheetId,t.id,n)}else{let n=t.type===`dynamic`?this.updateDynamicTable(t,r,i):this.updateStaticTable(t,r,i,a);this.history.update(`tables`,e.sheetId,t.id,n)}}updateStaticTable(e,t,n,r=e.type){if(r===`dynamic`)throw Error(`Cannot use updateStaticTable to update a dynamic table`);let i=t||e.range,a=i.zone,o=this.updateTableConfig(n,e.config),s=o||e.config,c=[];if(t||o&&`numberOfHeaders`in o)for(let t of S(a.left,a.right+1)){let n=a.top===e.range.zone.top?e.filters.find(e=>e.col===t):void 0,r={...a,left:t,right:t},o=n?.id||this.consumeNextId();c.push(this.createFilterFromZone(o,i.sheetId,r,s))}return{...e,range:i,config:s,filters:c.length?c:e.filters,type:r}}updateDynamicTable(e,t,n){let r=t?this.getters.getRangeFromZone(t.sheetId,Rn(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 eI(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 eI(n.id,r,t.config,this.getters.getRangeFromZone)});return{id:t.id,range:n,filters:r,config:b(t.config),type:t.type}}copyDynamicTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone);return{id:t.id,range:n,config:b(t.config),type:`dynamic`}}applyRangeChangeOnTable(e,t,n){let r=n(t.range),i;switch(r.changeType){case`REMOVE`:this.history.update(`tables`,e,t.id,void 0);return;case`NONE`:return;default:i=r.range}if(t.type===`dynamic`){let n=this.updateDynamicTable(t,i);this.history.update(`tables`,e,t.id,n);return}let a=[];for(let e of t.filters){let r=n(e.rangeWithHeaders);switch(r.changeType){case`REMOVE`:continue;case`NONE`:a.push(e);break;default:let n=r.range,i=eI(e.id,n,t.config,this.getters.getRangeFromZone);a.push(i)}}let o=i.zone;if(a.length<On(o).numberOfCols){for(let n=o.left;n<=o.right;n++)if(!a.find(e=>e.col===n)){let r=this.consumeNextId(),i={...o,left:n,right:n};a.push(this.createFilterFromZone(r,e,i,t.config))}a.sort((e,t)=>e.col-t.col)}let s=this.createStaticTable(t.id,t.type,i,t.config,a);this.history.update(`tables`,e,t.id,s)}consumeNextId(){let e=`${this.nextTableId}`;return this.history.update(`nextTableId`,this.nextTableId+1),e}import(e){for(let t of e.sheets)for(let e of t.tables||[]){let n=this.consumeNextId(),r=e.config||SA,i=this.getters.getRangeFromSheetXC(t.id,e.range),a=e.type||`static`,o=a===`dynamic`?this.createDynamicTable(n,i,r):this.createStaticTable(n,a,i,r);this.history.update(`tables`,t.id,o.id,o)}}export(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n={range:hn(e.range.zone),type:e.type};w(e.config,SA)||(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=hn(e.range.zone);t.tables.push({range:n,filters:[],config:e.config})}}},LW=class extends sb{getters;constructor({getters:e,stateObserver:t}){super(t),this.getters=e}};let RW=yO.mapping;function zW(e,t,n){return new BW(e,t,n).getParameters()}var BW=class{getters;computeCell;evalContext;rangeCache={};constructor(e,t,n){this.getters=t,this.computeCell=n,this.evalContext=Object.assign(Object.create(RW),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;let r={sheetId:e.sheetId,col:e.zone.left,row:e.zone.top};return t?(this.computeCell(r),{value:Fc(this.getters.getSheetName(e.sheetId),hn(e.zone))}):this.computeCell(r)}range(e,t){let n=this.getRangeError(e);if(n)return[[n]];let r=e.sheetId,i=e.zone,a=Sn(i,this.getters.getSheetZone(r));if(!a)return[[]];let{top:o,left:s,bottom:c,right:l}=i,u=`${r}-${o}-${s}-${c}-${l}-${t}`;if(u in this.rangeCache)return this.rangeCache[u];let d=a.bottom-a.top+1,f=a.right-a.left+1,p=Array(f),m=this.getters.getSheetName(e.sheetId);for(let e=a.left;e<=a.right;e++){let n=e-a.left;p[n]=Array(d);for(let i=a.top;i<=a.bottom;i++){let o=i-a.top,s=this.computeCell({sheetId:r,col:e,row:i});p[n][o]=t?{value:Fc(m,T(e,i))}:s}}return this.rangeCache[u]=p,p}getRangeError(e){if(!pn(e.zone))return new ma;if(e.invalidSheetName)return new ma(k(`Invalid sheet name: %s`,e.invalidSheetName))}},VW=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),HW=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 UW,this.rTrees[e].load(t[e])}insert(e){let t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new UW),this.rTrees[t].insert(e)}search({zone:e,sheetId:t}){return this.rTrees[t]?this.rTrees[t].search({minX:e.left,minY:e.top,maxX:e.right,maxY:e.bottom}):[]}remove(e){let t=e.boundingBox.sheetId;this.rTrees[t]&&this.rTrees[t].remove(e,this.rtreeItemComparer)}rtreeItemComparer(e,t){return e.boundingBox.sheetId===t.boundingBox.sheetId&&e.boundingBox?.zone.left===t.boundingBox.zone.left&&e.boundingBox?.zone.top===t.boundingBox.zone.top&&e.boundingBox?.zone.right===t.boundingBox.zone.right&&e.boundingBox?.zone.bottom===t.boundingBox.zone.bottom&&w(e.data,t.data)}},UW=class extends VW.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}},WW=class e{profilesStartingPosition=[0];profiles=new Map([[0,[]]]);constructor(e=[]){for(let t of e)this.add(t)}isEmpty(){return this.profiles.size===1&&this.profiles.get(0)?.length===0}add(e){$t(this.profilesStartingPosition,this.profiles,[e])}delete(e){$t(this.profilesStartingPosition,this.profiles,[e],!0)}has(e){return en(this.profilesStartingPosition,this.profiles,e)}difference(e){let t=this.copy();for(let n of e)t.delete(n);return t}copy(){let t=new e;t.profilesStartingPosition=[...this.profilesStartingPosition],t.profiles=new Map;for(let[e,n]of this.profiles)t.profiles.set(e,[...n]);return t}[Symbol.iterator](){return an(this.profilesStartingPosition,this.profiles)[Symbol.iterator]()}},GW=class e{setsBySheetId={};constructor(e=[]){for(let t of e)this.add(t)}add(e){this.setsBySheetId[e.sheetId]||(this.setsBySheetId[e.sheetId]=new WW),this.setsBySheetId[e.sheetId].add(e.zone)}addMany(e){for(let t of e)this.add(t)}addPosition(e){this.add(el(e))}addManyPositions(e){for(let t of e)this.addPosition(t)}has(e){return this.setsBySheetId[e.sheetId]?this.setsBySheetId[e.sheetId].has(e.zone):!1}hasPosition(e){return this.has(el(e))}delete(e){this.setsBySheetId[e.sheetId]&&this.setsBySheetId[e.sheetId].delete(e.zone)}deleteMany(e){for(let t of e)this.delete(t)}deleteManyPositions(e){for(let t of e)this.delete(el(t))}difference(t){let n=new e;for(let e in this.setsBySheetId)n.setsBySheetId[e]=this.setsBySheetId[e];for(let e in t.setsBySheetId)n.setsBySheetId[e]&&(n.setsBySheetId[e]=n.setsBySheetId[e].difference(t.setsBySheetId[e]));return n}copy(){let t=new e;for(let e in this.setsBySheetId)t.setsBySheetId[e]=this.setsBySheetId[e].copy();return t}clear(){this.setsBySheetId={}}isEmpty(){for(let e in this.setsBySheetId)if(!this.setsBySheetId[e].isEmpty())return!1;return!0}[Symbol.iterator](){let e=[];for(let t in this.setsBySheetId)for(let n of this.setsBySheetId[t])e.push({sheetId:t,zone:n});return e[Symbol.iterator]()}},KW=class{rTree;constructor(e=[]){let t=qW(e);this.rTree=new HW(t)}insert(e){let t=this.rTree.search(e.boundingBox),n=e.boundingBox,r=t.find(({boundingBox:e})=>e.sheetId===n.sheetId&&e.zone.left===n.zone.left&&e.zone.top===n.zone.top&&e.zone.right===n.zone.right&&e.zone.bottom===n.zone.bottom);r?r.data.add(e.data):this.rTree.insert({...e,data:new GW([e.data])})}search({zone:e,sheetId:t}){let n=new GW;for(let{data:r}of this.rTree.search({zone:e,sheetId:t}))n.addMany(r);return n}remove(e){let t=this.rTree.search(e.boundingBox),n=e.boundingBox,r=t.find(({boundingBox:e})=>e.sheetId===n.sheetId&&e.zone.left===n.zone.left&&e.zone.top===n.zone.top&&e.zone.right===n.zone.right&&e.zone.bottom===n.zone.bottom);r?r.data.delete(e.data):this.rTree.remove({...e,data:new GW([e.data])})}};function qW(e){let t=0,n=0;for(let r=0;r<e.length;r++){let i=e[r].boundingBox.zone;i.right>t&&(t=i.right),i.bottom>n&&(n=i.bottom)}t+=1,n+=1;let r=(((n+1)*t+1)*n+1)*t<=2**53-1;r||console.warn(`Max col/row size exceeded, using slow zone key`);let i={};for(let a of e){let e=a.boundingBox.sheetId;i[e]||(i[e]={});let o=a.boundingBox.zone,s=0;s=r?o.left+o.top*t+o.right*t*n+o.bottom*t*n*t:`${o.left},${o.top},${o.right},${o.bottom}`,i[e][s]?i[e][s].data.add(a.data):i[e][s]={boundingBox:a.boundingBox,data:new GW([a.data])}}let a=[];for(let e in i){let t=i[e];for(let e in t)a.push(t[e])}return a}var JW=class{dependencies=new bF;rTree;constructor(e=[]){this.rTree=new KW(e)}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:{sheetId:e.sheetId,zone:E(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=new GW){t=t.copy();let n=Array.from(e).reverse();for(;n.length>0;){let e=n.pop();t.add(e);let r=this.rTree.search(e);n.push(...r.difference(t))}for(let n of e)t.delete(n);return t}},YW=class extends Uint32Array{columnOffset=0;cols=0;rows=0;static create(e,t){let n=XW(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 XW(e){return e===0?-1/0:e<0?NaN:32-Math.clz32(--e)}var ZW=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]=YW.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)}},QW=class{resultsToArrayFormulas=new HW;arrayFormulasToResults=new bF;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map(e=>e.data)||$W}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 $W=[],eG=new B;eG.add(`pivots`,e=>{for(let t of e.getPivotIds())e.getPivot(t).markAsDirtyForEvaluation?.()});let tG=Object.freeze(rc({...new pa,origin:void 0})),nG=Object.freeze(rc({value:null}));var rG=class{context;getters;compilationParams;evaluatedCells=new bF;formulaDependencies=mt(new JW);blockedArrayFormulas=new ZW({});spreadingRelations=new QW;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=zW(this.context,this.getters,this.computeAndSave.bind(this))}getEvaluatedCell(e){return this.evaluatedCells.get(e)||nG}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===A.SpilledBlocked)?E(e):bn(E(e),n)}getEvaluatedPositions(){return this.evaluatedCells.keys()}getEvaluatedPositionsInSheet(e){return this.evaluatedCells.keysForSheet(e)}getArrayFormulaSpreadingOn(e){if(this.getEvaluatedCell(e).type!==`empty`)return this.spreadingRelations.searchFormulaPositionsSpreadingOn(e.sheetId,E(e)).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,!1)}updateCompilationParametersForIsolatedFormula(e){this.compilationParams=zW(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.__originCellPosition=e,this.compilationParams.evalContext.updateDependencies=void 0,this.compilationParams.evalContext.addDependencies=void 0,this.compilationParams.evalContext.lookupCaches=this.compilationParams.evalContext.lookupCaches||{forwardSearch:new Map,reverseSearch:new Map}}updateCompilationParameters(){this.compilationParams=zW(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 ZW(e)}evaluateCells(e){let t=performance.now(),n=new GW;n.addManyPositions(e);let r=this.getArrayFormulasImpactedByChangesOf(e);n.addMany(this.getCellsDependingOn(n)),n.addMany(r),n.addMany(this.getCellsDependingOn(r)),this.evaluate(n),console.debug(`evaluate Cells`,performance.now()-t,`ms`)}getArrayFormulasImpactedByChangesOf(e){let t=new GW;for(let n of e){let e=this.getters.getCell(n)?.content,r=this.getArrayFormulaSpreadingOn(n);r!==void 0&&t.addPosition(r),e||t.addPosition(n)}for(let e of[...t])t.addMany(this.getArrayFormulasBlockedBy(e.sheetId,e.zone));return t}buildDependencyGraph(){this.blockedArrayFormulas=this.createEmptyPositionSet(),this.spreadingRelations=new QW,this.formulaDependencies=mt(()=>{let e=[];for(let t of this.getters.getSheetIds()){let n=this.getters.getCells(t);for(let r in n){let i=n[r];if(i.isFormula){let n=i.compiledFormula.dependencies;for(let i of n)i.invalidSheetName||i.invalidXc||e.push({data:{sheetId:t,zone:E(this.getters.getCellPosition(r))},boundingBox:{sheetId:i.sheetId,zone:i.zone}})}}}return new JW(e)})}evaluateAllCells(){let e=performance.now();this.evaluatedCells=new bF;let t=[];for(let e of this.getters.getSheetIds()){let n=this.getters.getSheetZone(e);t.push({sheetId:e,zone:n})}this.evaluate(t),console.debug(`evaluate all cells`,performance.now()-e,`ms`)}evaluateFormulaResult(e,t,n){let r=lU(t),i=r.dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t));return this.updateCompilationParametersForIsolatedFormula(n),this.evaluateCompiledFormula(e,{...r,dependencies:i})}evaluateCompiledFormula(e,t,n){try{let r=sG(t,this.compilationParams,e,this.buildSafeGetSymbolValue(n),this.compilationParams.evalContext.__originCellPosition);return xa(r)?Ga(r,aG):aG(r)}catch(e){return Sy(e,``)}}getArrayFormulasBlockedBy(e,t){let n=new GW,r=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e,t);n.addManyPositions(r);let i=[...r].filter(e=>!this.blockedArrayFormulas.has(e));return i.length&&n.deleteManyPositions(i),n.addMany(this.getCellsDependingOn(n)),n}nextRangesToUpdate=new GW;cellsBeingComputed=new Set;symbolsBeingComputed=new Set;evaluate(e){this.cellsBeingComputed=new Set,this.nextRangesToUpdate=new GW(e);let t=0;for(;!this.nextRangesToUpdate.isEmpty()&&t++<30;){this.updateCompilationParameters();let e=[...this.nextRangesToUpdate];this.nextRangesToUpdate.clear(),this.clearEvaluatedRanges(e);for(let t of e){let{left:e,bottom:n,right:r,top:i}=t.zone;for(let a=e;a<=r;a++)for(let e=i;e<=n;e++){let n={sheetId:t.sheetId,col:a,row:e};if(this.nextRangesToUpdate.hasPosition(n))continue;let r=this.computeCell(n);r!==nG&&this.evaluatedCells.set(n,r)}}eG.getAll().forEach(e=>e(this.getters))}t>=30&&console.warn(`Maximum iteration reached while evaluating cells`)}clearEvaluatedRanges(e){for(let t of e){let{left:e,bottom:n,right:r,top:i}=t.zone;for(let a=e;a<=r;a++)for(let e=i;e<=n;e++)this.evaluatedCells.delete({sheetId:t.sheetId,col:a,row:e})}}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 nG;let r=n.id,i={format:n.format,locale:this.getters.getLocale()};try{return this.cellsBeingComputed.has(r)?tG:(this.cellsBeingComputed.add(r),n.isFormula?this.computeFormulaCell(e,n):tc(n,i,e))}catch(t){return t.value=t?.value||A.GenericError,t.message=t?.message||Ty,t.origin=e,t.errorOriginPosition=t?.errorOriginPosition,rc(t)}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=sG(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e);if(!xa(n)){let r=rc(oG(n),this.getters.getLocale(),t,e);return r.type===`error`&&(r.errorOriginPosition=n.errorOriginPosition??e),r}this.assertSheetHasEnoughSpaceToSpreadFormulaResult(e,n);let r=n.length,i=n[0].length;if(i===0)return rc({value:0},this.getters.getLocale(),t);if(i===1&&r===1)return rc(oG(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),iG(r,i,this.checkCollision(e)),iG(r,i,this.spreadValues(e,n)),this.invalidatePositionsDependingOnSpread(e.sheetId,a),rc(oG(n[0][0]),this.getters.getLocale(),t)}invalidatePositionsDependingOnSpread(e,t){let n=this.getCellsDependingOn(An(t).map(t=>({sheetId:e,zone:t})));n.delete({sheetId:e,zone:t}),this.nextRangesToUpdate.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 _a(k(`Result couldn't be automatically expanded. Please insert more rows.`)):s?new _a(k(`Result couldn't be automatically expanded. Please insert more columns.`)):new _a(k(`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 _a(k(`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 _a(k(`Array result was not expanded because it would overwrite data.`),o);this.blockedArrayFormulas.delete(e)}}spreadValues({sheetId:e,col:t,row:n},r){return(i,a)=>{let o={sheetId:e,col:i+t,row:a+n},s=this.getters.getCell(o),c=rc(oG(r[i][a]),this.getters.getLocale(),s,o);c.type===`error`&&(c.errorOriginPosition=r[i][a].errorOriginPosition??o),this.evaluatedCells.set(o,c)}}invalidateSpreading(e){let t=this.spreadingRelations.getArrayResultZone(e);if(!t)return;for(let n=t.left;n<=t.right;n++)for(let r=t.top;r<=t.bottom;r++){let t={sheetId:e.sheetId,col:n,row:r};this.getters.getCell(t)?.content||this.evaluatedCells.delete(t)}let n=e.sheetId;this.invalidatePositionsDependingOnSpread(n,t),this.nextRangesToUpdate.addMany(this.getArrayFormulasBlockedBy(n,t))}buildSafeGetSymbolValue(e){return t=>{if(this.symbolsBeingComputed.has(t))return tG;this.symbolsBeingComputed.add(t);try{return e?.(t)||new fa(k(`Invalid formula`))}finally{this.symbolsBeingComputed.delete(t)}}}getDirectDependencies(e){let t=this.getters.getCell(e);return t?.isFormula?t.compiledFormula.dependencies:[]}getCellsDependingOn(e){return this.formulaDependencies().getCellsDependingOn(e,this.nextRangesToUpdate)}};function iG(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 aG(e){return e.value===null||e.value===void 0?{...e,value:0}:e}function oG(e){return typeof e.value==`number`&&Math.abs(e.value)>Number.MAX_VALUE?new ya:aG(e)}function sG(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 cG=class extends LW{static getters=[`evaluateFormula`,`evaluateFormulaResult`,`evaluateCompiledFormula`,`getCorrespondingFormulaCell`,`getRangeFormattedValues`,`getRangeValues`,`getRangeFormats`,`getEvaluatedCell`,`getEvaluatedCells`,`getEvaluatedCellsInZone`,`getEvaluatedCellsPositionInZone`,`getEvaluatedCellsPositions`,`getSpreadZone`,`getArrayFormulaSpreadingOn`,`isArrayFormulaSpillBlocked`,`isEmpty`];shouldRebuildDependenciesGraph=!0;evaluator;positionsToUpdate=[];constructor(e){super(e),this.evaluator=new rG(e.custom,this.getters)}beforeHandle(e){(Ps.has(e.type)||Is.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`:if(e.cellIds)for(let t=0;t<e.cellIds.length;t++)this.positionsToUpdate.push(this.getters.getCellPosition(e.cellIds[t]));else this.evaluator.evaluateAllCells();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 xa(r)?Ga(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 Mn(e,t).map(this.getters.getEvaluatedCell)}getEvaluatedCellsPositionInZone(e,t){return Mn(e,t).map(e=>[e,this.getters.getEvaluatedCell(e)])}getSpreadZone(e,t={ignoreSpillError:!1}){return this.evaluator.getSpreadZone(e,t)}getArrayFormulaSpreadingOn(e){return this.evaluator.getArrayFormulaSpreadingOn(e)}isArrayFormulaSpillBlocked(e){return this.evaluator.isArrayFormulaSpillBlocked(e)}isEmpty(e,t){return jn(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 jn(r).reduce((e,r)=>{let{col:i,row:a}=r;return!this.getters.isColHidden(n,i)&&!this.getters.isRowHidden(n,a)&&e.push(t({sheetId:n,...r})),e},[])}exportForExcel(e){for(let t of e.sheets)t.cellValues={},t.formulaSpillRanges={};for(let t of this.evaluator.getEvaluatedPositions()){let n=this.evaluator.getEvaluatedCell(t),r=T(t.col,t.row),i=n.value,a=!1,o,s=!0,c=e.sheets.find(e=>e.id===t.sheetId),l=this.getCorrespondingFormulaCell(t);if(l){let u=this.getters.getCell(t);if(s=SU(l.compiledFormula.tokens),a=s&&u?.content===l.content,!s&&i!==``){o=(i??``).toString();let t=n.format;if(t){let n=_c(t,e.formats);c.formats[r]=n}}}let u=c.cells[r],d;d=s&&a&&l instanceof hW?l.contentWithFixedReferences:s?u:o,c.cells[r]=d,c.cellValues[r]=i===A.BadExpression?void 0:i;let f=this.getSpreadZone(t);f&&(c.formulaSpillRanges[r]=this.getters.getRangeString(this.getters.getRangeFromZone(t.sheetId,f),t.sheetId))}}getCorrespondingFormulaCell(e){let t=this.getters.getCell(e);if(t&&t.isFormula)return t.compiledFormula.isBadExpression?void 0:t;if(t&&t.content)return;let n=this.getArrayFormulaSpreadingOn(e);if(n===void 0)return;let r=this.getters.getCell(n);if(r?.isFormula)return r}};let lG=new B;lG.add(`data_validation_checkbox`,(e,t)=>{if(e.isCellValidCheckbox(t)){let n=!!e.getEvaluatedCell(t).value;return{svg:n?aj:rj,hoverSvg:n?aj:ij,priority:2,horizontalAlign:`center`,size:17,margin:2,position:t,type:`data_validation_checkbox`,onClick:(e,t)=>{let r=t.model.getters.getCell(e);if(t.model.getters.isReadonly()||r?.isFormula)return;let i=n?`FALSE`:`TRUE`;t.model.dispatch(`UPDATE_CELL`,{...e,content:i})}}}}),lG.add(`data_validation_chip_icon`,(e,t)=>{let n=e.getDataValidationChipStyle(t);if(n){let r=e.getCellComputedStyle(t);return{svg:tj(n),hoverSvg:nj(n),priority:10,horizontalAlign:`right`,size:Pl(r),margin:4,position:t,onClick:(e,t)=>{let{col:n,row:r}=e;t.model.selection.selectCell(n,r),t.startCellEdition()},type:`data_validation_chip_icon`}}}),lG.add(`data_validation_list_icon`,(e,t)=>{if(!e.isReadonly()&&e.cellHasListDataValidationIcon(t)){let n=e.getCellComputedStyle(t);return{svg:ZA(n),hoverSvg:$A(n),priority:2,horizontalAlign:`right`,size:17,margin:2,position:t,onClick:(e,t)=>{let{col:n,row:r}=e;t.model.selection.selectCell(n,r),t.startCellEdition()},type:`data_validation_list_icon`}}}),lG.add(`conditional_formatting`,(e,t)=>{let n=e.getConditionalIcon(t);if(n){let r=e.getCellStyle(t);return{type:`conditional_formatting`,svg:cj[n].svg,priority:1,horizontalAlign:`left`,size:Pl(r),margin:4,position:t}}}),lG.add(`pivot_collapse`,(e,t)=>{if(!e.isSpillPivotFormula(t))return;let n=e.getPivotCellFromPosition(t),r=e.getPivotIdFromPosition(t);if(n.type===`HEADER`&&r&&n.domain.length){let i=e.getPivotCoreDefinition(r),a=e.isDashboard(),o=n.dimension===`COL`?i.columns:i.rows,s=!a&&n.domain.length!==o.length,c=(i.collapsedDomains?.[n.dimension]??[]).some(e=>w(e,n.domain)),l=n.dimension===`ROW`?(n.domain.length-1)*15:0;return{type:`pivot_collapse`,priority:4,horizontalAlign:`left`,size:s||!a&&n.dimension===`ROW`&&i.rows.length>1?12:0,margin:s?4+l:l,svg:s?oj(c,!1):void 0,hoverSvg:s?oj(c,!0):void 0,position:t,onClick:Mh}}}),lG.add(`pivot_dashboard_sorting`,(e,t)=>{if(!e.isDashboard()||e.getPivotCellFromPosition(t).type!==`MEASURE_HEADER`)return;let n=e.getPivotCellSortDirection(t);if(n!==`asc`&&n!==`desc`)return;let r=e.getCellComputedStyle(t);return{type:`pivot_dashboard_sorting_${n}`,priority:5,horizontalAlign:`right`,size:17,margin:2,svg:n===`asc`?QA(r):ZA(r),position:t,onClick:void 0}});var uG=class extends LW{static getters=[`doesCellHaveGridIcon`,`getCellIcons`,`getCellIconRect`];cellIconsCache={};handle(e){e.type!==`SET_VIEWPORT_OFFSET`&&(this.cellIconsCache={})}getCellIcons(e){return this.cellIconsCache[e.sheetId]||(this.cellIconsCache[e.sheetId]={}),this.cellIconsCache[e.sheetId][e.col]||(this.cellIconsCache[e.sheetId][e.col]={}),this.cellIconsCache[e.sheetId][e.col][e.row]||(this.cellIconsCache[e.sheetId][e.col][e.row]=this.computeCellIcons(e)),this.cellIconsCache[e.sheetId][e.col][e.row]}getCellIconRect(e,t){let n=e.position,r=this.getters.getCellStyle(n)?.verticalAlign;return{x:this.getIconHorizontalPosition(t,e.horizontalAlign,e),y:this.getters.computeTextYCoordinate(t,e.size,r),width:e.size,height:e.size}}getIconHorizontalPosition(e,t,n){let r=e.x,i=e.x+e.width;switch(t){case`right`:return i-n.margin-n.size;case`left`:return r+n.margin;default:let e=Math.floor((i-r-n.size)/2);return i-n.size-e}}computeCellIcons(e){let t={left:void 0,right:void 0,center:void 0},n=lG.getAll();for(let r of n){let n=r(this.getters,e);n&&(!t[n.horizontalAlign]||n.priority>t[n.horizontalAlign].priority)&&(t[n.horizontalAlign]=n)}if(t.center&&(t.left||t.right)){let e=Math.max(t.left?.priority||0,t.right?.priority||0);t.center.priority<e?t.center=void 0:(t.left=void 0,t.right=void 0)}return Object.values(t).filter(C)}doesCellHaveGridIcon(e){return!!this.getCellIcons(e).length}};let dG=/"(#[0-9a-fA-F]{6})"/g;function fG(e){let t=[{leadColor:Or(255,0,0),colors:[]},{leadColor:Or(255,128,0),colors:[]},{leadColor:Or(128,128,0),colors:[]},{leadColor:Or(128,255,0),colors:[]},{leadColor:Or(0,255,0),colors:[]},{leadColor:Or(0,255,128),colors:[]},{leadColor:Or(0,255,255),colors:[]},{leadColor:Or(0,127,255),colors:[]},{leadColor:Or(0,0,255),colors:[]},{leadColor:Or(127,0,255),colors:[]},{leadColor:Or(128,0,128),colors:[]},{leadColor:Or(255,0,128),colors:[]}];for(let n of e.map(Mr)){let e=500,r=0;t.forEach((t,i)=>{let a=pG(n,t.leadColor);e>a&&(e=a,r=i)}),t[r].colors.push(n)}return t.map(e=>e.colors.sort((e,t)=>Pr(e).s-Pr(t).s)).flat().map(jr)}function pG(e,t){return Math.sqrt((e.r-t.r)**2+(e.g-t.g)**2+(e.b-t.b)**2)}var mG=class extends LW{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.chartId));break;case`UPDATE_CELL`:case`ADD_CONDITIONAL_FORMAT`:case`SET_BORDER`:case`SET_ZONE_BORDERS`:case`SET_FORMATTING`:case`CREATE_TABLE`:case`UPDATE_TABLE`:this.history.update(`shouldUpdateColors`,!0);break}}finalize(){this.shouldUpdateColors&&(this.history.update(`shouldUpdateColors`,!1),this.tryToAddColors(this.computeCustomColors()))}getCustomColors(){return fG(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=new Set;for(let n of this.getters.getStyleColors(e))t.add(n);for(let n of this.getters.getBordersColors(e))t.add(n);return[...t]}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(Sr(t.minimum.color)),n.push(t.midpoint?Sr(t.midpoint.color):void 0),n.push(Sr(t.maximum.color)))}return n.filter(C)}getChartColors(e){let t=this.getters.getChart(e);return t===void 0?[]:[...JSON.stringify(t.getDefinition()).matchAll(dG)].map(e=>e[1])}getTableColors(e){return this.getters.getTables(e).flatMap(e=>{let t=e.config,n=this.getters.getTableStyle(t.styleId);return[this.getTableStyleElementColors(n.wholeTable),t.numberOfHeaders>0?this.getTableStyleElementColors(n.headerRow):[],t.totalRow?this.getTableStyleElementColors(n.totalRow):[],t.bandedColumns?this.getTableStyleElementColors(n.firstColumnStripe):[],t.bandedColumns?this.getTableStyleElementColors(n.secondColumnStripe):[],t.bandedRows?this.getTableStyleElementColors(n.firstRowStripe):[],t.bandedRows?this.getTableStyleElementColors(n.secondRowStripe):[],t.firstColumn?this.getTableStyleElementColors(n.firstColumn):[],t.lastColumn?this.getTableStyleElementColors(n.lastColumn):[]].flat()})}getTableStyleElementColors(e){return e?[e.style?.fillColor,e.style?.textColor,e.border?.bottom?.color,e.border?.top?.color,e.border?.left?.color,e.border?.right?.color,e.border?.horizontal?.color,e.border?.vertical?.color].filter(C):[]}tryToAddColors(e){for(let t of e){if(!Tr(t))continue;let e=wr(t);t&&!_e.includes(e)&&this.history.update(`customColors`,e,!0)}}},hG=class extends LW{static getters=[`canCreateDynamicTableOnZones`,`doesZonesContainFilter`,`getFilter`,`getFilters`,`getTable`,`getTables`,`getTablesOverlappingZones`,`getFilterId`,`getFilterHeaders`,`isFilterHeader`];tables={};handle(e){if(Ps.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;wn(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=>En(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getTables(e).filter(e=>t.some(t=>wn(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(!Gn(t))return!1;let n=bn(...t),r={col:n.left,row:n.top,sheetId:e},i=this.getters.getArrayFormulaSpreadingOn(r);if(!i){let e=this.getters.getEvaluatedCell(r);return e.value===A.SpilledBlocked&&!e.errorOriginPosition}else if(w(i,r)&&Vn(n)===1)return!0;return w(n,this.getters.getSpreadZone(i))}coreTableToTable(e,t){if(t.type!==`dynamic`)return t;let n=t.range.zone,r={sheetId:e,col:n.left,row:n.top},i=this.getters.getSpreadZone(r)??t.range.zone,a=this.getters.getRangeFromZone(e,i),o=this.getDynamicTableFilters(e,t,i);return{id:t.id,range:a,filters:o,config:t.config}}getDynamicTableFilters(e,t,n){let r=[],{top:i,bottom:a,left:o,right:s}=n;for(let n=o;n<=s;n++){let s=n-o,c={left:n,right:n,top:i,bottom:a},l=eI(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:!jn(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=un(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 jn(s.range.zone)){let r={sheetId:t.id,...n},i=this.getters.getCellComputedStyle(r),a=this.getters.getCellComputedBorder(r),o=T(n.col,n.row);if(!ut(i)){let n=_c(i,e.styles);t.styles[o]=n}if(a){let n=_c(a,e.borders);t.borders[o]=n}}}t.tables=n}}},gG=class extends LW{static getters=[`getChartRuntime`,`getStyleOfSingleCellChart`];charts={};createRuntimeChart=h_(this.getters);handle(e){if(Ps.has(e.type)||Ls.has(e.type)||Fs.has(e.type))for(let e in this.charts)this.charts[e]=void 0;switch(e.type){case`UPDATE_CHART`:case`CREATE_CHART`:this.charts[e.chartId]=void 0;break;case`DELETE_CHART`:this.charts[e.chartId]=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:od(e)};if(!t)return{background:oe,fontColor:od(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||od(o)}}async 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=this.getters.getChartIds(t.id).find(e=>this.getters.getFigureIdFromChartId(e)===r.id);if(!e)continue;let i=this.getters.getChart(e),a=i?.getDefinitionForExcel(this.getters);if(a)n.push({...r,data:a});else{if(!i)continue;let n=this.getters.getChartType(e),a=await Hp(this.getters.getChartRuntime(e),r,n);a&&t.images.push({...r,tag:`image`,data:{mimetype:`image/png`,path:a,size:{width:r.width,height:r.height}}})}}t.charts=n}}},_G=class extends LW{static getters=[`getConditionalIcon`,`getCellConditionalFormatStyle`,`getConditionalDataBar`];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(Ps.has(e.type)||Ls.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]=mt(()=>this.getComputedStyles(e)),this.computedIcons[e]=mt(()=>this.getComputedIcons(e)),this.computedDataBars[e]=mt(()=>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(`=`)?lU(e):void 0);for(let i of n.ranges){let a=this.getters.getRangeFromSheetXC(e,i).zone;for(let i=a.top;i<=a.bottom;i++)for(let o=a.left;o<=a.right;o++){let s={sheetId:e,col:o,row:i},c=n.rule.values.map((t,n)=>{let s=r[n];return s?this.getters.getTranslatedCellFormula(e,o-a.left,i-a.top,s.tokens):t});this.getRuleResultForTarget(s,{...n.rule,values:c})&&(t[o]||(t[o]=[]),t[o][i]=Object.assign(t[o]?.[i]||{},n.rule.style))}}break}return t}getComputedIcons(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`IconSetRule`)for(let r of n.ranges)this.applyIcon(e,r,n.rule,t);return t}getComputedDataBars(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`DataBarRule`)for(let r of n.ranges)this.applyDataBar(e,r,n.rule,t);return t}parsePoint(e,t,n,r){let i=this.getters.getRangeFromSheetXC(e,t).zone,a=this.getters.getEvaluatedCellsInZone(e,i).filter(e=>e.type===`number`).map(e=>e.value);switch(n.type){case`value`:return r===`max`?Pt(a):Ft(a);case`number`:return Number(n.value);case`percentage`:let t=Ft(a);return t+(Pt(a)-t)*Number(n.value)/100;case`percentile`:return na(a,Number(n.value)/100,!0);case`formula`:let i=n.value&&this.getters.evaluateFormula(e,n.value);return typeof i==`number`?i: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=Pt(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});!En(i,l,c)||u.type!==`number`||u.value<=0||(r[n]||(r[n]=[]),r[n][t]={color:Sr(o),percentage:u.value*100/a})}}applyColorScale(e,t,n,r){let i=this.parsePoint(e,t,n.minimum,`min`),a=n.midpoint?this.parsePoint(e,t,n.midpoint):null,o=this.parsePoint(e,t,n.maximum,`max`);if(i===null||o===null||i>=o||a&&(i>=a||a>=o))return;let s=this.getters.getRangeFromSheetXC(e,t).zone,c=[{value:i,color:n.minimum.color}];n.midpoint&&a&&c.push({value:a,color:n.midpoint.color}),c.push({value:o,color:n.maximum.color});let l=ai(c);for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let a=this.getters.getEvaluatedCell({sheetId:e,col:n,row:t});if(a.type===`number`){let e=x(a.value,i,o);r[n]||(r[n]=[]),r[n][t]=r[n]?.[t]||{},r[n][t].fillColor=l(e)}}}getRuleResultForTarget(e,t){let n=this.getters.getEvaluatedCell(e);if(n.type===`error`)return!1;let{sheetId:r}=e,i=W.get(t.operator),a=t.values.map(t=>t.startsWith(`=`)?this.getters.evaluateFormula(r,t,e)??``:nc(t,R));if(a.some(gm))return!1;let o={type:t.operator,values:a.map(mm),dateValue:t.dateValue||`exactDate`};return i.isValueValid(n.value??``,o,this.getters,r)}};let vG={isValid:!0};var yG=class extends LW{static getters=[`getDataValidationInvalidCriterionValueMessage`,`getInvalidDataValidationMessage`,`getValidationResultForCellValue`,`getDataValidationRangeValues`,`isCellValidCheckbox`,`getDataValidationCellStyle`,`getDataValidationChipStyle`,`isDataValidationInvalid`];validationResults={};handle(e){if(Ps.has(e.type)||e.type===`EVALUATE_CELLS`||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)){this.validationResults={};return}switch(e.type){case`ADD_DATA_VALIDATION_RULE`:case`REMOVE_DATA_VALIDATION_RULE`:delete this.validationResults[e.sheetId];break}}isDataValidationInvalid(e){return!this.getValidationResultForCell(e).isValid}getDataValidationCellStyle(e){if(!this.hasChip(e))return this.getDataValidationStyle(e)}getDataValidationChipStyle(e){if(this.hasChip(e))return this.getDataValidationStyle(e)??{fillColor:`#E7E9ED`}}getInvalidDataValidationMessage(e){let t=this.getValidationResultForCell(e);return t.isValid?void 0:t.error}getDataValidationInvalidCriterionValueMessage(e,t){let n=W.get(e);return t.startsWith(`=`)?n.allowedValues===`onlyLiterals`?k(`The value must not be a formula`):this.isValidFormula(t)?void 0:H.CriterionError.validFormula:n.allowedValues===`onlyFormulas`?k(`The value must be a formula`):n.isCriterionValueValid(t)?void 0:n.criterionValueErrorString}getDataValidationRangeValues(e,t){let n=this.getters.getRangeFromSheetXC(e,String(t.values[0])),r=[],i=new Set;for(let e of jn(n.zone)){let t=this.getters.getEvaluatedCell({...e,sheetId:n.sheetId});t.formattedValue&&!i.has(t.formattedValue)&&(i.add(t.formattedValue),r.push({label:t.formattedValue,value:t.value?.toString()||``}))}return r}isCellValidCheckbox(e){if(!this.getters.isMainCellPosition(e))return!1;let t=this.getters.getValidationRuleForCell(e);return!t||t.criterion.type!==`isBoolean`?!1:this.getValidationResultForCell(e).isValid}getValidationResultForCellValue(e,t){let n=this.getters.getValidationRuleForCell(t);if(!n)return vG;let r=this.getRuleErrorForCellValue(e,t,n);return r?{error:r,rule:n,isValid:!1}:vG}hasChip(e){let t=this.getters.getValidationRuleForCell(e);return(t?.criterion.type===`isValueInList`||t?.criterion.type===`isValueInRange`)&&t.criterion.displayStyle===`chip`}getDataValidationStyle(e){let t=this.getters.getValidationRuleForCell(e);if(!t||this.isDataValidationInvalid(e))return;let n=this.getters.getEvaluatedCell(e),r=this.getValueColor(t,n.value);if(r)return{fillColor:r,textColor:Ur(r)}}getValueColor(e,t){if(!(e.criterion.type!==`isValueInList`&&e.criterion.type!==`isValueInRange`)){for(let n in e.criterion.colors)if(n.toLowerCase()===String(t).toLowerCase())return e.criterion.colors[n]}}isValidFormula(e){return!lU(e).isBadExpression}getValidationResultForCell(e){let{col:t,row:n,sheetId:r}=e;return this.validationResults[r]||(this.validationResults[r]=this.computeSheetValidationResults(r)),this.validationResults[r][t]?.[n]?.()||vG}computeSheetValidationResults(e){let t={},n=this.getters.getDataValidationRules(e).map(e=>e.ranges);for(let e of Qc(n.flat())){let{col:n,row:r}=e;t[n]||(t[n]=[]),t[n][r]=mt(()=>{let t=this.getters.getEvaluatedCell(e);return t.type===`empty`?vG:this.getValidationResultForCellValue(t.value,e)})}return t}getRuleErrorForCellValue(e,t,n){let{sheetId:r}=t,i=n.criterion,a=W.get(i.type),o=this.getCellOffsetInRule(t,n),s=this.getEvaluatedCriterionValues(r,t,o,i);if(s.some(gm))return;let c={...i,values:s.map(mm)};if(!a.isValueValid(e,c,this.getters,r))return a.getErrorString(c,this.getters,r)}getCellOffsetInRule(e,t){let n=t.ranges.find(t=>En(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,r){return r.values.map(r=>{if(!r.startsWith(`=`))return nc(r,R);let i=lU(r),a=this.getters.getTranslatedCellFormula(e,n.col,n.row,i.tokens);return this.getters.evaluateFormula(e,a,t)})}},bG=class extends LW{static getters=[`getRowSize`,`getHeaderSize`,`getMaxAnchorOffset`];tallestCellInRow={};ctx=Sl();beforeHandle(e){switch(e.type){case`ADD_COLUMNS_ROWS`:if(e.dimension===`COL`)return;let t=gt(e.position,e.base),n=Array(e.quantity).fill(void 0),r=kt(this.tallestCellInRow[e.sheetId],n,t);this.history.update(`tallestCellInRow`,e.sheetId,r);break}}handle(e){switch(e.type){case`START`:case`UPDATE_LOCALE`:for(let e of this.getters.getSheetIds())this.initializeSheet(e);break;case`CREATE_SHEET`:this.initializeSheet(e.sheetId);break;case`DUPLICATE_SHEET`:{let t=b(this.tallestCellInRow[e.sheetId]);this.history.update(`tallestCellInRow`,e.sheetIdTo,t);break}case`DELETE_SHEET`:let t={...this.tallestCellInRow};delete t[e.sheetId],this.history.update(`tallestCellInRow`,t);break;case`REMOVE_COLUMNS_ROWS`:{if(e.dimension===`COL`)return;let t=Ot(this.tallestCellInRow[e.sheetId],e.elements);this.history.update(`tallestCellInRow`,e.sheetId,t);break}case`RESIZE_COLUMNS_ROWS`:{let t=e.sheetId;if(e.dimension===`ROW`)for(let n of e.elements){let e=this.getRowTallestCell(t,n);this.history.update(`tallestCellInRow`,t,n,e)}else for(let n of S(0,this.getters.getNumberRows(t)))for(let r of e.elements)this.updateRowSizeForCellChange(t,n,r)}break;case`SET_FORMATTING`:if(e.style&&(`fontSize`in e.style||`wrapping`in e.style||`rotation`in e.style))for(let t of e.target)this.updateRowSizeForZoneChange(e.sheetId,t);break;case`UPDATE_CELL`:this.updateRowSizeForCellChange(e.sheetId,e.row,e.col);break;case`ADD_MERGE`:case`REMOVE_MERGE`:for(let t of e.target)for(let n of jn(t))this.updateRowSizeForCellChange(e.sheetId,n.row,n.col)}}getRowSize(e,t){return Math.round(this.getters.getUserRowSize(e,t)??this.tallestCellInRow[e][t]?.size??23)}getMaxAnchorOffset(e,t,n){let{numberOfRows:r,numberOfCols:i}=this.getters.getSheetSize(e),a=0;for(;a<t&&r>0;r--)a+=this.getRowSize(e,r-1);let o=0;for(;o<n&&i>0;i--)o+=this.getters.getColSize(e,i-1);return{col:i,row:r,offset:{x:o-n,y:a-t}}}getHeaderSize(e,t,n){return this.getters.isHeaderHidden(e,t,n)?0:t===`ROW`?this.getRowSize(e,n):this.getters.getColSize(e,n)}updateRowSizeForZoneChange(e,t){for(let n=t.top;n<=t.bottom;n++){let t=this.getRowTallestCell(e,n);this.history.update(`tallestCellInRow`,e,n,t)}}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.getCellStyle(e),r=this.getters.getColSize(e.sheetId,e.col);return Cl(this.ctx,t,n,this.getters.getLocale(),r)}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 xG=`0.00%`;function SG(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=ch[e.aggregator];if(!r)return{value:0};try{return r([n],this.getters.getLocale())}catch(t){return Sy(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}=bL(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new ha:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}if(r.find(t=>t.nameWithGranularity===e)){let{rowDomain:n}=bL(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new ha:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}return this.getPivotCellValueAndFormat(e,t)});return xa(a)?a[0][0]:a}getValuesToAggregate(e,t){let{rowDomain:n,colDomain:r}=bL(this,t),i=super.getExpandedTableStructure(),a=[];if(r.length===0&&n.length<this.definition.rows.length&&this.definition.rows.length&&this.definition.columns.length){let t=this.treeToLeafDomains(i.getColTree()),r=this.getSubTreeMatchingDomain(i.getRowTree(),n),o=this.treeToLeafDomains(r);for(let r of t)for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t).concat(r)));return a}else if(n.length===this.definition.rows.length&&r.length===0){let t=i.getColTree(),o=this.getSubTreeMatchingDomain(t,r),s=this.treeToLeafDomains(o,r);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else if(n.length===this.definition.rows.length&&r.length&&r.length<this.definition.columns.length){let t=this.getSubTreeMatchingDomain(i.getColTree(),r),o=this.treeToLeafDomains(t,r);for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else{let t=i.getRowTree(),o=this.getSubTreeMatchingDomain(t,n),s=this.treeToLeafDomains(o,n);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,t.concat(r)));return a}}getSubTreeMatchingDomain(e,t,n=0){if(n>t.length)return[];if(t.length===n)return e;for(let r of e){let e=_h(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:A.NotAvailable,message:k(`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 Sy(e,`COMPUTE_MEASURE_DISPLAY_VALUE`)}}asPercentOfGrandTotal(e,t){let n=this.getGrandTotal(t.id);return n===0?{value:A.DivisionByZero}:{value:this.measureValueToNumber(e)/n,format:xG}}asPercentOfRowTotal(e,t,n){let r=this.getRowTotal(t.id,n);return r===0?{value:A.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:xG}}asPercentOfColumnTotal(e,t,n){let r=this.getColumnTotal(t.id,n);return r===0?{value:A.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:xG}}asPercentOfParentRowTotal(e,t,n){let r=vL(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:xG}}asPercentOfParentColumnTotal(e,t,n){let r=yL(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:xG}}asPercentOfParentTotal(e,t,n,r){let{fieldNameWithGranularity:i}=r;if(!i)return e;if(!OL(i,n))return{value:``};let a=EL(this,i,n),o=this._getPivotCellValueAndFormat(t.id,a),s=this.measureValueToNumber(o);return s===0?{value:``}:{value:this.measureValueToNumber(e)/s,format:xG}}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:A.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}=bL(this,n),u=jL(l),d=jL(c);return{value:s[u]?.[d]??``,format:i===`running_total`?e.format:xG}}asPercentOf(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!OL(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0||o===`sameValue`&&s===0?{value:A.DivisionByZero}:!o||o===`sameValue`&&!s?{value:``}:o===`sameValue`?{value:1,format:xG}:s===void 0?{value:A.NullError}:{value:s/o,format:xG}}asDifferenceFrom(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!OL(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(!OL(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0?{value:A.DivisionByZero}:!o||o===`sameValue`?{value:``}:s===void 0?{value:A.NullError}:{value:(s-o)/o,format:xG}}asRank(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;if(!OL(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}=bL(this,n),u=jL(l),d=jL(c);return{value:s[u]?.[d]??``}}computeRank(e,t,n){let r={},i=kL(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=qa(o));for(let s of o){let o=jL(xL(this,a,s[0].domain)),c=s.map(t=>({...t,value:this.strictMeasureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain)),rowDomain:xL(this,i,t.domain)})).filter(e=>OL(t,e.rowDomain)),l=Object.groupBy(c,e=>NL(e.rowDomain,t));for(let e in l)l[e]=Lt(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=jL(xL(this,i,e.domain)),a=l[NL(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:Rt(r)}computeRunningTotal(e,t,n){let r={},i=kL(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=qa(o));for(let s of o){let o=jL(xL(this,a,s[0].domain));r[o]={};let c={},l=s.map(t=>({...t,rowDomain:xL(this,i,t.domain),value:this.measureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain))})).filter(e=>OL(t,e.rowDomain));for(let e of l){let n=jL(e.rowDomain),i=PL(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=jL(n),a=PL(n,t),s=r[o][i]||0,l=c[a];r[o][i]=l?s/l:void 0}}return i===`row`?r:Rt(r)}getGrandTotal(e){let t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){let n=bL(this,t).rowDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}getColumnTotal(e,t){let n=bL(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)`?AL(this,t,n,r):DL(t,n,r);if(w(i,t))return`sameValue`;if(!i||!CL(this,i))throw new ha;let a=this._getPivotCellValueAndFormat(e.id,i);return this.strictMeasureValueToNumber(a)}getPivotValueCells(e){return this.getCollapsedTableStructure().getPivotCells().map(t=>t.filter(t=>t.type===`VALUE`&&t.measure===e)).filter(e=>e.length>0)}measureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(!e.value)return 0;throw Error(`Value ${e.value} is not a number`)}strictMeasureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(e.value)throw Error(`Value ${e.value} is not a number`)}getCollapsedTableStructure(){let e=super.getCollapsedTableStructure();return this.sortTableStructure(e),e}getExpandedTableStructure(){let e=super.getExpandedTableStructure();return this.sortTableStructure(e),e}sortTableStructure(e){if(!this.definition.sortedColumn||e.isSorted)return;let t=this.definition.sortedColumn.measure;Th(this.definition.sortedColumn,this)&&e.sort(t,this.definition.sortedColumn,(e,t)=>this._getPivotCellValueAndFormat(e,t))}}return t}let CG=[`ADD_PIVOT`,`UPDATE_PIVOT`,`REMOVE_PIVOT`];function wG(e){return CG.includes(e.type)}var TG=class extends LW{static getters=[`getPivot`,`getFirstPivotFunction`,`getPivotCellSortDirection`,`getPivotIdFromPosition`,`getPivotCellFromPosition`,`generateNewCalculatedMeasureName`,`isPivotUnused`,`isSpillPivotFormula`];pivots={};unusedPivotsInFormulas;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(Ps.has(e.type))for(let e of this.getters.getPivotIds())this.setupPivot(e,{recreate:!0});switch(e.type){case`REFRESH_PIVOT`:this.refreshPivot(e.id);break;case`ADD_PIVOT`:this.setupPivot(e.pivotId);break;case`DUPLICATE_PIVOT`:this.setupPivot(e.newPivotId);break;case`UPDATE_PIVOT`:this.setupPivot(e.pivotId,{recreate:!0});break;case`DELETE_SHEET`:case`UPDATE_CELL`:this.unusedPivotsInFormulas=void 0;break;case`UNDO`:case`REDO`:{this.unusedPivotsInFormulas=void 0;let t=e.commands.filter(wG);for(let e of t){let t=e.pivotId;this.getters.isExistingPivot(t)&&this.setupPivot(t,{recreate:!0})}break}case`UPDATE_LOCALE`:Rh();break}}getPivotIdFromPosition(e){let t=this.getters.getCorrespondingFormulaCell(e);if(t&&t.isFormula){let n=this.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(n){let e=n.args[0]?.toString();return e&&this.getters.getPivotId(e)}}}isSpillPivotFormula(e){let t=this.getters.getCorrespondingFormulaCell(e);return t&&t.isFormula?this.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens)?.functionName===`PIVOT`:!1}getFirstPivotFunction(e,t){let n=EU(t);if(!n)return;let{functionName:r,args:i}=n;return{functionName:r,args:i.map(t=>{if(t.type===`EMPTY`)return;if(t.type===`STRING`||t.type===`BOOLEAN`||t.type===`NUMBER`)return t.value;let n=yB(t);return this.getters.evaluateFormula(e,n)})}}getPivotCellFromPosition(e){let t=this.getters.getCorrespondingFormulaCell(e);if(!t||!t.isFormula||DU(t.compiledFormula.tokens)===0)return BL;let n=this.getters.getCellPosition(t.id),r=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(!r)return BL;let{functionName:i,args:a}=r,o=a[0];if(!o)return BL;let s=this.getters.getPivotId(o.toString());if(!s)return BL;let c=this.getPivot(s);if(!c.isValid()||i===`PIVOT`&&!t.content.replaceAll(` `,``).toUpperCase().startsWith(`=PIVOT`))return BL;try{if(i===`PIVOT`){let t=Nh(this.getters.getPivotCoreDefinition(s),mm(a[1]),mm(a[2]),mm(a[3]),mm(a[4]),mm(a[5]),this.getters.getLocale()),r=c.getCollapsedTableStructure().getPivotCells(t),i=e.col-n.col,o=e.row-n.row;return r[i][o]}let t=e.row-n.row,r=e.col-n.col;if(a=a.map(e=>xa(e)?e[r][t]:e),i===`PIVOT.HEADER`&&a.at(-2)===`measure`)return{type:`MEASURE_HEADER`,domain:c.parseArgsToPivotDomain(a.slice(1,-2).map(e=>({value:e}))),measure:a.at(-1)?.toString()||``};if(i===`PIVOT.HEADER`){let e=c.parseArgsToPivotDomain(a.slice(1).map(e=>({value:e})));return{type:`HEADER`,domain:e,dimension:bL(c,e).colDomain.length?`COL`:`ROW`}}let[o,...l]=a.slice(1);return{type:`VALUE`,domain:c.parseArgsToPivotDomain(l.map(e=>({value:e}))),measure:o?.toString()||``}}catch{return BL}}generateNewCalculatedMeasureName(e){let t=e.map(e=>e.fieldName);return zt(k(`Calculated measure 1`),t,{compute:(e,t)=>k(`Calculated measure %s`,t)})}getPivot(e){if(!this.getters.isExistingPivot(e))throw Error(`pivot ${e} not found`);return this.pivots[e]}isPivotUnused(e){let{type:t}=this.getters.getPivot(e);return this._getUnusedPivotsInFormulas().includes(e)&&ZL.get(t).isPivotUnused(this.getters,e)}getPivotCellSortDirection(e){let t=this.getters.getPivotIdFromPosition(e),n=this.getters.getPivotCellFromPosition(e);if(n.type===`EMPTY`||n.type===`HEADER`||!t)return;let r=this.getters.getPivot(t),i=bL(r,n.domain).colDomain,a=r.definition.sortedColumn;return a?.measure===n.measure&&w(a.domain,i)?a.order:`none`}refreshPivot(e){this.getters.getPivot(e).init({reload:!0})}setupPivot(e,{recreate:t}={recreate:!1}){let n=b(this.getters.getPivotCoreDefinition(e));if(e in this.pivots)t&&this.pivots[e].onDefinitionChange(n);else{let t=SG(ZL.get(n.type).ui);this.pivots[e]=new t(e,this.custom,{definition:n,getters:this.getters})}}_getUnusedPivotsInFormulas(){if(this.unusedPivotsInFormulas!==void 0)return this.unusedPivotsInFormulas;let e=new Set(this.getters.getPivotIds());for(let t of this.getters.getSheetIds())for(let n in this.getters.getCells(t)){let t=this.getters.getCellPosition(n),r=this.getPivotIdFromPosition(t);if(r&&(e.delete(r),!e.size))return this.unusedPivotsInFormulas=[],[]}return this.unusedPivotsInFormulas=[...e],this.unusedPivotsInFormulas}},EG=class{getters;dispatch;constructor(e,t){this.getters=e,this.dispatch=t}copy(e,t,n=`copyPaste`){}paste(e,t,n){}isPasteAllowed(e,t,n,r){return`Success`}isCutAllowed(e){return`Success`}getPasteTarget(e,t,n,r){return{zones:[],sheetId:e}}convertTextToClipboardData(e){}},DG=class extends EG{copy(e,t,n=`copyPaste`){}pasteFromCopy(e,t,n,r){if(t.length===1)for(let i of rA(t,n))this.pasteZone(e,i.left,i.top,n,r);else for(let i of Qt(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){}},OG=class extends DG{isCutAllowed(e){return e.zones.length===1?`Success`:`WrongCutSelection`}copy(e,t,n=`copyPaste`){let r=e.sheetId,{clippedZones:i,rowsIndexes:a,columnsIndexes:o}=e,s=[],c=a.length===1&&o.length===1;for(let t of a){let i=[];for(let s of o){let l={col:s,row:t,sheetId:r},u=this.getters.getCell(l),d=this.getters.getEvaluatedCell(l),f=this.getters.getPivotIdFromPosition(l),p=this.getters.getArrayFormulaSpreadingOn(l);if(n!==`shiftCells`&&f&&p){let t=this.getters.getSpreadZone(p);if((!w(p,l)||!c)&&t&&!e.zones.some(e=>Dn(t,e))){let e=this.getters.getPivotCellFromPosition(l),t=gh(this.getters.getPivotFormulaId(f),e);u={id:u?.id||``,format:u?.format,content:t,isFormula:!1,parsedValue:d.value}}}else if(n!==`shiftCells`&&p&&!w(p,l)){let e=a.includes(p.row)&&o.includes(p.col)?``:z(d.value,{locale:this.getters.getLocale()});u={id:u?.id||``,format:d.format,content:e,isFormula:!1,parsedValue:d.value}}i.push({content:u?.content??``,format:u?.format,tokens:u?.isFormula?u.compiledFormula.tokens.map(({value:e,type:t})=>({value:e,type:t})):[],border:this.getters.getCellBorder(l)||void 0,evaluatedCell:d,position:l})}s.push(i)}return{cells:s,zones:i,sheetId:e.sheetId}}isPasteAllowed(e,t,n,r){if(!n.cells)return`Success`;if(r?.isCutOperation&&r?.pasteOption!==void 0)return`WrongPasteOption`;if(t.length>1&&(n.cells.length>1||n.cells[0].length>1))return`WrongPasteSelection`;let i=n.cells.length,a=n.cells[0].length;for(let r of rA(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:rA(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(`
|
|
117
|
-
`).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=qv(e[n]||``,t);r.push({content:i,evaluatedCell:{formattedValue:i}})}n.cells.push(r)}return n}},
|
|
118
|
-
%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=Qt(this.getters.getSelectedZones()),t=this.getters.getActiveSheetId(),n=0;for(let{col:r,row:i}of e.map(jn).flat()){let e=this.getters.getCell({col:r,row:i,sheetId:t});if(!e)continue;let a=jt(e.content);a!==e.content&&(n+=1,this.dispatch(`UPDATE_CELL`,{sheetId:t,col:r,row:i,content:a}))}let r=n?k(`Trimmed whitespace from %s cells.`,n):k(`No selected cells had whitespace trimmed.`);this.ui.notifyUI({type:`info`,text:r,sticky:!1})}};let AG=new B;AG.add(`ALPHANUMERIC_INCREMENT_MODIFIER`,{apply:(e,t)=>{e.current+=e.increment;let n=Math.abs(e.current).toString();n=`0`.repeat(Math.max(e.numberPostfixLength-n.length,0))+n;let r=`${e.prefix}${n}`;return{cellData:{border:t.border,style:t.style,format:t.cell&&t.cell.format,content:r},tooltip:{props:{content:r}}}}}).add(`INCREMENT_MODIFIER`,{apply:(e,t,n)=>{e.current+=e.increment;let r=e.current.toString(),i=n.getLocale(),a=z(e.current,{format:t.cell?.format,locale:i});return{cellData:{border:t.border,style:t.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:a}}:void 0}}}).add(`DATE_INCREMENT_MODIFIER`,{apply:(e,t,n)=>{let r=I(e.current,n.getLocale());r.setFullYear(r.getFullYear()+e.increment.years||0),r.setMonth(r.getMonth()+e.increment.months||0),r.setDate(r.getDate()+e.increment.days||0);let i=Fi(r);e.current=i;let a=n.getLocale(),o=z(i,{format:t.cell?.format,locale:a});return{cellData:{border:t.border,style:t.style,format:t.cell&&t.cell.format,content:i.toString()},tooltip:i?{props:{content:o}}:void 0}}}).add(`COPY_MODIFIER`,{apply:(e,t,n)=>{let r=t.cell?.content||``,i={locale:n.getLocale(),format:t.cell?.format};return{cellData:{border:t.border,style:t.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:t.cell?tc(t.cell,i).formattedValue:``}}:void 0}}}).add(`FORMULA_MODIFIER`,{apply:(e,t,n,r)=>{e.current+=e.increment;let i=0,a=0;switch(r){case`up`:i=0,a=-e.current;break;case`down`:i=0,a=e.current;break;case`left`:i=-e.current,a=0;break;case`right`:i=e.current,a=0;break}let o=t.cell;if(!o||!o.isFormula)return{cellData:{}};let s=t.sheetId,c=n.getTranslatedCellFormula(s,i,a,o.compiledFormula.tokens);return{cellData:{border:t.border,style:t.style,format:o.format,content:c},tooltip:c?{props:{content:c}}:void 0}}});let jG=new B,MG=/(\d+)$/,NG=/^(.*\D+)/,PG=/^(.*\D+)(\d+)$/,FG=/^0*/;function IG(e,t,n){let r=[],i=!1;for(let a of t){a===e&&(i=!0);let t=a===void 0||a.isFormula?void 0:tc(a,{locale:R,format:a.format});if(t&&n(t))r.push(t);else{if(i)return r;r=[]}}return r}function LG(e){let t=[],n=e[0];for(let r=1;r<e.length;r++){let i=e[r];t.push(i-n),n=i}return t.reduce((e,t)=>e+t,0)/t.length}function RG(e){let t=1;return e.length>=2&&(t=LG(e)*e.length),t}function zG(e){return e.length<2?e[0]||{years:0,months:0,days:0}:e.every(t=>t.years===e[0].years&&t.months===e[0].months&&t.days===e[0].days)?e[0]:void 0}function BG(e){if(e.length<2)return 1;let t=e.map(e=>I(e,R)),n=zG(VG(t));if(n===void 0)return;let r=Object.values(n).filter(e=>e!==0).length===1,i=Object.values(n).every(e=>e===0);if(!r||i){let n=t.map((e,n)=>{if(n===0)return 0;let r=t[n-1];return Math.floor(e.getTime())-Math.floor(r.getTime())}).slice(1);if(n.every(e=>e===n[0]))return e.length*(e[1]-e[0])}return{years:n.years*e.length,months:n.months*e.length,days:n.days*e.length}}jG.add(`simple_value_copy`,{condition:(e,t)=>t.length===1&&!e.isFormula&&!(e.format&&ns(e.format)),generateRule:()=>({type:`COPY_MODIFIER`}),sequence:10}).add(`increment_alphanumeric_value`,{condition:e=>!e.isFormula&&tc(e,{locale:R}).type===`text`&&PG.test(e.content),generateRule:(e,t,n)=>{let r=parseInt(e.content.match(MG)[0]),i=e.content.match(NG)[0],a=IG(e,t,e=>e.type===`text`&&PG.test(e.value)).filter(e=>i===(e.value??``).toString().match(NG)[0]).map(e=>(e.value??``).toString().match(MG)[0]),o=a.reduce((e,t)=>{let n=t.match(FG)[0].length;return n>e[1]?[t,n]:e},[a[0],0]),s=o[1]?o[0].length:0,c=RG(a.map(e=>parseInt(e)));return[`up`,`left`].includes(n)&&a.length===1&&(c=-c),{type:`ALPHANUMERIC_INCREMENT_MODIFIER`,prefix:i,current:r,increment:c,numberPostfixLength:s}},sequence:15}).add(`copy_text`,{condition:e=>!e.isFormula&&tc(e,{locale:R}).type===`text`,generateRule:()=>({type:`COPY_MODIFIER`}),sequence:20}).add(`update_formula`,{condition:e=>e.isFormula,generateRule:(e,t)=>({type:`FORMULA_MODIFIER`,increment:t.length,current:0}),sequence:30}).add(`increment_dates`,{condition:(e,t)=>!e.isFormula&&tc(e,{locale:R}).type===`number`&&!!e.format&&ns(e.format),generateRule:(e,t)=>{let n=BG(IG(e,t,e=>e.type===`number`&&!!e.format&&ns(e.format)).map(e=>Number(e.value)));if(n===void 0)return{type:`COPY_MODIFIER`};let r=tc(e,{locale:R});return typeof n==`object`?{type:`DATE_INCREMENT_MODIFIER`,increment:n,current:r.type===`number`?r.value:0}:{type:`INCREMENT_MODIFIER`,increment:n,current:r.type===`number`?r.value:0}},sequence:25}).add(`increment_number`,{condition:e=>!e.isFormula&&tc(e,{locale:R}).type===`number`,generateRule:(e,t,n)=>{let r=IG(e,t,e=>e.type===`number`&&!ns(e.format||``)).map(e=>Number(e.value)),i=RG(r);[`up`,`left`].includes(n)&&r.length===1&&(i=-i);let a=tc(e,{locale:R});return{type:`INCREMENT_MODIFIER`,increment:i,current:a.type===`number`?a.value:0}},sequence:40});function VG(e){return e.length<2?[{years:0,months:0,days:0}]:e.map((t,n)=>{if(n===0)return{years:0,months:0,days:0};let r=O.fromTimestamp(e[n-1].getTime()),i=Ui(r,t),a=Vi(r,t)%12;return r.setFullYear(r.getFullYear()+i),r.setMonth(r.getMonth()+a),{years:i,months:a,days:Hi(r,t)}}).slice(1)}var HG=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}=AG.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}}}},UG=class extends cb{static layers=[`Autofill`];static getters=[`getAutofillTooltip`];autofillZone;steps;lastCellSelected={};direction;tooltip;allowDispatch(e){switch(e.type){case`AUTOFILL_SELECT`:let t=this.getters.getActiveSheetId();return this.lastCellSelected.col=e.col===-1?this.lastCellSelected.col:x(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=e.row===-1?this.lastCellSelected.row:x(e.row,0,this.getters.getNumberRows(t)),this.lastCellSelected.col!==void 0&&this.lastCellSelected.row!==void 0?`Success`:`InvalidAutofillSelection`}return`Success`}handle(e){switch(e.type){case`AUTOFILL`:this.autofill(!0);break;case`AUTOFILL_SELECT`:this.select(e.col,e.row);break;case`AUTOFILL_AUTO`:this.autofillAuto();break}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||this.direction===void 0){this.tooltip=void 0;return}let t=this.getters.getSelectedZone(),n=this.autofillZone,r=[];switch(this.direction){case`down`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.top;n<=t.bottom;n++)i.push(T(e,n));let a=this.createGenerator(i);for(let t=n.top;t<=n.bottom;t++)r.push(this.computeNewCell(a,e,t))}break;case`up`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.bottom;n>=t.top;n--)i.push(T(e,n));let a=this.createGenerator(i);for(let t=n.bottom;t>=n.top;t--)r.push(this.computeNewCell(a,e,t))}break;case`left`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.right;n>=t.left;n--)i.push(T(n,e));let a=this.createGenerator(i);for(let t=n.right;t>=n.left;t--)r.push(this.computeNewCell(a,t,e))}break;case`right`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.left;n<=t.right;n++)i.push(T(n,e));let a=this.createGenerator(i);for(let t=n.left;t<=n.right;t++)r.push(this.computeNewCell(a,t,e))}break}if(e){let e={},t={},n={},i=this.getters.getActiveSheetId();for(let a of r)this.collectBordersData(a,e),this.autofillMerge(i,a),this.autofillCell(i,a),this.collectConditionalFormatsData(i,a,t),this.collectDataValidationsData(i,a,n);this.autofillBorders(i,e),this.autofillConditionalFormats(i,t),this.autofillDataValidations(i,n),this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0}}collectBordersData(e,t){let n=JSON.stringify(e.border);n in t||(t[n]=[]),t[n].push(E({col:e.col,row:e.row}))}collectConditionalFormatsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s=this.getters.getRulesByCell(e,r,i),c=T(a,o);for(let e of s)e.id in n||(n[e.id]=[]),n[e.id].push(c)}collectDataValidationsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s={sheetId:e,col:r,row:i},c=this.getters.getValidationRuleForCell(s);c&&(c.id in n||(n[c.id]=[]),n[c.id].push(E({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:Qt(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(un),[]);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=Qt(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(En(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=jG.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}=Zt(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,a=this.getters.getCellStyle(e);t.push({data:{...e,border:r,style:a},rule:n})}return new HG(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([]))}},WG=class extends cb{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}=En(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)||kn(bn(a,t))?[{position:{col:r,row:i},zone:a}]:this.sumDimensions(e,bn(a,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,n){let r=this.getters.getSheet(e),i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.findSuitableZoneToSum(r,i.col,i.row);if(a)return this.getters.expandZone(e,a)}findSuitableZoneToSum(e,t,n){let r=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:n-1}),i=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:n});if(this.isNumber(i)&&!this.isNumber(r))return this.findHorizontalZone(e,t,n);let a=this.findVerticalZone(e,t,n);if(this.isZoneValid(a))return a;let o=this.findHorizontalZone(e,t,n);if(this.isZoneValid(o))return o}findVerticalZone(e,t,n){let r={top:0,bottom:n-1,left:t,right:t},i=this.reduceZoneStart(e,r,r.bottom);return{...r,top:i}}findHorizontalZone(e,t,n){let r={top:n,bottom:n,left:0,right:t-1},i=this.reduceZoneStart(e,r,r.right);return{...r,left:i}}reduceZoneStart(e,t,n){let r=this.getters.getEvaluatedCellsInZone(e.id,t),i=S(n,-1,-1),a=Pt(i.filter(e=>r[e]&&!r[e].isAutoSummable)),o=Ze(i.filter(e=>this.isNumber(r[e])))[0]||[];return Pt(o)<a?1/0:Ft(o)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===`number`&&!(e.format&&ns(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 kn(t)?(n.add(On(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)},jn(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)},jn(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`))}},GG=class extends cb{static getters=[`getCellTableStyle`,`getCellTableBorder`,`getCellTableBorderZone`,`getCellTableStyleZone`];tableStyles={};handle(e){if(Ps.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tableStyles={};return}if(qG(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]}getCellTableStyleZone(e,t){let n=new bF;for(let r of this.getters.getTablesOverlappingZones(e,[t])){let t=this.tableStyles[e][r.id]().styles;for(let r of Object.keys(t)){let i=t[r],a=parseInt(r);for(let t of Object.keys(i)){let r=i[t];r&&n.set({sheetId:e,col:a,row:parseInt(t)},r)}}}return n}getCellTableBorder(e){let t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().borders[e.col]?.[e.row]}getCellTableBorderZone(e,t){let n=new bF;for(let r of this.getters.getTablesOverlappingZones(e,[t])){let t=this.tableStyles[e][r.id]().borders;for(let r of Object.keys(t)){let i=t[r],a=parseInt(r);for(let t of Object.keys(i)){let r=i[t];r&&n.set({sheetId:e,col:a,row:parseInt(t)},r)}}}return n}computeTableStyle(e,t){return mt(()=>{let{config:n,numberOfCols:r,numberOfRows:i}=this.getTableRuntimeConfig(e,t),a=nI(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 KG=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 qG(e){return KG.has(e.type)}var JG=class extends cb{static getters=[`getCellComputedBorder`,`getCellComputedStyle`];styles=new bF;borders=new bF;handle(e){if(Ps.has(e.type)||e.type===`UPDATE_CELL`||e.type===`SET_FORMATTING`||e.type===`CLEAR_FORMATTING`||e.type===`ADD_DATA_VALIDATION_RULE`||e.type===`REMOVE_DATA_VALIDATION_RULE`||e.type===`EVALUATE_CELLS`){this.styles=new bF,this.borders=new bF;return}if(qG(e)){`sheetId`in e?(this.styles.clearSheet(e.sheetId),this.borders.clearSheet(e.sheetId)):(this.styles=new bF,this.borders=new bF);return}if(Ls.has(e.type)){this.styles=new bF;return}if(Rs.has(e.type)){this.borders=new bF;return}}getCellComputedBorder(e){let t=this.borders.get(e);return t===void 0&&(t=this.computeCellBorder(e),this.borders.set(e,t)),t}getCellComputedStyle(e,t){let n=this.styles.get(e);return n===void 0&&(this.precomputeCellStyle(e.sheetId,t??E(e)),n=this.styles.get(e)??{}),n}precomputeCellStyle(e,t){let n=this.getters.getCellStyleInZone(e,t),r=this.getters.getCellTableStyleZone(e,t);for(let i=t.left;i<=t.right;i++)for(let a=t.top;a<=t.bottom;a++){let t={sheetId:e,col:i,row:a};if(this.styles.get(t)!==void 0)continue;let o={...bt(r.get(t)),...bt(this.getters.getDataValidationCellStyle(t)),...bt(n.get(t)),...bt(this.getters.getCellConditionalFormatStyle(t))};this.getters.getEvaluatedCell(t).link&&!o.textColor&&(o.textColor=`#017E84`),this.styles.set(t,o)}}computeCellBorder(e){let t=this.getters.getCellBorder(e)||{},n={...bt(this.getters.getCellTableBorder(e)||{}),...bt(t)};return ut(n)?null:n}},YG=class extends cb{static getters=[`hasBooleanValidationInZones`];handle(e){switch(e.type){case`TOGGLE_CHECKBOX`:this.toggleCheckbox(e.sheetId,e.target);break}}hasBooleanValidationInZones(e){let t=this.getters.getActiveSheetId();for(let n of e)for(let e=n.left;e<=n.right;e++)for(let r=n.top;r<=n.bottom;r++)if(this.getters.isCellValidCheckbox({col:e,row:r,sheetId:t}))return!0;return!1}toggleCheckbox(e,t){for(let n of t)for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++){let n={col:t,row:r,sheetId:e};if(this.getters.isCellValidCheckbox(n)){let e=this.getters.getEvaluatedCell(n).value?`FALSE`:`TRUE`;this.dispatch(`UPDATE_CELL`,{...n,content:e})}}}};let XG=new class extends B{addTransformation(e,t,n){this.content[e]||(this.content[e]=new Map);for(let r of t)this.content[e].set(r,n);return this}getTransformation(e,t){return this.content[t]&&this.content[t].get(e)}},ZG=new class extends B{add(e,t){return super.add(e,t),this}replace(e,t){return super.replace(e,t),this}get(e){return this.content[e]}};XG.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],uK),XG.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],uK),XG.addTransformation(`DELETE_SHEET`,[`MOVE_RANGES`],tK),XG.addTransformation(`DELETE_FIGURE`,[`UPDATE_FIGURE`,`UPDATE_CHART`,`UPDATE_CAROUSEL`],nK),XG.addTransformation(`DELETE_CHART`,[`UPDATE_CHART`],rK),XG.addTransformation(`DELETE_CHART`,[`UPDATE_CAROUSEL`],iK),XG.addTransformation(`CREATE_SHEET`,[`CREATE_SHEET`],aK),XG.addTransformation(`ADD_MERGE`,[`ADD_MERGE`,`REMOVE_MERGE`],oK),XG.addTransformation(`ADD_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],sK),XG.addTransformation(`REMOVE_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],sK),XG.addTransformation(`ADD_COLUMNS_ROWS`,[`UPDATE_TABLE`],cK),XG.addTransformation(`REMOVE_COLUMNS_ROWS`,[`UPDATE_TABLE`],cK),XG.addTransformation(`REMOVE_TABLE_STYLE`,[`CREATE_TABLE`,`UPDATE_TABLE`],lK),XG.addTransformation(`ADD_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],dK),XG.addTransformation(`REMOVE_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],dK),XG.addTransformation(`REMOVE_PIVOT`,[`RENAME_PIVOT`,`DUPLICATE_PIVOT`,`INSERT_PIVOT`,`UPDATE_PIVOT`],eK),XG.addTransformation(`DELETE_SHEET`,[`ADD_PIVOT`,`UPDATE_PIVOT`],$G),XG.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],QG),XG.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],QG);function QG(e,t){if(e.pivot.type!==`SPREADSHEET`||e.pivot.dataSet?.sheetId!==t.sheetId)return e;let n=Qn(e.pivot.dataSet.zone,t),r=n?{...e.pivot.dataSet,zone:n}:void 0;return{...e,pivot:{...e.pivot,dataSet:r}}}function $G(e,t){return e.pivot.type===`SPREADSHEET`&&e.pivot.dataSet?.sheetId===t.sheetId?{...e,pivot:{...e.pivot,dataSet:void 0}}:e}function eK(e,t){if(e.pivotId!==t.pivotId)return e}function tK(e,t){let n=t.sheetId;if(!(e.targetSheetId===n||e.sheetId===n))return e}function nK(e,t){if(e.figureId!==t.figureId)return e}function rK(e,t){if(e.chartId!==t.chartId)return e}function iK(e,t){return{...e,definition:{...e.definition,items:e.definition.items.filter(e=>!(e.type===`chart`&&e.chartId===t.chartId))}}}function aK(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 oK(e,t){if(e.sheetId!==t.sheetId)return e;let n=[];for(let r of e.target)t.target.every(e=>!wn(r,e))&&n.push(r);if(n.length)return{...e,target:n}}function sK(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 cK(e,t){if(e.sheetId!==t.sheetId)return e;let n=Qn(e.zone,t);if(!n)return;let r=e.newTableRange?$n(e.newTableRange,t):void 0;return{...e,newTableRange:r,zone:n}}function lK(e,t){return e.config?.styleId===t.tableStyleId?{...e,config:{...e.config,styleId:SA.styleId}}:e}function uK(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n;if(t.type===`REMOVE_COLUMNS_ROWS`?n=hl(t.elements,[e.base])[0]:t.type===`ADD_COLUMNS_ROWS`&&(n=ml(gt(t.position,t.base),t.quantity,[e.base])[0]),n!==void 0)return{...e,base:n}}function dK(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n=S(e.start,e.end+1),r=[];if(t.type===`REMOVE_COLUMNS_ROWS`?r=hl(t.elements,n):t.type===`ADD_COLUMNS_ROWS`&&(r=ml(gt(t.position,t.base),t.quantity,n)),r.length!==0)return{...e,start:Math.min(...r),end:Math.max(...r)}}function fK(e,t){let n=e.content&&Wu(e.sheetId,e.content,t);return{...e,content:n}}ZG.add(`UPDATE_CELL`,fK);function pK(e,t){let n=e.cf.rule;if(e={...e,cf:{...e.cf}},n.type===`CellIsRule`)e.cf.rule={...n,values:n.values.map(n=>Wu(e.sheetId,n,t))};else if(n.type===`ColorScaleRule`){let{minimum:r,maximum:i,midpoint:a}=n;e.cf.rule={...n,minimum:{...r,value:r.value&&Wu(e.sheetId,r.value,t)},maximum:{...i,value:i.value&&Wu(e.sheetId,i.value,t)},midpoint:a?{...a,value:Wu(e.sheetId,a.value,t)}:void 0}}else if(n.type===`IconSetRule`){let{upperInflectionPoint:r,lowerInflectionPoint:i}=n;e.cf.rule={...n,upperInflectionPoint:{...r,value:Wu(e.sheetId,r.value,t)},lowerInflectionPoint:{...i,value:Wu(e.sheetId,i.value,t)}}}else n.type===`DataBarRule`&&(e.cf.rule={...n,rangeValues:n.rangeValues?Gu(e.sheetId,n.rangeValues,t).range:void 0});return e}ZG.add(`ADD_CONDITIONAL_FORMAT`,pK);function mK(e,t){return e={...e,rule:{...e.rule,criterion:{...e.rule.criterion}}},e.rule.criterion.values=e.rule.criterion.values.map(n=>Wu(e.sheetId,n,t)),e}ZG.add(`ADD_DATA_VALIDATION_RULE`,mK);function hK(e,t){return e=b(e),e.pivot.measures.map(e=>{e.computedBy&&(e.computedBy.formula=Wu(e.computedBy.sheetId,e.computedBy.formula,t))}),e}ZG.add(`ADD_PIVOT`,hK),ZG.add(`UPDATE_PIVOT`,hK),ZG.add(`CREATE_CHART`,gK),ZG.add(`UPDATE_CHART`,gK);function gK(e,t){return{...e,definition:__(e.sheetId,e.definition,t)}}let _K=[{match:Os,fn:SK},{match:As,fn:CK},{match:Ns,fn:wK},{match:Ms,fn:DK},{match:ks,fn:EK},{match:js,fn:TK}];function vK(e,t){let n=XG.getTransformation(e.type,t.type),r=n?n(e,t):xK(e,t);return r&&yK(r,t)}function yK(e,t){let n=ZG.get(e.type);if(!n)return e;let r=nl(t);return r?n(e,r):e}function bK(e,t){let n=[...e],r=new Set(XG.getKeys());for(let e of t)(r.has(e.type)||rl.contains(e.type))&&(n=n.reduce((t,n)=>{let r=vK(n,e);return r&&t.push(r),t},[]));return n}function xK(e,t){for(let{match:n,fn:r}of _K)if(n(e)){let n=r(e,t);if(n===`SKIP_TRANSFORMATION`)continue;if(n===`IGNORE_COMMAND`)return;e=n}return e}function SK(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 CK(e,t){let n=SK(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=[];for(let n of e.target){let e=Qn(n,t);e&&r.push(e)}return r.length?{...e,target:r}:`IGNORE_COMMAND`}function wK(e,t){let n=SK(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=Qn(e.zone,t);return r?{...e,zone:r}:`IGNORE_COMMAND`}function TK(e,t){if(!(`sheetId`in t))return e;let n=e.ranges.map(e=>$n(e,t)).filter(C);return n.length?{...e,ranges:n}:`IGNORE_COMMAND`}function EK(e,t){let n=SK(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=hl(t.elements,e.elements):t.type===`ADD_COLUMNS_ROWS`&&(r=ml(gt(t.position,t.base),t.quantity,e.elements)),r.length===0?`IGNORE_COMMAND`:{...e,elements:r}}function DK(e,t){let n=SK(e,t);return n===`SKIP_TRANSFORMATION`?t.type===`ADD_COLUMNS_ROWS`||t.type===`REMOVE_COLUMNS_ROWS`?OK(e,t):t.type===`ADD_MERGE`?kK(e,t):`SKIP_TRANSFORMATION`:n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e}function OK(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 kK(e,t){for(let n of t.target)if(!(e.col===n.left&&e.row===n.top)&&En(e.col,e.row,n))return`IGNORE_COMMAND`;return e}var AK=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}},jK=class extends Error{},MK=class extends er{revisions;transportService;serverRevisionId;clients={};clientId=`local`;debouncedMove;pendingMessages=[];awaitingClientPosition;waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;uuidGenerator=new Gl;lastLocalOperation;constructor(e,t,n=Ee){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=n,this.debouncedMove=dt(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,n){if(!t.length||!n.length||!this.canApplyOptimisticUpdate())return;let r=new AK(this.uuidGenerator.uuidv4(),this.clientId,t,e,n,Date.now());this.revisions.append(r.id,r),e.type!==`REQUEST_REDO`&&(this.lastLocalOperation=r),this.trigger(`new-local-state-update`,{id:r.id}),this.sendUpdateMessage({type:`REMOTE_REVISION`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:r.id,clientId:r.clientId,commands:r.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_UNDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_REDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}move(e){this.debouncedMove(e)}join(e){e?(this.clients[e.id]=e,this.clientId=e.id):(this.clients.local={id:`local`,name:`local`},this.clientId=`local`),this.transportService.onNewMessage(this.clientId,this.onMessageReceived.bind(this)),this.awaitingClientPosition&&=(this._move(this.awaitingClientPosition),void 0)}loadInitialMessages(e){let t=performance.now(),n=e.reduce((e,t)=>e+(t.type===`REMOTE_REVISION`?t.commands.length:1),0);this.isReplayingInitialRevisions=!0;for(let t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1,console.debug(`Replayed`,n,`commands in`,performance.now()-t,`ms`)}async leave(e){e&&Object.keys(this.clients).length===1&&this.lastRevisionMessage&&this.lastRevisionMessage?.type!==`SNAPSHOT_CREATED`&&await this.snapshot(e()),delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.sendToTransport({type:`CLIENT_LEFT`,clientId:this.clientId,version:1})}async snapshot(e){if(this.pendingMessages.length!==0)return;let t=this.uuidGenerator.uuidv4();await this.sendToTransport({type:`SNAPSHOT`,nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getCurrentClient(){return this.getClient(this.clientId)}getClient(e){let t=this.clients[e];if(!t)throw new jK(`The client left the session`);return t}getConnectedClients(){return new Set(Object.values(this.clients).filter(C))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return this.pendingMessages.length===0}getLastLocalNonEmptyRevision(){return this.lastLocalOperation}_move(e){if(!this.clients[this.clientId]){this.awaitingClientPosition=e;return}let t=this.clients[this.clientId]?.position;if(t?.col===e.col&&t.row===e.row&&t.sheetId===e.sheetId)return;let n=t?`CLIENT_MOVED`:`CLIENT_JOINED`,r=this.getCurrentClient();this.clients[this.clientId]={...r,position:e},this.sendToTransport({type:n,version:1,client:{...r,position:e}}).then(()=>{this.pendingMessages.length>0&&!this.waitingAck&&this.sendPendingMessage()})}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 AK(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:bK(n,t)})}break;case`SNAPSHOT_CREATED`:{let t=new AK(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.sendToTransport({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()}async sendToTransport(e){return this.transportService.sendMessage(e)}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.
|
|
119
|
-
${JSON.stringify(e)}`);this.waitingAck=!0,this.sendToTransport({...e,serverRevisionId:this.serverRevisionId}).catch(e=>{if(!(e instanceof jK))throw e.cause||e;this.waitingAck=!1})}}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`)}},NK=class extends cb{static getters=[`getClientsToDisplay`,`getClient`,`getCurrentClient`,`getConnectedClients`,`isFullySynchronized`];static layers=[`Selection`];colors=new ni(12);session;constructor(e){super(e),this.session=e.session}isPositionValid(e){return e.row<this.getters.getNumberRows(e.sheetId)&&e.col<this.getters.getNumberCols(e.sheetId)}getClient(e){return this.session.getClient(e)}getCurrentClient(){return this.session.getCurrentClient()}getConnectedClients(){return[...this.session.getConnectedClients()].map(e=>({...e,color:this.colors.get(e.id)}))}isFullySynchronized(){return this.session.isFullySynchronized()}getClientsToDisplay(){try{this.getters.getCurrentClient()}catch(e){if(e instanceof jK)return[];throw e}let e=this.getters.getActiveSheetId(),t=[];for(let n of this.getters.getConnectedClients())n.id!==this.getters.getCurrentClient().id&&n.position&&n.position.sheetId===e&&this.isPositionValid(n.position)&&t.push({...n,position:n.position});return t}drawLayer(e){if(this.getters.isDashboard())return;let{ctx:t,thinLineWidth:n}=e,r=this.getters.getActiveSheetId();for(let e of this.getClientsToDisplay()){let{row:i,col:a}=e.position,o=this.getters.expandZone(r,{top:i,bottom:i,left:a,right:a}),{x:s,y:c,width:l,height:u}=this.getters.getVisibleRect(o);if(l<=0||u<=0)continue;let d=e.color;t.fillStyle=`${d}10`,t.lineWidth=4*n,t.strokeStyle=d,t.globalCompositeOperation=`multiply`,t.fillRect(s,c,l,u),t.globalCompositeOperation=`source-over`,t.strokeRect(s,c,l,u),t.font=`bold ${Ce+1}px ${we}`}}},PK=class extends cb{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 Qc(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=(xa(r)?r[0][0]:r)?.toString()}else n=t.content;(!n||!$e(n))&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}else n.type!==`boolean`&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}}}}},FK=class extends cb{static getters=[`dynamicTranslate`];dynamicTranslate(e){return e}},IK=class extends cb{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 Qt(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=Qt(r.map(E));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:Qt(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 Qt(t))for(let t of jn(i)){let i=this.getCellNumberFormat({sheetId:e,...t});if(i!==void 0){let e=ys(i,n);r[e]=r[e]||[],r[e].push(t)}}for(let t in r){let n=Qt(r[t].map(e=>E(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&&ns(e.format)))return e.format||os(e.value)}}},LK=class extends cb{static getters=[`getGeoJsonFeatures`,`geoFeatureNameToId`,`getGeoChartAvailableRegions`];geoJsonService;geoJsonCache={};constructor(e){super(e),this.geoJsonService=e.external.geoJsonService}getGeoChartAvailableRegions(){return this.geoJsonService?this.geoJsonService.getAvailableRegions()||[]:(console.error(`No geoJsonService provided to the model`),[])}getGeoJsonFeatures(e){if(!this.geoJsonService){console.error(`No geoJsonService provided to the model`);return}let t=this.geoJsonCache[e];if(!(t instanceof Promise)){if(t!==void 0)return t??void 0;this.geoJsonCache[e]=new Promise(async t=>{let n=await this.geoJsonService?.getTopoJson(e);this.geoJsonCache[e]=this.convertToGeoJson(n),this.dispatch(`EVALUATE_CHARTS`),t()})}}geoFeatureNameToId(e,t){if(!this.geoJsonService){console.error(`No geoJsonService provided to the model`);return}return this.geoJsonService.geoFeatureNameToId(e,t)}convertToGeoJson(e){if(!e)return null;if(e.type===`Topology`){let t=globalThis.ChartGeo.topojson.feature(e,Object.values(e.objects)[0]);return t.type===`FeatureCollection`?t.features:[t]}else if(e.type===`FeatureCollection`)return e.features;throw Error(`Invalid TopoJSON`)}},RK=class extends cb{static getters=[`getNextVisibleCellPosition`,`findVisibleHeader`,`findLastVisibleColRowIndex`,`findFirstVisibleColRowIndex`,`isRowHidden`,`isColHidden`,`isHeaderHidden`];isRowHidden(e,t){return this.getters.isRowHiddenByUser(e,t)||this.getters.isRowFiltered(e,t)}isColHidden(e,t){return this.getters.isColHiddenByUser(e,t)}isHeaderHidden(e,t,n){return t===`COL`?this.isColHidden(e,n):this.isRowHidden(e,n)}getNextVisibleCellPosition({sheetId:e,col:t,row:n}){return{sheetId:e,col:this.findVisibleHeader(e,`COL`,t,this.getters.getNumberCols(e)-1),row:this.findVisibleHeader(e,`ROW`,n,this.getters.getNumberRows(e)-1)}}findVisibleHeader(e,t,n,r){if(n<=r){for(let i=n;i<=r;i++)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}if(n>r){for(let i=n;i>=r;i--)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}}findLastVisibleColRowIndex(e,t,{last:n,first:r}){return S(n,r,-1).find(n=>!this.isHeaderHidden(e,t,n))||r}findFirstVisibleColRowIndex(e,t){let n=this.getters.getNumberHeaders(e,t);for(let r=0;r<n;r++)if(t===`COL`&&!this.isColHidden(e,r)||t===`ROW`&&!this.isRowHidden(e,r))return r}exportForExcel(e){for(let t of e.sheets)for(let[e,n]of Object.entries(t.rows))n.isHidden=this.isRowHidden(t.id,Number(e))}},zK=class extends cb{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){Vn(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:k(`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:k(`Pivot #%(formulaId)s`,{formulaId:i}),position:r}),this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:n,sheetIdTo:t});let a=this.getters.getPivot(e);this.insertPivotWithTable(t,0,0,e,a.getCollapsedTableStructure().export(),`dynamic`)}duplicatePivotInNewSheet(e,t,n){this.dispatch(`DUPLICATE_PIVOT`,{pivotId:e,newPivotId:t,duplicatedPivotName:k(`%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(k(`%(newPivotName)s (Pivot #%(formulaId)s)`,{newPivotName:o,formulaId:a})),position:i}).isSuccessful){this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:r,sheetIdTo:n});let i=this.getters.getPivot(e);this.insertPivotWithTable(n,0,0,t,i.getCollapsedTableStructure().export(),`dynamic`)}}getPivotDuplicateSheetName(e){let t=this.getters.getSheetIds().map(e=>this.getters.getSheetName(e));return zt(Xe(e),t)}insertPivotWithTable(e,t,n,r,i,a){let{cols:o,rows:s,measures:c,fieldsType:l}=i,u=new zL(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:{...Le,numberOfHeaders:d}})}resizeSheet(e,t,n,r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:s-l,position:`after`})}splitPivotFormula(e,t,n,r){let i=this.getters.getSpreadZone({sheetId:e,col:t,row:n});if(!i)return;let a=this.getters.getPivotFormulaId(r),o=new Map;for(let t=i.left;t<=i.right;t++)for(let n=i.top;n<=i.bottom;n++){let r={sheetId:e,col:t,row:n};o.set(r,this.getters.getPivotCellFromPosition(r))}for(let[e,t]of o)this.dispatch(`UPDATE_CELL`,{...e,content:gh(a,t)});if(this.getters.getCoreTable({sheetId:e,col:t,row:n})?.type===`dynamic`){let r=E({col:t,row:n}),a=this.getters.getRangeDataFromZone(e,i);this.dispatch(`UPDATE_TABLE`,{sheetId:e,zone:r,newTableRange:a,tableType:`static`})}}};let BK=new B,VK=new B;function HK(e,t){if(t&&BK.contains(t.type))return BK.get(t.type)(e,t)}function UK(e,t,n){if(VK.contains(t.type))return VK.get(t.type)(e,t,n)}function WK(e){return!e||!e.rootCommand||typeof e.rootCommand!=`object`?!1:Hs(e.rootCommand)?BK.contains(e.rootCommand.type):VK.contains(e.rootCommand.type)}function GK(e,t){if(!(!e.rootCommand||typeof e.rootCommand!=`object`))return Hs(e.rootCommand)?HK(t,e.rootCommand):UK(t,e.rootCommand,e.commands)}var KK=class extends cb{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=GK(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:WK(this.getPossibleRevisionToRepeat())}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}getPossibleRevisionToRepeat(){return this.session.getLastLocalNonEmptyRevision()}},qK=class{trackedValues=new Set;domainToArray(e){return e.flatMap(e=>[e.field,P(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)}},JK=class extends cb{static getters=[`getPivotPresenceTracker`];trackPresencePivotId;tracker;handle(e){switch(e.type){case`PIVOT_START_PRESENCE_TRACKING`:this.tracker=new qK,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}}},YK=class extends cb{allowDispatch(e){switch(e.type){case`SORT_CELLS`:return En(e.col,e.row,e.zone)?this.checkValidations(e,this.checkMerge,this.checkMergeSizes,this.checkArrayFormulaInSortZone):`InvalidSortAnchor`}return`Success`}handle(e){switch(e.type){case`SORT_CELLS`:this.sortZone(e.sheetId,e,e.zone,e.sortDirection,e.sortOptions||{});break}}checkMerge({sheetId:e,zone:t}){return this.getters.doesIntersectMerge(e,t)&&jn(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=>wn(e,t)),r=On(n[0]),[i,a]=[r.numberOfCols,r.numberOfRows];return n.every(e=>{let[t,n]=[e.right-e.left+1,e.bottom-e.top+1];return t===i&&n===a})?`Success`:`InvalidSortZone`}checkArrayFormulaInSortZone({sheetId:e,zone:t}){return jn(t).some(({col:t,row:n})=>{let r=this.getters.getArrayFormulaSpreadingOn({sheetId:e,col:t,row:n});return r&&!w(r,{sheetId:e,col:t,row:n})})?`SortZoneWithArrayFormulas`:`Success`}hasHeader(e,t){if(t[0].length===1)return!1;let n=t.map(t=>t.map(({col:t,row:n})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).type));return n[0][0]===`empty`&&(n=n.slice(1)),n.some(e=>e[0]===`empty`)?!1:!!n.some(e=>e[1]!==`empty`&&e[0]!==e[1])}sortZone(e,t,n,r,i){let[a,o]=this.mainCellsSteps(e,n),s=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,c=Object.assign({},n),l=this.mainCells(e,n);!i.sortHeaders&&this.hasHeader(e,l)&&(c.top+=o),l=this.mainCells(e,c);let u=l[s-c.left],d=Hw(u.map(e=>this.getters.getEvaluatedCell(e)),r,!!i.emptyCellAsZero).map(e=>e.index),[f,p]=[l.length,l[0].length],m=[];for(let t=0;t<f;t++)for(let n=0;n<p;n++){let r=l[t][d[n]],i=this.getters.getCell(r),s=this.getters.getCellStyle(r),u=c.left+t*a,f=c.top+n*o,p={sheetId:r.sheetId,col:u,row:f,content:``};if(i){let t=i.content;if(i.isFormula){let n=this.getters.getCellPosition(i.id);t=this.getters.getTranslatedCellFormula(e,0,f-n.row,i.compiledFormula.tokens)}p.style=s,p.content=t,p.format=i.format}m.push(p)}m.forEach(e=>this.dispatch(`UPDATE_CELL`,e))}mainCellsSteps(e,t){let n=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[n?n.right-n.left+1:1,n?n.bottom-n.top+1:1]}mainCells(e,t){let[n,r]=this.mainCellsSteps(e,t),i=[],a=S(t.left,t.right+1,n),o=S(t.top,t.bottom+1,r);for(let t of a){let n=[];i.push(n);for(let r of o)n.push({sheetId:e,col:t,row:r})}return i}},XK=class extends cb{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[`
|
|
120
|
-
`,`;`,`,`,` `,`.`])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}),c=this.getters.getCellStyle({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:Wv(n,this.getters.getLocale()),format:``,style:{...NW,...c}})}}getSplittedCols(e,t){if(!t)throw Error(`Separator cannot be empty`);let n=this.getters.getActiveSheetId(),r=[];for(let i of S(e.top,e.bottom+1)){let a=this.getters.getEvaluatedCell({sheetId:n,col:e.left,row:i}).formattedValue;r.push(this.splitAndRemoveTrailingEmpty(a,t))}return r}splitAndRemoveTrailingEmpty(e,t){let n=e.split(t);for(;n.length>1&&n[n.length-1]===``;)n.pop();return n}willSplittedColsOverwriteContent(e,t){let n=this.getters.getActiveSheetId();for(let r of S(e.top,e.bottom+1)){let i=t[r-e.top];for(let t=1;t<i.length;t++){let i=this.getters.getCell({sheetId:n,col:e.left+t,row:r});if(i&&i.content)return!0}}return!1}removeMergesInSplitZone(e,t){let n=this.getters.getActiveSheetId(),r=Math.max(...t.map(e=>e.length)),i={...e,right:e.left+r-1},a=this.getters.getMergesInZone(n,i);this.dispatch(`REMOVE_MERGE`,{sheetId:n,target:a})}addColsToAvoidCollisions(e,t){let n=this.getters.getActiveSheetId(),r=0;for(let i of S(e.top,e.bottom+1)){let a={sheetId:n,col:e.left,row:i},o=t[i-e.top],s=this.getColsToAddToAvoidCollision(a,o);r=Math.max(r,s)}r&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:e.left,sheetId:n,sheetName:this.getters.getSheetName(n),quantity:r,position:`after`})}getColsToAddToAvoidCollision(e,t){let n=t.length;for(let t=1;t<n;t++){let r=e.col+t,i=this.getters.getCell({...e,col:r});if(i&&i.content)return n-t}return 0}addColumnsToNotOverflowSheet(e,t){let n=this.getters.getActiveSheetId(),r=Math.max(...t.map(e=>e.length-1)),i=this.getters.getNumberCols(n)-1;e.left+r>i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:i,sheetId:n,sheetName:this.getters.getSheetName(n),quantity:e.left+r-i,position:`after`})}checkSingleColSelected(){return this.getters.isSingleColSelected()?`Success`:`MoreThanOneColumnSelected`}checkNonEmptySelector(e){return e.separator===``?`EmptySplitSeparator`:`Success`}checkNotOverwritingContent(e){if(e.addNewColumns||e.force)return`Success`;let t=this.getters.getSelectedZones()[0],n=this.getSplittedCols(t,e.separator);return this.willSplittedColsOverwriteContent(t,n)?`SplitWillOverwriteContent`:`Success`}checkSeparatorInSelection({separator:e}){let t=this.getters.getSelectedCells();for(let n of t)if(n.formattedValue.includes(e))return`Success`;return`NoSplitSeparatorInSelection`}},ZK=class extends cb{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=QF(t.range.zone,t.config);if(a&&En(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)}},QK=class extends cb{allowDispatch(e){switch(e.type){case`RESIZE_TABLE`:let t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return`TableNotFound`;let n=t.range.zone,r=this.getters.getRangeFromRangeData(e.newTableRange).zone;return r.top!==n.top||r.left!==n.left?`InvalidTableResize`:this.canDispatch(`UPDATE_TABLE`,{...e}).reasons}return`Success`}handle(e){switch(e.type){case`RESIZE_TABLE`:{let t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(this.dispatch(`UPDATE_TABLE`,{...e}),!t)return;let n=this.getters.getRangeFromRangeData(e.newTableRange).zone;if(this.selection.selectCell(n.right,n.bottom),!t.config.automaticAutofill)return;let r=t.range.zone;if(n.bottom>=r.bottom){for(let t=n.left;t<=n.right;t++){let i={col:t,row:r.bottom,sheetId:e.sheetId};this.getters.getCell(i)?.content.startsWith(`=`)&&this.dispatch(`AUTOFILL_TABLE_COLUMN`,{...i,autofillRowStart:r.bottom,autofillRowEnd:n.bottom})}break}}}}},$K=class extends cb{static getters=[`shouldShowFormulas`];showFormulas=!1;handle(e){switch(e.type){case`SET_FORMULA_VISIBILITY`:this.showFormulas=e.show;break}}shouldShowFormulas(){return this.showFormulas}},eq=class extends cb{static getters=[`getCellWidth`,`getTextWidth`,`getCellText`,`getCellMultiLineText`,`getMultilineTextSize`,`getContiguousZone`,`computeTextYCoordinate`];ctx=Sl();allowDispatch(e){return this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e)}handle(e){switch(e.type){case`AUTORESIZE_COLUMNS`:for(let t of e.cols){let n=this.getColMaxWidth(e.sheetId,t);n!==0&&this.dispatch(`RESIZE_COLUMNS_ROWS`,{elements:[t],dimension:`COL`,size:n,sheetId:e.sheetId})}break;case`AUTORESIZE_ROWS`:this.autoResizeRows(e.sheetId,e.rows);break;case`DELETE_UNFILTERED_CONTENT`:let t=[];for(let n of e.target){let r=Ze(S(n.top,n.bottom+1).filter(t=>!this.getters.isRowFiltered(e.sheetId,t)));for(let e of r)t.push({...n,top:e[0],bottom:e[e.length-1]})}this.dispatch(`DELETE_CONTENT`,{sheetId:e.sheetId,target:t});break}}getCellWidth(e){let t=this.getters.getCellComputedStyle(e),n=0,r=this.getters.getEvaluatedCell(e).formattedValue;if(r){let e=Il(this.ctx,r,t,void 0);n+=El(this.ctx,e,t).width}for(let t of this.getters.getCellIcons(e))n+=t.margin+t.size;if(this.getters.getDataValidationChipStyle(e)&&(n+=10),n===0)return 0;if(n+=8,t.wrapping===`wrap`){let t=this.getters.getColSize(this.getters.getActiveSheetId(),e.col);return Math.min(t,n)}return n}getTextWidth(e,t){return Dl(this.ctx,e,t)}getMultilineTextSize(e,t){return El(this.ctx,e,t)}getCellText(e,t){let n=this.getters.getCell(e),r=this.getters.getLocale();if(t?.showFormula&&n?.isFormula)return Yv(n.content,r);if(t?.showFormula&&!n?.content)return``;{let n=this.getters.getCellStyle(e),i=this.getters.getEvaluatedCell(e),a=t?.availableWidth?{availableWidth:t.availableWidth,measureText:e=>Dl(this.ctx,e,n||{})}:void 0;return z(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 Il(this.ctx,r,n,t.wrapText?t.maxWidth:void 0)}computeTextYCoordinate(e,t,n=xe,r=1){let i=e.y+1,a=xl(t,r);if(e.height>a+8){if(n===`middle`)return Math.ceil(i+(e.height-a)/2);if(n===`bottom`)return i+e.height-a-4}return i+4}getContiguousZone(e,t){let n=t=>{for(let n of S(t.left,t.right+1)){if(!this.isCellEmpty({sheetId:e,col:n,row:t.top-1}))return{...t,top:t.top-1};if(!this.isCellEmpty({sheetId:e,col:n,row:t.bottom+1}))return{...t,bottom:t.bottom+1}}for(let n of S(t.top,t.bottom+1)){if(!this.isCellEmpty({sheetId:e,col:t.left-1,row:n}))return{...t,left:t.left-1};if(!this.isCellEmpty({sheetId:e,col:t.right+1,row:n}))return{...t,right:t.right+1}}return t},r=!1,i=t;do{r=!1;let e=n(i);Cn(i,e)||(r=!0,i=e)}while(r);return i}isCellEmpty(e){let t=this.getters.getMainCellPosition(e);return this.getters.getEvaluatedCell(t).type===`empty`}getColMaxWidth(e,t){let n=jn(this.getters.getColsZone(e,t,t)).map(t=>this.getCellWidth({sheetId:e,...t}));return Math.max(0,Pt(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,i;for(let[n,a]of this.getters.getEvaluatedCellsPositionInZone(e,this.getters.getRowsZone(e,r,r))){if(a.value===void 0)continue;let r=this.getters.getColSize(e,n.col),o=this.getters.getCellStyle(n),s=a.formattedValue,c=wl(this.ctx,s,o,r);c>t&&c>23&&(t=c,i=n)}let a=i&&this.getters.getCell(i);a&&!a.isFormula&&(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})}},tq=class extends cb{static getters=[`getSelectedCarouselItem`,`getChartFromFigureId`,`getChartIdFromFigureId`];uuidGenerator=new Gl;carouselStates={};allowDispatch(e){switch(e.type){case`ADD_FIGURE_CHART_TO_CAROUSEL`:return!this.getters.doesCarouselExist(e.carouselFigureId)||this.getters.getFigure(e.sheetId,e.chartFigureId)?.tag!==`chart`?`InvalidFigureId`:`Success`;case`DUPLICATE_CAROUSEL_CHART`:return!this.getters.doesCarouselExist(e.carouselId)||!this.getters.getCarousel(e.carouselId).items.some(t=>t.type===`chart`&&t.chartId===e.chartId)||this.getters.getChart(e.duplicatedChartId)?`InvalidFigureId`:`Success`;case`ADD_NEW_CHART_TO_CAROUSEL`:return this.getters.doesCarouselExist(e.figureId)?`Success`:`InvalidFigureId`;case`UPDATE_CAROUSEL_ACTIVE_ITEM`:return this.getters.doesCarouselExist(e.figureId)?this.getters.getCarousel(e.figureId).items.some(t=>w(t,e.item))?`Success`:`InvalidCarouselItem`:`InvalidFigureId`}return`Success`}handle(e){switch(e.type){case`ADD_NEW_CHART_TO_CAROUSEL`:this.addNewChartToCarousel(e.figureId,e.sheetId);break;case`ADD_FIGURE_CHART_TO_CAROUSEL`:this.addFigureChartToCarousel(e.carouselFigureId,e.chartFigureId,e.sheetId);break;case`DUPLICATE_CAROUSEL_CHART`:this.duplicateCarouselChart(e);break;case`UPDATE_CAROUSEL_ACTIVE_ITEM`:this.carouselStates[e.figureId]=this.getCarouselItemId(e.item);break;case`POPOUT_CHART_FROM_CAROUSEL`:this.popOutChartFromCarousel(e.carouselId,e.chartId,e.sheetId);break;case`DELETE_FIGURE`:delete this.carouselStates[e.figureId];break;case`UPDATE_CAROUSEL`:this.fixWrongCarouselState(e.figureId);break;case`DELETE_CHART`:case`UNDO`:case`REDO`:case`DELETE_SHEET`:for(let e in this.carouselStates)this.fixWrongCarouselState(e);break}}popOutChartFromCarousel(e,t,n){let r=this.getters.getCarousel(e);if(!r)return;let i=this.getters.getFigure(n,e),a=this.getters.getChartDefinition(t);if(!a||!i)return;let o=this.getters.getFigureUI(n,i),s=this.getters.getPositionAnchorOffset({x:o.x+50,y:o.y+50}),c=this.uuidGenerator.smallUuid();this.dispatch(`CREATE_CHART`,{...s,chartId:this.uuidGenerator.smallUuid(),figureId:c,sheetId:n,size:{width:i.width,height:i.height},definition:{...a}});let l=r.items.filter(e=>e.type!==`chart`||e.chartId!==t);this.dispatch(`UPDATE_CAROUSEL`,{sheetId:n,figureId:e,definition:{...r,items:l}}),this.dispatch(`SELECT_FIGURE`,{figureId:c})}getSelectedCarouselItem(e){let t=this.getters.getCarousel(e);if(t.items.length)return this.carouselStates[e]?t.items.find(t=>this.getCarouselItemId(t)===this.carouselStates[e]):t.items[0]}getChartFromFigureId(e){if(!this.getters.getFigureSheetId(e))return;let t=this.getChartIdFromFigureId(e);return t?this.getters.getChart(t):void 0}getChartIdFromFigureId(e){let t=this.getters.getFigureSheetId(e);if(!t)return;let n=this.getters.getFigure(t,e);if(!(!n||n.tag!==`chart`&&n.tag!==`carousel`)){if(n.tag===`carousel`){let t=this.getSelectedCarouselItem(e);return t?.type===`chart`?t.chartId:void 0}return this.getters.getChartIds(t).find(t=>this.getters.getFigureIdFromChartId(t)===e)}}fixWrongCarouselState(e){if(!this.getters.doesCarouselExist(e)){delete this.carouselStates[e];return}let t=this.getters.getCarousel(e);t.items.length===0?delete this.carouselStates[e]:this.carouselStates[e]&&t.items.some(t=>this.getCarouselItemId(t)===this.carouselStates[e])||(this.carouselStates[e]=this.getCarouselItemId(t.items[0]))}addNewChartToCarousel(e,t){let n=this.getters.getCarousel(e),r=this.uuidGenerator.smallUuid();this.dispatch(`CREATE_CHART`,{chartId:r,figureId:e,sheetId:t,definition:q_});let i={...n,items:[...n.items,{type:`chart`,chartId:r}]};this.dispatch(`UPDATE_CAROUSEL`,{sheetId:t,figureId:e,definition:i})}addFigureChartToCarousel(e,t,n){let r=this.getChartIdFromFigureId(t);if(!r)return;let i=this.getters.getCarousel(e),a={...i,items:[...i.items,{type:`chart`,chartId:r}]};this.dispatch(`UPDATE_CAROUSEL`,{sheetId:n,figureId:e,definition:a}),this.dispatch(`UPDATE_CHART`,{sheetId:n,chartId:r,figureId:e,definition:this.getters.getChartDefinition(r)}),this.dispatch(`DELETE_FIGURE`,{sheetId:n,figureId:t})}duplicateCarouselChart({carouselId:e,chartId:t,sheetId:n,duplicatedChartId:r}){let i=this.getters.getChart(t);if(!i)return;let a=this.getters.getCarousel(e),o=a.items.findIndex(e=>e.type===`chart`&&e.chartId===t);if(o===-1)return;this.dispatch(`CREATE_CHART`,{chartId:r,figureId:e,sheetId:n,definition:i.getDefinition()});let s=kt(a.items,[{type:`chart`,chartId:r}],o+1);this.dispatch(`UPDATE_CAROUSEL`,{sheetId:n,figureId:e,definition:{...a,items:s}})}getCarouselItemId(e){return e.type===`chart`?e.chartId:`carouselDataView`}};async function nq(e){return new Promise((t,n)=>{let r=new Image;r.addEventListener(`load`,()=>{let e=document.createElement(`canvas`);e.width=r.width,e.height=r.height,e.getContext(`2d`)?.drawImage(r,0,0),e.toBlob(t,`image/png`)}),r.addEventListener(`error`,n),r.src=e})}var rq=class extends cb{static layers=[`Clipboard`];static getters=[`getClipboardTextAndImageContent`,`getClipboardId`,`getClipboardTextContent`,`isCutOperation`];status=`invisible`;originSheetId;copiedData;_isCutOperation=!1;clipboardId=new Gl().uuidv4();fileStore;uuidGenerator;constructor(e){super(e),this.fileStore=e.external.fileStore,this.uuidGenerator=new Gl}allowDispatch(e){switch(e.type){case`CUT`:let t=this.getters.getSelectedZones();return this.isCutAllowedOn(t);case`PASTE_FROM_OS_CLIPBOARD`:{let t=this.convertTextToClipboardData(e.clipboardContent.text??``),n=e.pasteOption;return this.isPasteAllowed(e.target,t,{pasteOption:n,isCutOperation:!1})}case`PASTE`:{if(!this.copiedData)return`EmptyClipboard`;let t=e.pasteOption;return this.isPasteAllowed(e.target,this.copiedData,{pasteOption:t,isCutOperation:this._isCutOperation})}case`COPY_PASTE_CELLS_ABOVE`:{let e=this.getters.getSelectedZones();if(e.length>1||e[0].top===0&&e[0].bottom===0)return`InvalidCopyPasteSelection`;break}case`COPY_PASTE_CELLS_ON_LEFT`:{let e=this.getters.getSelectedZones();if(e.length>1||e[0].left===0&&e[0].right===0)return`InvalidCopyPasteSelection`;break}case`INSERT_CELL`:{let{cut:t,paste:n}=this.getInsertCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);return this.isPasteAllowed(n,r,{isCutOperation:!0})}case`DELETE_CELL`:{let{cut:t,paste:n}=this.getDeleteCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);return this.isPasteAllowed(n,r,{isCutOperation:!0})}}return`Success`}handle(e){switch(e.type){case`COPY`:case`CUT`:let t=this.getters.getSelectedZones();this.status=`visible`,this.originSheetId=this.getters.getActiveSheetId(),this._isCutOperation=e.type===`CUT`,this.copiedData=this.copy(t);break;case`PASTE_FROM_OS_CLIPBOARD`:{this._isCutOperation=!1;let t=e.clipboardContent;if(t.data?.version!==iP()&&(t={...t},delete t.data),t.imageData){let n=this.getters.getActiveSheetId(),r=this.uuidGenerator.uuidv4(),i=t.imageData,a=L_(this.getters,i.size);this.dispatch(`CREATE_IMAGE`,{definition:i,size:a,col:e.target[0].left,row:e.target[0].top,offset:{x:0,y:0},sheetId:n,figureId:r})}t.data?this.copiedData=t.data:this.copiedData=this.convertTextToClipboardData(t.text??``);let n=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:n,selectTarget:!0,isCutOperation:!1}),this.status=`invisible`,this.copiedData=void 0;break}case`PASTE`:{let t=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:t,selectTarget:!0,isCutOperation:this._isCutOperation}),this.status=`invisible`,this._isCutOperation&&=(this.copiedData=void 0,!1);break}case`COPY_PASTE_CELLS_ABOVE`:{let e=this.getters.getSelectedZone(),t=e.top!==e.bottom,n={...e,bottom:t?e.top:e.top-1,top:t?e.top:e.top-1};this.originSheetId=this.getters.getActiveSheetId();let r=this.copy([n]);this.paste([e],r,{isCutOperation:!1,selectTarget:!0})}break;case`COPY_PASTE_CELLS_ON_LEFT`:{let e=this.getters.getSelectedZone(),t=e.left!==e.right,n={...e,right:t?e.left:e.left-1,left:t?e.left:e.left-1};this.originSheetId=this.getters.getActiveSheetId();let r=this.copy([n]);this.paste([e],r,{isCutOperation:!1,selectTarget:!0})}break;case`CLEAN_CLIPBOARD_HIGHLIGHT`:this.status=`invisible`;break;case`DELETE_CELL`:{let{cut:t,paste:n}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!pn(t[0])){this.dispatch(`CLEAR_CELLS`,{target:[e.zone],sheetId:this.getters.getActiveSheetId()});break}let r=this.copy(t,`shiftCells`);this.paste(n,r,{isCutOperation:!0});break}case`INSERT_CELL`:{let{cut:t,paste:n}=this.getInsertCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);this.paste(n,r,{isCutOperation:!0});break}case`ADD_COLUMNS_ROWS`:if(this.status=`invisible`,!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;this.isColRowDirtyingClipboard(e.position===`before`?e.base:e.base+1,e.dimension)&&(this.copiedData=void 0);break;case`REMOVE_COLUMNS_ROWS`:if(this.status=`invisible`,!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;for(let t of e.elements)if(this.isColRowDirtyingClipboard(t,e.dimension)){this.copiedData=void 0;break}this.status=`invisible`;break;case`REPEAT_PASTE`:this.paste(e.target,this.copiedData,{isCutOperation:!1,pasteOption:e.pasteOption,selectTarget:!0});break;case`DELETE_SHEET`:if(!this._isCutOperation)return;this.originSheetId===e.sheetId&&(this.copiedData=void 0,this.status=`invisible`);break;default:Hs(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?BB.figureHandlers:BB.cellHandlers;return t.getKeys().map(e=>({handlerName:e,handler:new(t.get(e))(this.getters,this.dispatch)}))}isCutAllowedOn(e){let t=this.getClipboardData(e);for(let{handler:e}of this.selectClipboardHandlers(t)){let n=e.isCutAllowed(t);if(n!==`Success`)return n}return`Success`}isPasteAllowed(e,t,n){for(let{handler:r}of this.selectClipboardHandlers(t)){let i=r.isPasteAllowed(this.getters.getActiveSheetId(),e,t,{...n});if(i!==`Success`)return i}return`Success`}isColRowDirtyingClipboard(e,t){if(!this.copiedData||!this.copiedData.zones)return!1;let{zones:n}=this.copiedData;for(let r of n)if(t===`COL`&&e<=r.right||t===`ROW`&&e<=r.bottom)return!0;return!1}copy(e,t=`copyPaste`){let n={},r=this.getClipboardData(e);for(let{handlerName:e,handler:i}of this.selectClipboardHandlers(r)){let a=i.copy(r,this._isCutOperation,t);n[e]=a;for(let e of[`sheetId`,`cells`,`zones`,`figureId`])a&&e in a&&(n[e]=a[e])}return n}paste(e,t,n){if(!t)return;let r=this.getters.getActiveSheetId(),i=this.selectClipboardHandlers(t),{target:a,zone:o,selectedZones:s}=sA(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),oA(i,t,a,n),n?.selectTarget&&cA(this.selection,e,s)}addMissingDimensions(e,t,n,r,i){let a=n+i-this.getters.getNumberRows(e);a>0&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:this.getters.getNumberRows(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:a,position:`after`});let o=t+r-this.getters.getNumberCols(e);o>0&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:this.getters.getNumberCols(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:o,position:`after`})}getClipboardTextContent(){return this.getPlainTextContent()}getClipboardId(){return this.clipboardId}async getClipboardTextAndImageContent(){let e=await this.getImageContent(),t=e?.type,n={"text/plain":this.getPlainTextContent(),"text/html":await this.getHTMLContent()};return t&&e&&(n[t]=e),n}getSheetData(){let e={version:iP(),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(`
|
|
115
|
+
`,e.endsWith(`{`)&&n++;return t.trim()}let aU=yO.content,oU={"=":`EQ`,"+":`ADD`,"-":`MINUS`,"*":`MULTIPLY`,"/":`DIVIDE`,">=":`GTE`,"<>":`NE`,">":`GT`,"<=":`LTE`,"<":`LT`,"^":`POWER`,"&":`CONCATENATE`},sU={"-":`UMINUS`,"+":`UPLUS`,"%":`UNARY.PERCENT`},cU={};function lU(e){return uU(Uu(e))}function uU(e){try{return dU(e)}catch(t){return{tokens:e,dependencies:[],execute:function(){return t},isBadExpression:!0,normalizedFormula:e.map(e=>e.value).join(``)}}}function dU(e){let{dependencies:t,literalValues:n,symbols:r}=pU(e),i=fU(e);if(!cU[i]){let t=qO([...e]),n=new nU,s=0,c=0,l=0;if(t.type===`BIN_OPERATION`&&t.value===`:`||t.type===`EMPTY`)throw new fa(k(`Invalid formula`));let u=o(t),d=new eU;d.append(u),d.append(`return ${u.returnExpression};`),cU[i]=Function(`deps`,`ref`,`range`,`getSymbolValue`,`ctx`,d.toString());function a(e){let{args:t}=e,n=aU[e.value.toUpperCase()];if(!n)throw new ga(k(`Unknown function: "%s"`,e.value));mU(e);let r=[],i=_y(n,t.length);for(let e=0;e<t.length;e++){let a=n.args[i(e).index??-1],s=t[e],c=a.type||[],l=c.includes(`META`)||c.includes(`RANGE<META>`),u=c.some(e=>hU(e));r.push(o(s,l,u))}return r}function o(e,t=!1,i=!1){let u=new eU(n);if(e.type!==`REFERENCE`&&!(e.type===`BIN_OPERATION`&&e.value===`:`)&&t)throw new fa(k(`Argument must be a reference to a cell or range.`));switch(e.debug&&(u.append(`debugger;`),u.append(`ctx["debug"] = true;`)),e.type){case`BOOLEAN`:return u.return(`{ value: ${e.value} }`);case`NUMBER`:return u.return(`this.literalValues.numbers[${c++}]`);case`STRING`:return u.return(`this.literalValues.strings[${s++}]`);case`REFERENCE`:return u.return(`${e.value.includes(`:`)||i?`range`:`ref`}(deps[${l++}], ${t?`true`:`false`})`);case`FUNCALL`:let n=a(e).map(e=>e.assignResultToVariable());u.append(...n);let d=e.value.toUpperCase();return u.return(`ctx['${d}'](${n.map(e=>e.returnExpression)})`);case`ARRAY`:return o({type:`FUNCALL`,value:`ARRAY.LITERAL`,args:e.value.map(e=>({type:`FUNCALL`,value:`ARRAY.ROW`,args:e,tokenStartIndex:0,tokenEndIndex:0})),tokenStartIndex:0,tokenEndIndex:0});case`UNARY_OPERATION`:{let t=sU[e.value],n=o(e.operand,!1,!1).assignResultToVariable();return u.append(n),u.return(`ctx['${t}'](${n.returnExpression})`)}case`BIN_OPERATION`:{let t=oU[e.value],n=o(e.left,!1,!1).assignResultToVariable(),r=o(e.right,!1,!1).assignResultToVariable();return u.append(n),u.append(r),u.return(`ctx['${t}'](${n.returnExpression}, ${r.returnExpression})`)}case`SYMBOL`:let f=r.indexOf(e.value);return u.return(`getSymbolValue(this.symbols[${f}])`);case`EMPTY`:return u.return(`undefined`)}}}return{execute:cU[i],dependencies:t,literalValues:n,symbols:r,tokens:e,isBadExpression:!1,normalizedFormula:i}}function fU(e){let t=``;for(let n of e)switch(n.type){case`STRING`:t+=`|S|`;break;case`NUMBER`:t+=`|N|`;break;case`REFERENCE`:case`INVALID_REFERENCE`:n.value.includes(`:`)?t+=`|R|`:t+=`|C|`;break;case`SPACE`:break;default:t+=n.value;break}return t}function pU(e){let t={numbers:[],strings:[]},n=[],r=[];for(let i of e)switch(i.type){case`INVALID_REFERENCE`:case`REFERENCE`:n.push(i.value);break;case`STRING`:let e=Je(i.value);t.strings.push({value:e});break;case`NUMBER`:{let e=ta(i.value,R);t.numbers.push({value:e});break}case`SYMBOL`:r.push(Je(i.value,`'`))}return{dependencies:n,literalValues:t,symbols:r}}function mU(e){let t=e.args.length,n=e.value.toUpperCase(),r=aU[n],{nbrArgRepeating:i,minArgRequired:a}=r;if(t<a)throw new fa(k(`Invalid number of arguments for the %(functionName)s function. Expected %(minArgRequired)s minimum, but got %(nbrArgSupplied)s instead.`,{functionName:n,minArgRequired:a,nbrArgSupplied:t}));if(t>r.maxArgPossible)throw new fa(k(`Invalid number of arguments for the %(functionName)s function. Expected %(maxArgPossible)s maximum, but got %(nbrArgSupplied)s instead.`,{functionName:n,maxArgPossible:r.maxArgPossible,nbrArgSupplied:t}));if(i>1){let e=i*Math.floor((t-a)/i),o=t-a-e-r.nbrOptionalNonRepeatingArgs;if(o>0)throw new fa(k(`Invalid number of arguments for the %(functionName)s function. Repeatable arguments should be supplied in groups of %(nbrArgRepeating)s, with up to %(nbrArgOptional)s optional. Got %(nbrValueRemaining)s too many.`,{functionName:n,nbrArgRepeating:i,nbrArgOptional:r.nbrOptionalNonRepeatingArgs,nbrValueRemaining:o}))}}function hU(e){return e.startsWith(`RANGE`)}function gU(e,t){return{sequence:0,autoSelectFirstProposal:!0,getProposals(n){let r=e.measures.filter(e=>e!==t).map(e=>{let t=Ye(e.id);return{text:t,description:e.displayName,htmlContent:[{value:t,color:ge}],fuzzySearchKey:e.displayName+t+e.fieldName}}),i=e.rows.concat(e.columns).map(e=>{let t=Ye(e.nameWithGranularity);return{text:t,description:e.displayName,htmlContent:[{value:t,color:ge}],fuzzySearchKey:e.displayName+t+e.fieldName}});return r.concat(i)},selectProposal(e,t){let n=e.end;e.type===`SYMBOL`&&(n=e.start);let r=e.end;this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t)}}}var _U=class extends t.Component{static template=`o-spreadsheet-PivotMeasureEditor`;static components={PivotDimension:ZH,StandaloneComposer:fk};static props={definition:Object,measure:Object,onMeasureUpdated:Function,onRemoved:Function,generateMeasureId:Function,aggregators:Object,pivotId:String};getMeasureAutocomplete(){return gU(this.props.definition,this.props.measure)}updateMeasureFormula(e){this.props.onMeasureUpdated({...this.props.measure,computedBy:{sheetId:this.env.model.getters.getActiveSheetId(),formula:e[0]===`=`?e:`=`+e}})}updateAggregator(e){this.props.onMeasureUpdated({...this.props.measure,aggregator:e,id:this.props.generateMeasureId(this.props.measure.fieldName,e)})}updateName(e,t){this.props.measure.computedBy&&t?this.props.onMeasureUpdated({...this.props.measure,userDefinedName:t,id:this.props.generateMeasureId(t,this.props.measure.aggregator),fieldName:t}):this.props.onMeasureUpdated({...this.props.measure,userDefinedName:t})}toggleMeasureVisibility(){this.props.onMeasureUpdated({...this.props.measure,isHidden:!this.props.measure.isHidden})}openShowValuesAs(){this.env.replaceSidePanel(`PivotMeasureDisplayPanel`,`pivot_key_${this.props.pivotId}`,{pivotId:this.props.pivotId,measure:this.props.measure})}getColoredSymbolToken(e){if(e.type!==`SYMBOL`)return;let t=Je(e.value,`'`);if(this.props.definition.columns.some(e=>e.nameWithGranularity===t)||this.props.definition.rows.some(e=>e.nameWithGranularity===t)||this.props.definition.measures.some(e=>e.id===t&&e.id!==this.props.measure.id))return ge}get isCalculatedMeasureInvalid(){return lU(this.props.measure.computedBy?.formula??``).isBadExpression}},vU=class extends t.Component{static template=`o-spreadsheet-PivotSortSection`;static components={Section:q};static props={definition:Object,pivotId:String};get hasValidSort(){let e=this.env.model.getters.getPivot(this.props.pivotId);return!!this.props.definition.sortedColumn&&Th(this.props.definition.sortedColumn,e)}get sortDescription(){return k(`Sorted on column (%(ascOrDesc)s):`,{ascOrDesc:this.props.definition.sortedColumn?.order===`asc`?k(`ascending`):k(`descending`)})}get sortValuesAndFields(){let e=this.props.definition.sortedColumn;if(!e)return[];let t=this.env.model.getters.getPivot(this.props.pivotId),n=this.env.model.getters.getLocale(),r=[],i=[];for(let a of e.domain){r.push(a);let{value:e,format:o}=t.getPivotHeaderValueAndFormat(r),s=z(e,{format:o,locale:n}),c=t.definition.getDimension(a.field);i.push({field:Ch(c),value:s})}e.domain.length===0&&i.push({value:k(`Total`)});let a=t.getMeasure(e.measure).displayName;return i.push({value:a,field:k(`Measure`)}),i}},yU=class extends t.Component{static template=`o-spreadsheet-PivotLayoutConfigurator`;static components={AddDimensionButton:XH,PivotDimension:ZH,PivotDimensionOrder:$H,PivotDimensionGranularity:QH,PivotMeasureEditor:_U,PivotSortSection:vU,PivotCustomGroupsCollapsible:JH};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=Sk();AGGREGATORS=sh;composerFocus;isDateOrDatetimeField=ph;setup(){this.composerFocus=D(_r)}startDragAndDrop(e,t){if(t.button!==0||t.target.tagName===`SELECT`)return;let n=this.getDimensionElementsRects(),{columns:r,rows:i}=this.props.definition,a=[...r.map(e=>e.nameWithGranularity),`__rows_title__`,...i.map(e=>e.nameWithGranularity)],o=r.concat(i),s=a.map((e,t)=>({id:e,size:n[t+1].height,position:n[t+1].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.nameWithGranularity,initialMousePosition:t.clientY,items:s,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{let n=a.findIndex(t=>t===e);if(n===t)return;let r=[...a];r.splice(n,1),r.splice(t,0,e);let i=r.slice(0,r.indexOf(`__rows_title__`)),s=r.slice(r.indexOf(`__rows_title__`)+1);this.props.onDimensionsUpdated({columns:i.map(e=>o.find(t=>t.nameWithGranularity===e)).filter(C),rows:s.map(e=>o.find(t=>t.nameWithGranularity===e)).filter(C)})}})}getGranularitiesFor(e){return ph(e)?e.type===`date`?this.props.dateGranularities:this.props.datetimeGranularities:[]}startDragAndDropMeasures(e,t){if(t.button!==0||t.target.tagName===`SELECT`||t.target.tagName===`INPUT`||this.composerFocus.focusMode!==`inactive`)return;let n=this.getDimensionElementsRects(),{measures:r,columns:i,rows:a}=this.props.definition,o=r.map(e=>e.id),s=3+i.length+a.length,c=o.map((e,t)=>({id:e,size:n[t+s].height,position:n[t+s].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.id,initialMousePosition:t.clientY,items:c,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{let n=o.findIndex(t=>t===e);if(n===t)return;let i=[...o];i.splice(n,1),i.splice(t,0,e),this.props.onDimensionsUpdated({measures:i.map(e=>r.find(t=>t.id===e)).filter(C)})}})}getDimensionElementsRects(){return Array.from(this.dimensionsRef.el.children).map(e=>{let t=getComputedStyle(e),n=e.getBoundingClientRect();return{x:n.x,y:n.y,width:n.width+parseInt(t.marginLeft||`0`)+parseInt(t.marginRight||`0`),height:n.height+parseInt(t.marginTop||`0`)+parseInt(t.marginBottom||`0`)}})}removeDimension(e){let{columns:t,rows:n}=this.props.definition;this.props.onDimensionsUpdated({columns:t.filter(t=>t.nameWithGranularity!==e.nameWithGranularity),rows:n.filter(t=>t.nameWithGranularity!==e.nameWithGranularity)})}removeMeasureDimension(e){let{measures:t}=this.props.definition;this.props.onDimensionsUpdated({measures:t.filter(t=>t.id!==e.id)})}addColumnDimension(e){let{columns:t}=this.props.definition;this.props.onDimensionsUpdated({columns:t.concat([{fieldName:e,order:`asc`}])})}addRowDimension(e){let{rows:t}=this.props.definition;this.props.onDimensionsUpdated({rows:t.concat([{fieldName:e,order:`asc`}])})}addMeasureDimension(e){let{measures:t}=this.props.definition,n=this.getDefaultMeasureAggregator(e);this.props.onDimensionsUpdated({measures:t.concat([{id:this.getMeasureId(e,n),fieldName:e,aggregator:n}])})}updateMeasure(e,t){let{measures:n}=this.props.definition,r={measures:n.map(n=>n.id===e.id?t:n)};this.props.definition.sortedColumn?.measure===e.id&&(r.sortedColumn={...this.props.definition.sortedColumn,measure:t.id}),this.props.onDimensionsUpdated(r)}getMeasureId(e,t){let n=e.replaceAll(`'`,``)+(t?`:${t}`:``),r=n,i=2;for(;this.props.definition.measures.some(e=>e.id===r);)r=`${n}:${i}`,i++;return r}getDefaultMeasureAggregator(e){let t=this.props.measureFields.find(t=>t.name===e);return t?.aggregator?t.aggregator:`count`}addCalculatedMeasure(){let{measures:e}=this.props.definition,t=this.env.model.getters.generateNewCalculatedMeasureName(e);this.props.onDimensionsUpdated({measures:e.concat([{id:this.getMeasureId(t,`sum`),fieldName:t,aggregator:`sum`,computedBy:{sheetId:this.env.model.getters.getActiveSheetId(),formula:`=0`}}])})}getCustomField(e){return this.env.model.getters.getPivotCoreDefinition(this.props.pivotId).customFields?.[e.nameWithGranularity]}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?Ch(r):``;return nm.descriptions[t.type](i)}getHugeDimensionErrorMessage(e){let t=this.env.model.getters.getPivot(this.props.pivotId).getPossibleFieldValues(e);return t.length>100?k(`This dimension contains a lot of values (%s), and might slow down the pivot table.`,t.length):void 0}},bU=class extends t.Component{static template=`o-spreadsheet-PivotTitleSection`;static components={CogWheelMenu:SV,Section:q,TextInput:gV};static props={pivotId:String,flipAxis:Function};get cogWheelMenuItems(){return[{name:k(`Flip axes`),icon:`o-spreadsheet-Icon.EXCHANGE`,execute:this.props.flipAxis},{name:k(`Duplicate`),icon:`o-spreadsheet-Icon.COPY`,execute:()=>this.duplicatePivot()},{name:k(`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?k(`Pivot duplicated.`):n.isCancelledBecause(`PivotInError`)?k(`Cannot duplicate a pivot in error.`):k(`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(k(`Are you sure you want to delete this pivot?`),()=>{this.env.model.dispatch(`REMOVE_PIVOT`,{pivotId:this.props.pivotId})})}onNameChanged(e){let t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);this.env.model.dispatch(`UPDATE_PIVOT`,{pivotId:this.props.pivotId,pivot:{...t,name:e}})}};let xU=yO.content;function SU(e){try{return YO(qO(e)).filter(e=>e.type===`FUNCALL`&&!xU[e.value.toUpperCase()]?.isExported).length===0}catch{return!1}}function CU(e,t){if(!e.some(e=>e.type===`SYMBOL`&&t.includes(e.value.toUpperCase())))return[];let n;try{n=qO(e)}catch{return[]}return wU(n,t)}function wU(e,t){return YO(e).filter(e=>e.type===`FUNCALL`&&t.includes(e.value.toUpperCase())).map(e=>({functionName:e.value.toUpperCase(),args:e.args}))}let TU=[`PIVOT.VALUE`,`PIVOT.HEADER`,`PIVOT`];function EU(e){return CU(e,TU)[0]}function DU(e){return CU(e,TU)}function OU(e){return CU(e,TU).length}function kU(e,t){let n=`"${t?`${e.name}:${t}`:e.name}"`,r=e.string===e.name?n:e.string+n;return{text:n,description:e.string+(e.help?` (${e.help})`:``),htmlContent:[{value:n,color:He.STRING}],fuzzySearchKey:r}}function AU(e){let t=`"${e.id}"`,n=e.displayName+e.fieldName+t;return{text:t,description:e.displayName,htmlContent:[{value:t,color:He.STRING}],fuzzySearchKey:n}}function jU(e,t){let n=e.end,r=e.end;e.type!==`ARG_SEPARATOR`&&(n=e.start),this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t)}function MU(e,t){let n=e.end,r=e.end;e.type!==`LEFT_PAREN`&&(n=e.start),this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t)}function NU(e){let t=e.functionContext?.args[0];if(!(!t||![`STRING`,`NUMBER`].includes(t.type)))return t.value}var PU=class extends hr{pivotId;updateMode;mutators=[`reset`,`deferUpdates`,`applyUpdate`,`discardPendingUpdate`,`update`];_updatesAreDeferred;draft=null;notification=this.get(ck);alreadyNotified=!1;alreadyNotifiedForPivotSize=!1;constructor(e,t,n=`canDefer`){super(e),this.pivotId=t,this.updateMode=n,this._updatesAreDeferred=this.getters.getPivotCoreDefinition(this.pivotId).deferUpdates??!1}handle(e){switch(e.type){case`UPDATE_PIVOT`:e.pivotId===this.pivotId&&this.getters.getPivot(this.pivotId).init()}}get updatesAreDeferred(){return this.updateMode===`neverDefer`?!1:this._updatesAreDeferred}get fields(){return this.pivot.getFields()}get pivot(){return this.getters.getPivot(this.pivotId)}get definition(){let e=ZL.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:k(`Count`),type:`integer`,aggregator:`sum`}],t=this.fields;for(let n in t){let r=t[n];r&&ZL.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&&ZL.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=>ph(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 ZL.get(this.pivot.type).datetimeGranularities}get dateGranularities(){return ZL.get(this.pivot.type).dateGranularities}get unusedGranularities(){return this.getUnusedGranularities(this.fields,this.draft??this.getters.getPivotCoreDefinition(this.pivotId))}reset(e){this.pivotId=e,this._updatesAreDeferred=!0,this.draft=null}deferUpdates(e){e===!1&&this.draft?(this.draft.deferUpdates=!1,this.applyUpdate()):this.update({deferUpdates:e}),this._updatesAreDeferred=e}applyUpdate(){if(this.draft){if(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:k(`Pivot updates only work with dynamic pivot tables. Use the formula '%s' or re-insert the static pivot from the Data menu.`,e),sticky:!0})}let e=this.getters.getPivot(this.pivotId),t=e.isValid()?e.getExpandedTableStructure().numberOfCells:0;!this.alreadyNotifiedForPivotSize&&t>5e5&&(this.alreadyNotifiedForPivotSize=!0,this.notification.notifyUser({type:`warning`,text:rm(t,this.getters.getLocale()),sticky:!0}))}}discardPendingUpdate(){this.draft=null}update(e){let t=this.getters.getPivotCoreDefinition(this.pivotId),n={...t,...this.draft,...e},r={...n,columns:n.columns.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),rows:n.rows.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),measures:n.measures.map(e=>({id:e.id,fieldName:e.fieldName,aggregator:e.aggregator,userDefinedName:e.userDefinedName,computedBy:e.computedBy,isHidden:e.isHidden,format:e.format,display:e.display})),sortedColumn:this.shouldKeepSortedColumn(n)?n.sortedColumn:void 0};if(r.collapsedDomains){let{COL:e,ROW:t}=r.collapsedDomains;r.collapsedDomains={COL:e.filter(e=>this.areDomainFieldsValid(e,r.columns)),ROW:t.filter(e=>this.areDomainFieldsValid(e,r.rows))}}if(!this.draft&&w(t,r))return;let i=this.addDefaultDateTimeGranularity(this.fields,r);this.draft=i,this.updatesAreDeferred||this.applyUpdate()}isUpdatedPivotVisibleInViewportOnlyAsStaticPivot(){let e=0,t=this.getters.getPivotFormulaId(this.pivotId);for(let n of this.getters.getVisibleCellPositions()){let r=this.getters.getCell(n);if(r?.isFormula){let n=EU(r.compiledFormula.tokens),i=n?.args[0]?.value;if(n&&t===i.toString()){if(n.functionName===`PIVOT`)return!1;e++}}}return e>0}addDefaultDateTimeGranularity(e,t){let{columns:n,rows:r}=t,i=b(n),a=b(r),o=this.getUnusedGranularities(e,t);for(let t of i.concat(a)){let n=e[t.fieldName]?.type;if((n===`date`||n===`datetime`)&&!t.granularity){let e=o[t.fieldName]?.values().next().value;o[t.fieldName]?.delete(e),t.granularity=e}}return{...t,columns:i,rows:a}}getUnusedGranularities(e,t){let{columns:n,rows:r,measures:i}=t,a=n.concat(r).concat(i).filter(t=>{let n=e[t.fieldName]?.type;return n===`date`||n===`datetime`}),o={};for(let t of a)o[t.fieldName]=new Set(e[t.fieldName]?.type===`date`?this.dateGranularities:this.datetimeGranularities);for(let e of a)o[e.fieldName].delete(e.granularity);return o}shouldKeepSortedColumn(e){let{sortedColumn:t}=e;if(!t)return!0;let n=this.getters.getPivotCoreDefinition(this.pivotId);return e.measures.find(e=>e.id===t.measure)&&w(n.columns,e.columns)}areDomainFieldsValid(e,t){let n=t.map(({fieldName:e,granularity:t})=>e+(t?`:${t}`:``));for(let t=0;t<e.length;t++)if(e[t].field!==n[t])return!1;return!0}},FU=class extends t.Component{static template=`o-spreadsheet-PivotSpreadsheetSidePanel`;static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:yU,Section:q,SelectionInput:kk,Checkbox:Fk,PivotDeferUpdate:qH,PivotTitleSection:bU};store;state;pivotSidePanelRef=(0,t.useRef)(`pivotSidePanel`);setup(){this.store=or(PU,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 IU=new B;IU.add(`SPREADSHEET`,{editor:FU});var LU=class extends t.Component{static template=`o-spreadsheet-PivotDesignPanel`;static props={pivotId:String};static components={Section:q,Checkbox:Fk,NumberInput:LV};store;setup(){this.store=or(PU,this.props.pivotId,`neverDefer`)}updatePivotStyleNumberProperty(e,t){let n=parseInt(e);this.store.update({style:{...this.pivotStyle,[t]:isNaN(n)?void 0:n}})}updatePivotStyleProperty(e,t){this.store.update({style:{...this.pivotStyle,[e]:t}})}get pivotStyle(){return this.env.model.getters.getPivotCoreDefinition(this.props.pivotId).style||{}}get defaultStyle(){return rh}},RU=class extends t.Component{static template=`o-spreadsheet-PivotSidePanel`;static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:yU,Section:q,PivotDesignPanel:LU};state=(0,t.useState)({panel:`configuration`});setup(){OH(this)}get sidePanelEditor(){let e=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);if(!e)throw Error(`pivotId does not correspond to a pivot.`);return IU.get(e.type).editor}get highlights(){return GH(this.env.model.getters,this.props.pivotId)}switchPanel(e){this.state.panel=e}},zU=class extends t.Component{static template=`o-spreadsheet-RemoveDuplicatesPanel`;static components={ValidationMessages:IB,Section:q,Checkbox:Fk};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=k(`Column %s`,Ht(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)}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(em.Errors[n]||em.Errors.Unexpected);return Array.from(t)}get selectionStatisticalInformation(){let e=On(this.env.model.getters.getSelectedZone());return k(`%(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))}},BU=class extends t.Component{static template=`o-spreadsheet-SettingsPanel`;static components={Section:q,ValidationMessages:IB,BadgeSelection:AV};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=Uv(e);return t||console.warn(`Invalid locale: ${e.code} ${e}`),t}).sort((e,t)=>e.name.localeCompare(t.name))}get numberFormatPreview(){return z(1234567.89,{format:`#,##0.00`,locale:this.env.model.getters.getLocale()})}get dateFormatPreview(){let e=this.env.model.getters.getLocale();return z(1.6,{format:e.dateFormat,locale:e})}get dateTimeFormatPreview(){let e=this.env.model.getters.getLocale();return z(1.6,{format:oy(e),locale:e})}get firstDayOfWeek(){return Vo[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(!w(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 VU={SplitIsDestructive:k(`This will overwrite data in the subsequent columns. Split anyway?`)};function HU(e,t,n){let r=e.model.dispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:t,addNewColumns:n});return r.isCancelledBecause(`SplitWillOverwriteContent`)&&e.askConfirmation(VU.SplitIsDestructive,()=>{r=e.model.dispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:t,addNewColumns:n,force:!0})}),r}let UU=[{name:k(`Detect automatically`),value:`auto`},{name:k(`Custom separator`),value:`custom`},{name:k(`Space`),value:` `},{name:k(`Comma`),value:`,`},{name:k(`Semicolon`),value:`;`},{name:k(`Line Break`),value:`
|
|
116
|
+
`}];var WU=class extends t.Component{static template=`o-spreadsheet-SplitIntoColumnsPanel`;static components={ValidationMessages:IB,Section:q,Checkbox:Fk};static props={onCloseSidePanel:Function};state=(0,t.useState)({separatorValue:`auto`,addNewColumns:!1,customSeparator:``});setup(){let e=D(_r);(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(){HU(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($p.Errors[n]||$p.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($p.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 UU}get isConfirmDisabled(){return!this.separatorValue||this.errorMessages.length>0}};function GU(e,t){return e.model.getters.isTableStyleEditable(t)?p([{id:`editTableStyle`,name:k(`Edit table style`),execute:e=>e.openSidePanel(`TableStyleEditorPanel`,{styleId:t}),isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.EDIT`},{id:`deleteTableStyle`,name:k(`Delete table style`),execute:e=>e.model.dispatch(`REMOVE_TABLE_STYLE`,{tableStyleId:t}),icon:`o-spreadsheet-Icon.TRASH`}]):[]}function KU(e,t,n,r){e.resetTransform(),qU(e,t,n,r),JU(e,t,n,r),YU(e,t,n,r)}function qU(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 JU(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 YU(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()}var XU=class extends t.Component{static template=`o-spreadsheet-TableStylePreview`;static components={MenuPopover:Dv};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,anchorRect:null,menuItems:[]});setup(){(0,t.onWillUpdateProps)(e=>{(!w(this.props.tableConfig,e.tableConfig)||!w(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,KU(t,nI(e.tableConfig,e.tableStyle,5,5),(n-1)/5,(r-1)/5)}onContextMenu(e){this.props.styleId&&(this.menu.menuItems=GU(this.env,this.props.styleId),this.menu.isOpen=!0,this.menu.anchorRect={x:e.clientX,y:e.clientY,width:0,height:0})}closeMenu(){this.menu.isOpen=!1,this.menu.anchorRect=null,this.menu.menuItems=[]}get styleName(){return this.props.styleId?this.env.model.getters.getTableStyle(this.props.styleId).displayName:``}get isStyleEditable(){return this.props.styleId?this.env.model.getters.isTableStyleEditable(this.props.styleId):!1}editTableStyle(){this.env.openSidePanel(`TableStyleEditorPanel`,{styleId:this.props.styleId})}},ZU=class extends t.Component{static template=`o-spreadsheet-TableStylesPopover`;static components={Popover:Cv,TableStylePreview:XU};static props={tableConfig:Object,popoverProps:{type:Object,optional:!0},closePopover:Function,onStylePicked:Function,selectedStyleId:{type:String,optional:!0}};categories=xA;tableStyleListRef=(0,t.useRef)(`tableStyleList`);state=(0,t.useState)({selectedCategory:this.initialSelectedCategory});setup(){(0,t.useExternalListener)(window,`click`,this.onExternalClick,{capture:!0})}onExternalClick(e){this.tableStyleListRef.el&&!Zf(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})}},QU=class extends t.Component{static template=`o-spreadsheet-TableStylePicker`;static components={TableStylesPopover:ZU,TableStylePreview:XU};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:`top-right`,verticalOffset:0}}closePopover(){this.state.popoverProps=void 0}},$U=class extends t.Component{static template=`o-spreadsheet-TablePanel`;static components={TableStylePicker:QU,SelectionInput:kk,ValidationMessages:IB,Checkbox:Fk,Section:q,NumberInput:LV};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($F(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:this.env.model.getters.getRangeData(n.range),tableType:t}),a=this.env.model.getters.getCoreTable($F(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=parseInt(e);this.updateNumberOfHeaders(t)}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(Vn(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:this.env.model.getters.getRangeData(t),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=$F(s);this.env.model.selection.selectZone({zone:E(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=>tm.Errors[e]||tm.Errors.Unexpected)}getCheckboxLabel(e){return tm.Checkboxes[e]}get canHaveFilters(){return this.tableConfig.numberOfHeaders>0}get hasFilterCheckboxTooltip(){return this.canHaveFilters?void 0:tm.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 tm.Tooltips.isDynamic}};let eW=`#3C78D8`;var tW=class extends t.Component{static template=`o-spreadsheet-TableStyleEditorPanel`;static components={Section:q,RoundColorPicker:bk,TableStylePreview:XU};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||eW,selectedTemplateName:e?.templateName||`lightColoredText`,styleName:e?.displayName||this.env.model.getters.getNewCustomTableStyleName()}}togglePicker(){this.state.pickerOpened=!this.state.pickerOpened}onColorPicked(e){this.state.primaryColor=Tr(e)?e:eW,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(LA).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 RA(this.state.styleName,e,this.state.primaryColor)}};let nW=new B;nW.add(`ConditionalFormatting`,{title:k(`Conditional formatting`),Body:MH}),nW.add(`ChartPanel`,{title:k(`Chart`),Body:TH,computeState:(e,t)=>{let n=e.getSelectedFigureId(),r=n?e.getChartIdFromFigureId(n):t.chartId;return!r||!e.isChartDefined(r)?{isOpen:!1}:{isOpen:!0,props:{chartId:r}}}}),nW.add(`FindAndReplace`,{title:k(`Find and Replace`),Body:RH}),nW.add(`SplitToColumns`,{title:k(`Split text into columns`),Body:WU}),nW.add(`Settings`,{title:k(`Spreadsheet settings`),Body:BU}),nW.add(`RemoveDuplicates`,{title:k(`Remove duplicates`),Body:zU}),nW.add(`DataValidation`,{title:k(`Data validation`),Body:FH}),nW.add(`DataValidationEditor`,{title:k(`Data validation`),Body:NH}),nW.add(`MoreFormats`,{title:k(`More formats`),Body:HH}),nW.add(`TableSidePanel`,{title:k(`Edit table`),Body:$U,computeState:e=>{let t=e.getFirstTableInSelection();return t?{isOpen:!0,props:{table:e.getCoreTable($F(t))},key:t.id}:{isOpen:!1}}}),nW.add(`TableStyleEditorPanel`,{title:k(`Create custom table style`),Body:tW,computeState:(e,t)=>({isOpen:!0,props:{...t},key:t.styleId??`new`})}),nW.add(`PivotSidePanel`,{title:(e,t)=>k(`Pivot #%s`,e.model.getters.getPivotFormulaId(t.pivotId)),Body:RU,computeState:(e,t)=>({isOpen:e.isExistingPivot(t.pivotId),props:t,key:`pivot_key_${t.pivotId}`})}),nW.add(`PivotMeasureDisplayPanel`,{title:(e,t)=>k(`Measure "%s" options`,e.model.getters.getPivot(t.pivotId).getMeasure(t.measure.id).displayName),Body:WH,computeState:(e,t)=>{try{return e.getPivot(t.pivotId).getMeasure(t.measure.id),{isOpen:!0,props:t,key:`pivot_measure_display_${t.pivotId}_${t.measure.id}`}}catch{return{isOpen:!1}}}}),nW.add(`CarouselPanel`,{title:k(`Carousel`),Body:CV,computeState:(e,t)=>{let n=t.figureId||e.getSelectedFigureId();return!n||!e.doesCarouselExist(n)?{isOpen:!1}:{isOpen:!0,props:{figureId:n}}}});var rW=class{mutators=[`setSmallThreshhold`];_isSmallCallback=()=>!1;get isSmall(){return this._isSmallCallback()}setSmallThreshhold(e){this._isSmallCallback=e}},iW=class extends hr{mutators=[`open`,`replace`,`toggle`,`close`,`changePanelSize`,`resetPanelSize`,`togglePinPanel`,`closeMainPanel`,`changeSpreadsheetWidth`,`toggleCollapsePanel`];mainPanel=void 0;secondaryPanel;availableWidth=0;screenWidthStore=this.get(rW);get isMainPanelOpen(){return this.mainPanel&&this.mainPanel.componentTag?this.computeState(this.mainPanel).isOpen:!1}get isSecondaryPanelOpen(){return this.secondaryPanel&&this.secondaryPanel.componentTag?this.computeState(this.secondaryPanel).isOpen:!1}get mainPanelProps(){return this.mainPanel?this.getPanelProps(this.mainPanel):void 0}get mainPanelKey(){return this.mainPanel?this.getPanelKey(this.mainPanel):void 0}get secondaryPanelProps(){return this.secondaryPanel?this.getPanelProps(this.secondaryPanel):void 0}get secondaryPanelKey(){return this.secondaryPanel?this.getPanelKey(this.secondaryPanel):void 0}get totalPanelSize(){return(this.mainPanel?.size||0)+(this.secondaryPanel?.size??0)}getPanelProps(e){let t=this.computeState(e);return t.isOpen?(e.currentPanelProps=t.props??e.currentPanelProps,t.props??{}):{}}getPanelKey(e){let t=this.computeState(e);if(t.isOpen)return t.key}open(e,t={}){if(this.screenWidthStore.isSmall)return;let n={currentPanelProps:t,componentTag:e,size:350},r=this.computeState(n);if(!r.isOpen)return;if(!this.mainPanel||!this.mainPanel.isPinned||this.mainPanelKey===r.key){this._openPanel(`mainPanel`,n,r);return}let i=this.mainPanel.isCollapsed?350:this.mainPanel.size;if(!this.secondaryPanel&&i+350>this.availableWidth){this.get(ck).notifyUser({sticky:!1,type:`warning`,text:k(`The window is too small to display multiple side panels.`)});return}this._openPanel(`secondaryPanel`,n,r)}replace(e,t,n={}){let r={currentPanelProps:n,componentTag:e,size:350},i=this.computeState(r);if(!i.isOpen)return;let a=()=>{this.mainPanel?.isCollapsed&&this.toggleCollapsePanel(`mainPanel`)},o=this.mainPanelKey===i.key,s=this.secondaryPanelKey===i.key;if(o&&this.secondaryPanel){this.close(),a();return}if(s){this.closeMainPanel(),this.togglePinPanel(),a();return}let c=this.mainPanelKey===t?`mainPanel`:`secondaryPanel`;this._openPanel(c,r,i)}_openPanel(e,t,n){let r=this[e];r&&t.componentTag!==r.componentTag&&r.currentPanelProps?.onCloseSidePanel?.(),this[e]={currentPanelProps:n.props??{},componentTag:t.componentTag,size:r?.size||350,isCollapsed:r?.isCollapsed||!1,isPinned:r&&`isPinned`in r?r.isPinned:!1},this[e].isCollapsed&&this.toggleCollapsePanel(e)}toggle(e,t){let n=this.mainPanel?.isPinned?this.secondaryPanel:this.mainPanel;n&&e===n.componentTag?this.close():this.open(e,t)}close(){if(this.mainPanel?.isPinned){this.secondaryPanel&&=(this.secondaryPanel.currentPanelProps.onCloseSidePanel?.(),void 0);return}this.mainPanel?.currentPanelProps.onCloseSidePanel?.(),this.mainPanel=void 0}closeMainPanel(){this.mainPanel?.currentPanelProps.onCloseSidePanel?.(),this.mainPanel=this.secondaryPanel||void 0,this.secondaryPanel=void 0}changePanelSize(e,t){let n=this[e];if(!n||`isCollapsed`in n&&n.isCollapsed)return;t=Math.max(t,350);let r=e===`mainPanel`?this.secondaryPanel?.size||0:this.mainPanel?.size||0;t>this.availableWidth-r&&(e===`mainPanel`&&this.secondaryPanel&&(this.secondaryPanel.size=Math.max(this.availableWidth-t,350),r=this.secondaryPanel.size),t=Math.max(this.availableWidth-r,350)),n.size=t}resetPanelSize(e){this[e]&&(this[e].size=350)}togglePinPanel(){this.mainPanel&&(this.mainPanel.isPinned=!this.mainPanel.isPinned,!this.mainPanel.isPinned&&this.secondaryPanel&&(this.secondaryPanel?.currentPanelProps.onCloseSidePanel?.(),this.mainPanel=this.secondaryPanel,this.secondaryPanel=void 0))}toggleCollapsePanel(e){let t=this[e];t&&(t.isCollapsed?(t.isCollapsed=!1,this.changePanelSize(e,350)):(t.isCollapsed=!0,t.size=45))}computeState({componentTag:e,currentPanelProps:t}){let n=nW.get(e).computeState,r=n?n(this.getters,t):{isOpen:!0,props:t};return r.isOpen?{...r,key:r.key||e}:r}changeSpreadsheetWidth(e){this.availableWidth=e-150,this.secondaryPanel&&e-this.totalPanelSize<150&&(this.secondaryPanel?.currentPanelProps.onCloseSidePanel?.(),this.secondaryPanel=void 0),this.mainPanel&&e-this.totalPanelSize<150&&(this.mainPanel.size=Math.max(e-150,350))}},aW=class extends t.Component{static template=`o-spreadsheet-TableResizer`;static props={table:Object};state=(0,t.useState)({highlightZone:void 0});dragNDropGrid=Xz(this.env);setup(){OH(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`;let r=yp(this.env,e);this.dragNDropGrid.start(r,(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?[{range:this.env.model.getters.getRangeFromZone(this.props.table.range.sheetId,this.state.highlightZone),color:`#777`,noFill:!0}]:[]}};let oW={ROW:qz,COL:Bz,CELL:SR,GROUP_HEADERS:Gz,UNGROUP_HEADERS:Kz};var sW=class extends t.Component{static template=`o-spreadsheet-Grid`;static props={exposeFocus:Function,getGridSize:Function};static components={GridComposer:TB,GridOverlay:KB,GridPopover:qB,HeadersOverlay:$B,MenuPopover:Dv,Autofill:Qz,ClientTag:eB,Highlight:cV,Popover:Cv,VerticalScrollBar:fV,HorizontalScrollBar:dV,TableResizer:aW,Selection:pV};HEADER_HEIGHT=26;HEADER_WIDTH=48;menuState;gridRef;highlightStore;cellPopovers;composerFocusStore;DOMFocusableElementStore;paintFormatStore;clientFocusStore;dragNDropGrid=Xz(this.env);onMouseWheel;hoveredCell;sidePanel;setup(){this.highlightStore=D(sk),this.menuState=(0,t.useState)({isOpen:!1,anchorRect:null,menuItems:[]}),this.gridRef=(0,t.useRef)(`grid`),this.hoveredCell=D(Pv),this.composerFocusStore=D(_r),this.DOMFocusableElementStore=D(xO),this.sidePanel=D(iW),this.paintFormatStore=D(HB),this.clientFocusStore=D(Yz),D(Jz),(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()),tV(`canvas`,this.env.model,()=>this.env.model.getters.getSheetViewDimensionWithHeaders()),this.onMouseWheel=iV((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=D(Bk),(0,t.useEffect)((e,t)=>{!e&&!t&&this.DOMFocusableElementStore.focus()},()=>[this.sidePanel.isMainPanelOpen,this.sidePanel.isSecondaryPanelOpen]),rV(this.gridRef,this.moveCanvas.bind(this),()=>{let{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0},()=>{let{maxOffsetY:e}=this.env.model.getters.getMaximumSheetOffset(),{scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo();return t<e})}get highlights(){return this.highlightStore.highlights}get gridOverlayDimensions(){let e=this.env.model.getters.getScrollBarWidth();return U({top:`26px`,left:`48px`,height:`calc(100% - ${26+e}px)`,width:`calc(100% - ${48+e}px)`})}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_UNFILTERED_CONTENT`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Backspace:()=>{this.env.model.dispatch(`DELETE_UNFILTERED_CONTENT`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Escape:()=>{this.cellPopovers.isOpen?this.cellPopovers.close():this.menuState.isOpen?this.closeMenu():this.paintFormatStore.isActive?this.paintFormatStore.cancel():this.env.model.dispatch(`CLEAN_CLIPBOARD_HIGHLIGHT`)},"Ctrl+A":()=>this.env.model.selection.loopSelection(),"Ctrl+Z":()=>this.env.model.dispatch(`REQUEST_UNDO`),"Ctrl+Y":()=>this.env.model.dispatch(`REQUEST_REDO`),F4:()=>this.env.model.dispatch(`REQUEST_REDO`),"Ctrl+B":()=>this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{bold:!this.env.model.getters.getCurrentStyle().bold}}),"Ctrl+I":()=>this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{italic:!this.env.model.getters.getCurrentStyle().italic}}),"Ctrl+U":()=>this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{underline:!this.env.model.getters.getCurrentStyle().underline}}),"Ctrl+O":()=>iF(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&&$s(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+H":()=>this.sidePanel.open(`FindAndReplace`,{}),"Ctrl+F":()=>this.sidePanel.open(`FindAndReplace`,{}),"Ctrl+Shift+E":()=>this.setHorizontalAlign(`center`),"Ctrl+Shift+L":()=>this.setHorizontalAlign(`left`),"Ctrl+Shift+R":()=>this.setHorizontalAlign(`right`),"Ctrl+Shift+V":()=>NP(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?YP(this.env):i&&!r&&qP(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(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:`COL`,elements:e}):t.length>0&&e.length===0&&this.env.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:this.env.model.getters.getActiveSheetId(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:`ROW`,elements:t})},"Shift+PageDown":()=>{this.env.model.dispatch(`ACTIVATE_NEXT_SHEET`)},"Shift+PageUp":()=>{this.env.model.dispatch(`ACTIVATE_PREVIOUS_SHEET`)},PageDown:()=>this.env.model.dispatch(`SHIFT_VIEWPORT_DOWN`),PageUp:()=>this.env.model.dispatch(`SHIFT_VIEWPORT_UP`),"Ctrl+K":()=>sF(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{x:t.x+t.width-8/2,y: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(){let{height:e,width:t}=this.props.getGridSize();this.env.model.dispatch(`RESIZE_SHEETVIEW`,{width:t-48,height:e-26,gridOffsetX:48,gridOffsetY:26})}moveCanvas(e,t){let{scrollX:n,scrollY:r}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:n+e,offsetY:r+t})}processSpaceKey(e){this.env.model.getters.hasBooleanValidationInZones(this.env.model.getters.getSelectedZones())&&(e.preventDefault(),e.stopPropagation(),this.env.model.dispatch(`TOGGLE_CHECKBOX`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()}))}getClientPositionKey(e){return`${e.id}-${e.position?.sheetId}-${e.position?.col}-${e.position?.row}`}isCellHovered(e,t){return this.hoveredCell.col===e&&this.hoveredCell.row===t}get focusedClients(){return this.clientFocusStore.focusedClients}getGridRect(){let e=this.env.model.getters.getViewportZoomLevel(),{width:t,height:n}=this.env.model.getters.getSheetViewDimensionWithHeaders();return{...ep(this.gridRef),width:t*e,height:n*e}}onCellClicked(e,t,n,r){if(r.ev.preventDefault(),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),this.env.isMobile())return;let i=e,a=t;this.dragNDropGrid.start(r,(e,t,n)=>{n.preventDefault(),(e!==i&&e!==-1||t!==a&&t!==-1)&&(i=e===-1?i:e,a=t===-1?a:t,this.env.model.selection.setAnchorCorner(i,a))},()=>{this.env.model.selection.commitSelection(),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(),CO(e,this.env.model.selection),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())}onKeydown(e){let t=cp(e),n=this.keyDownMapping[t];if(n){e.preventDefault(),e.stopPropagation(),n();return}if(t===` `){this.processSpaceKey(e);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.getVisibleRectWithZoom(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`;En(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.anchorRect={x:t,y:n,width:0,height:0},this.menuState.menuItems=oW[e].getMenuItems()}async copy(e,t){if(!this.gridEl.contains(document.activeElement)||this.composerFocusStore.activeComposer.editionMode!==`inactive`)return;e?cI(this.env):this.env.model.dispatch(`COPY`);let n=await this.env.model.getters.getClipboardTextAndImageContent();await this.env.clipboard.write(n),t.preventDefault()}async paste(e){if(!this.gridEl.contains(document.activeElement))return;e.preventDefault();let t=e.clipboardData;if(!t)return;let n=[...t.files]?.find(e=>eA.includes(e.type)),r={content:{"text/plain":t?.getData(`text/plain`),"text/html":t?.getData(`text/html`)}};n&&(r.content[n.type]=n);let i=this.env.model.getters.getSelectedZones(),a=this.env.model.getters.isCutOperation(),o=this.env.model.getters.getClipboardId(),s=iA(r.content);o===s.data?.clipboardId?DP(this.env,i):await OP(this.env,i,s),a&&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.getVisibleRectWithZoom(n),i=this.getGridRect();this.toggleContextMenu(`GROUP_HEADERS`,e+r+i.x,t+i.y);break}case`left`:{if(!XF(this.env,`COL`)&&!XF(this.env,`ROW`))return;let{x:e,y:t,width:r}=this.env.model.getters.getVisibleRectWithZoom(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(tI)}get displaySelectionHandler(){return this.env.isMobile()&&this.composerFocusStore.activeComposer.editionMode===`inactive`}};let cW=new B;cW.add(`SPREADSHEET`,!1);var lW=class extends t.Component{static template=`o-spreadsheet-ClickableCellSortIcon`;static props={position:Object,sortDirection:String};hoveredTableStore;setup(){this.hoveredTableStore=D(UB)}get style(){let e=this.env.model.getters.getCellComputedStyle(this.props.position);return U({color:e.textColor||`#374151C2`,"background-color":this.getBackgroundColor(e)})}get verticalJustifyClass(){switch(this.env.model.getters.getCellComputedStyle(this.props.position).verticalAlign){case`top`:return`justify-content-start`;case`middle`:return`justify-content-center`;default:return`justify-content-end`}}getBackgroundColor(e){let t=this.hoveredTableStore.overlayColors.get(this.props.position);return t?Lr(e.fillColor||`#FFFFFF`,t):e.fillColor||`#FFFFFF`}},uW=class extends t.Component{static template=`o-spreadsheet-FullScreenFigure`;static props={};static components={ChartFigure:Av};fullScreenFigureStore;ref=(0,t.useRef)(`fullScreenFigure`);spreadsheetRect=xv();figureRegistry=Mv;setup(){this.fullScreenFigureStore=D(cv);let e=D(Zl),n;(0,t.onWillUpdateProps)(()=>{n!==this.figureUI?.id&&e.enableAnimationForChart(this.chartId+`-fullscreen`),n=this.figureUI?.id}),(0,t.useEffect)(e=>e?.focus(),()=>[this.ref.el])}get figureUI(){return this.fullScreenFigureStore.fullScreenFigure}get chartId(){if(this.figureUI)return this.env.model.getters.getChartIdFromFigureId(this.figureUI?.id)}exitFullScreen(){this.figureUI&&this.fullScreenFigureStore.toggleFullScreenFigure(this.figureUI.id)}onKeyDown(e){e.key===`Escape`&&this.exitFullScreen()}get figureComponent(){if(this.figureUI)return Mv.get(this.figureUI.tag).Component}},dW=class extends t.Component{static template=`o_spreadsheet.PivotHTMLRenderer`;static components={Checkbox:Fk};static props={pivotId:String,onCellClicked:Function};pivot=this.env.model.getters.getPivot(this.props.pivotId);data={columns:[],rows:[],values:[]};state=(0,t.useState)({showMissingValuesOnly:!1});setup(){let e=this.pivot.getExpandedTableStructure(),t=this.env.model.getters.getPivotFormulaId(this.props.pivotId);this.data={columns:this._buildColHeaders(t,e),rows:this._buildRowHeaders(t,e),values:this._buildValues(t,e)}}get tracker(){return this.env.model.getters.getPivotPresenceTracker(this.props.pivotId)}getTableData(){if(!this.state.showMissingValuesOnly)return this.data;let e=this.getColumnsIndexes(),t=this.getRowsIndexes();return{columns:this.buildColumnsMissing(e),rows:this.buildRowsMissing(t),values:this.buildValuesMissing(e,t)}}addRecursiveRow(e){let t=this.pivot.getExpandedTableStructure().rows,n=[...t[e].values];if(n.length<=1)return[e];n.pop();let r=t.findIndex(e=>JSON.stringify(e.values)===JSON.stringify(n));return[e].concat(this.addRecursiveRow(r))}buildColumnsMissing(e){let t=[];for(let e of this.data.columns){let n=[];for(let t in e)for(let r=0;r<e[t].span;r++)n.push(parseInt(t,10));t.push(n)}for(let n=t[t.length-1].length;n>=0;n--)if(!e.includes(n))for(let e of t)e.splice(n,1);let n=[];for(let e in t){let r=[],i,a=1;for(let n=0;n<t[e].length;n++)i===t[e][n]?a++:(i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),i=t[e][n],a=1);i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),n.push(r)}return n}buildRowsMissing(e){return e.map(e=>this.data.rows[e])}buildValuesMissing(e,t){let n=e.map(()=>[]);for(let r of t)for(let t in e)n[t].push(this.data.values[e[t]][r]);return n}getColumnsIndexes(){let e=new Set;for(let t=0;t<this.data.columns.length;t++){let n=[];for(let e=0;e<this.data.columns[t].length;e++)for(let r=0;r<this.data.columns[t][e].span;r++)n.push(this.data.columns[t][e]);for(let t=0;t<n.length;t++)n[t].isMissing&&e.add(t)}for(let t=0;t<this.data.columns[this.data.columns.length-1].length;t++)this.data.values[t].find(e=>e.isMissing)&&e.add(t);return Array.from(e).sort((e,t)=>e-t)}getRowsIndexes(){let e=new Set;for(let t=0;t<this.data.rows.length;t++){this.data.rows[t].isMissing&&e.add(t);for(let n of this.data.values)n[t].isMissing&&this.addRecursiveRow(t).forEach(t=>e.add(t))}return Array.from(e).sort((e,t)=>e-t)}_buildColHeaders(e,t){let n=[];for(let r of t.columns){let t=[];for(let n of r){let r=[];for(let e=0;e<n.fields.length;e++)r.push({value:n.fields[e]},{value:n.values[e]});let i=this.pivot.parseArgsToPivotDomain(r),a=this.env.model.getters.getLocale();if(i.at(-1)?.field===`measure`){let{value:r,format:o}=this.pivot.getPivotMeasureValue(P(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${mh(e,i).join(`,`)})`,value:z(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(${mh(e,i).join(`,`)})`,value:z(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(${mh(e,i).join(`,`)})`,value:z(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=P(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(${mh(e,o,a).join(`,`)})`,value:z(s,{format:c,locale:l}),isMissing:!this.tracker?.isValuePresent(a,o)})}n.push(i)}return n}},fW=class extends sb{getters;dispatch;canDispatch;constructor({getters:e,stateObserver:t,range:n,dispatch:r,canDispatch:i}){super(t),n.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.dispatch=r,this.canDispatch=i}import(e){}export(e){}adaptRanges(e,t,n){}},pW=class extends fW{static getters=[`getCellBorder`,`getBordersColors`];borders={};allowDispatch(e){switch(e.type){case`SET_BORDER`:return this.checkBordersUnchanged(e);default:return`Success`}}handle(e){switch(e.type){case`ADD_MERGE`:for(let t of e.target)this.addBordersToMerge(e.sheetId,t);break;case`DUPLICATE_SHEET`:let t=this.borders[e.sheetId];if(t){let n=t.slice().map(e=>e?.slice().map(e=>b(e)));this.history.update(`borders`,e.sheetIdTo,n)}break;case`DELETE_SHEET`:let n={...this.borders};delete n[e.sheetId],this.history.update(`borders`,n);break;case`SET_BORDER`:this.setBorder(e.sheetId,e.col,e.row,e.border);break;case`SET_BORDERS_ON_TARGET`:for(let t of e.target)for(let n=t.top;n<=t.bottom;n++)for(let r=t.left;r<=t.right;r++)this.setBorder(e.sheetId,r,n,e.border);break;case`SET_ZONE_BORDERS`:if(e.border){let t=e.target.map(t=>this.getters.expandZone(e.sheetId,t));this.setBorders(e.sheetId,t,e.border.position,e.border.color===``?void 0:{style:e.border.style||Te.style,color:e.border.color||Te.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 Ze(r))if(e.dimension===`COL`){let n=this.getters.getColsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersHorizontally(e.sheetId,t[0]+1,-t.length)}else{let n=this.getters.getRowsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersVertically(e.sheetId,t[0]+1,-t.length)}break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumns(e):this.handleAddRows(e);break}}handleAddColumns(e){let t,n;e.position===`before`?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity),t=e.base,n=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,n)}handleAddRows(e){let t,n;e.position===`before`?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity),t=e.base,n=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,n)}getCellBorder({sheetId:e,col:t,row:n}){let r=this.borders[e]?.[t]?.[n];return r?.top||r?.bottom||r?.left||r?.right?b(r):null}getBordersColors(e){let t=[],n=this.borders[e];if(n){for(let e of n.filter(C))for(let n of e)if(n)for(let e of[`top`,`bottom`,`left`,`right`]){let r=n[e]?.color;r&&t.push(r)}}return t}ensureColumnBorderContinuity(e,t,n){let r=S(t+1,n);for(let i=0;i<this.getters.getNumberRows(e);i++){let a=this.getCellBorder({sheetId:e,col:t,row:i}),o=this.getCellBorder({sheetId:e,col:n,row:i});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,n,i,t)}}}ensureRowBorderContinuity(e,t,n){let r=S(t+1,n);for(let i=0;i<this.getters.getNumberCols(e);i++){let a=this.getCellBorder({sheetId:e,col:i,row:t}),o=this.getCellBorder({sheetId:e,col:i,row:n});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,i,n,t)}}}getCommonSides(e,t){let n={};for(let r of[`top`,`bottom`,`left`,`right`])e[r]&&w(e[r],t[r])&&(n[r]=e[r]);return n}getColumnsWithBorders(e){let t=this.borders[e];return t?Object.keys(t).map(e=>parseInt(e,10)):[]}getRowsWithBorders(e){let t=this.borders[e]?.filter(C);if(!t)return[];let n=new Set;for(let e of t)for(let t in e)n.add(parseInt(t,10));return Array.from(n)}getRowsRange(e){return this.borders[e]?S(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,n){this.borders[e]&&this.getColumnsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(t=>{this.moveBordersOfColumn(e,t,n)})}shiftBordersVertically(e,t,n){this.borders[e]&&(n<0&&this.moveBordersOfRow(e,t,n,{destructive:!1}),this.getRowsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(t=>{this.moveBordersOfRow(e,t,n)}))}moveBordersOfRow(e,t,n,{destructive:r}={destructive:!0}){let i=this.borders[e];i&&this.getColumnsWithBorders(e).forEach(a=>{let o=i[a]?.[t+n],s=i[a]?.[t];this.history.update(`borders`,e,a,t+n,r?s:s||o),this.history.update(`borders`,e,a,t,void 0)})}moveBordersOfColumn(e,t,n,{destructive:r}={destructive:!0}){let i=this.borders[e];i&&this.getRowsRange(e).forEach(a=>{let o=i[t+n]?.[a],s=i[t]?.[a];this.history.update(`borders`,e,t+n,a,r?s:s||o),r&&this.history.update(`borders`,e,t,a,void 0)})}setBorder(e,t,n,r,i=!0){let a=this.getters.getNumberCols(e)-1,o=this.getters.getNumberRows(e)-1;(i||!this.borders[e]?.[t]?.[n]?.left)&&(this.history.update(`borders`,e,t,n,`left`,r?.left),r?.left&&t>0&&!w(this.borders[e]?.[t-1]?.[n]?.right,r?.left)&&this.history.update(`borders`,e,t-1,n,`right`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.top)&&(this.history.update(`borders`,e,t,n,`top`,r?.top),r?.top&&n>0&&!w(this.borders[e]?.[t]?.[n-1]?.bottom,r?.top)&&this.history.update(`borders`,e,t,n-1,`bottom`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.right)&&(this.history.update(`borders`,e,t,n,`right`,r?.right),r?.right&&t<a&&!w(this.borders[e]?.[t+1]?.[n]?.left,r?.right)&&this.history.update(`borders`,e,t+1,n,`left`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.bottom)&&(this.history.update(`borders`,e,t,n,`bottom`,r?.bottom),r?.bottom&&n<o&&!w(this.borders[e]?.[t]?.[n+1]?.top,r?.bottom)&&this.history.update(`borders`,e,t,n+1,`top`,void 0))}clearBorders(e,t,n=!1){let r=this.getters.getNumberCols(e)-1,i=this.getters.getNumberRows(e)-1;for(let a of Qt(t))for(let t=a.top;t<=a.bottom;t++){n&&(a.left>0&&this.history.update(`borders`,e,a.left-1,t,`right`,void 0),a.right<r&&this.history.update(`borders`,e,a.right+1,t,`left`,void 0));for(let r=a.left;r<=a.right;r++)this.history.update(`borders`,e,r,t,void 0),n&&(a.top>0&&this.history.update(`borders`,e,r,a.top-1,`bottom`,void 0),a.bottom<i&&this.history.update(`borders`,e,r,a.bottom+1,`top`,void 0))}}clearInsideBorders(e,t){for(let n of t)for(let t=n.top;t<=n.bottom;t++)for(let r=n.left;r<=n.right;r++)this.history.update(`borders`,e,r,t,void 0)}addBorder(e,t,n,r){this.setBorder(e,t,n,{...this.getCellBorder({sheetId:e,col:t,row:n}),...r})}setBorders(e,t,n,r){if(n===`clear`)return this.clearBorders(e,t,!0);for(let i of Qt(t)){if(n===`all`)for(let t=i.top;t<=i.bottom;t++)for(let n=i.left;n<=i.right;n++)this.addBorder(e,n,t,{top:r,right:r,bottom:r,left:r});if(n===`h`||n===`hv`){if(i.top===i.bottom)continue;for(let t=i.left;t<=i.right;t++){this.addBorder(e,t,i.top,{bottom:r});for(let n=i.top+1;n<i.bottom;n++)this.addBorder(e,t,n,{top:r,bottom:r});this.addBorder(e,t,i.bottom,{top:r})}}if(n===`v`||n===`hv`){if(i.left===i.right)continue;for(let t=i.top;t<=i.bottom;t++){this.addBorder(e,i.left,t,{right:r});for(let n=i.left+1;n<i.right;n++)this.addBorder(e,n,t,{left:r,right:r});this.addBorder(e,i.right,t,{left:r})}}if(n===`left`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.left,t,{left:r});if(n===`right`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.right,t,{right:r});if(n===`top`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.top,{top:r});if(n===`bottom`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.bottom,{bottom:r})}}addBordersToMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t,o=this.getCellBorder({sheetId:e,col:n,row:i}),s=this.getCellBorder({sheetId:e,col:r,row:a});this.clearBorders(e,[t]),o?.top&&this.setBorders(e,[{...t,bottom:i}],`top`,o.top),o?.left&&this.setBorders(e,[{...t,right:n}],`left`,o.left),s?.bottom?this.setBorders(e,[{...t,top:a}],`bottom`,s.bottom):o?.bottom&&this.setBorders(e,[{...t,top:a}],`bottom`,o.bottom),s?.right?this.setBorders(e,[{...t,left:r}],`right`,s.right):o?.right&&this.setBorders(e,[{...t,left:r}],`right`,o.right)}checkBordersUnchanged(e){let t=this.getCellBorder(e),n=!e.border?.bottom&&!e.border?.left&&!e.border?.right&&!e.border?.top;return!t&&n||w(t,e.border)?`NoChanges`:`Success`}import(e){if(Object.keys(e.borders||{}).length)for(let t of e.sheets)for(let[n,r]of yc(t.id,t.borders)){let{sheetId:t,col:i,row:a}=n,o=e.borders[r];this.setBorder(t,i,a,o,!1)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,un(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=_c(a,t),s={sheetId:n.id,col:r,row:i};e[o]??=[],e[o].push(s)}}n.borders=vc(e)}e.borders=t}exportForExcel(e){this.export(e)}},mW=class extends fW{static getters=[`getCarousel`,`doesCarouselExist`];carousels={};allowDispatch(e){switch(e.type){case`CREATE_CAROUSEL`:return this.getters.getFigure(e.sheetId,e.figureId)?`DuplicatedFigureId`:`Success`;case`UPDATE_CAROUSEL`:return this.carousels[e.sheetId]?.[e.figureId]?`Success`:`InvalidFigureId`}return`Success`}handle(e){switch(e.type){case`CREATE_CAROUSEL`:this.getters.getFigure(e.sheetId,e.figureId)||this.dispatch(`CREATE_FIGURE`,{...e,tag:`carousel`}),this.history.update(`carousels`,e.sheetId,e.figureId,e.definition);break;case`UPDATE_CAROUSEL`:this.removeDeletedCharts(e,this.getters.getCarousel(e.figureId).items),this.history.update(`carousels`,e.sheetId,e.figureId,e.definition);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`carousel`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.getCarousel(n.id);if(i){let t={width:n.width,height:n.height};this.dispatch(`CREATE_CAROUSEL`,{sheetId:e.sheetIdTo,figureId:r,offset:n.offset,col:n.col,row:n.row,size:t,definition:{items:i.items.map(t=>{if(t.type===`carouselDataView`)return{...t};let n=t.chartId.split(`??`).pop(),r=`${e.sheetIdTo}??${n}`;return{...t,chartId:r}})}})}}break}case`DELETE_FIGURE`:this.history.update(`carousels`,e.sheetId,e.figureId,void 0);break;case`DELETE_SHEET`:this.history.update(`carousels`,e.sheetId,void 0);break}}doesCarouselExist(e){for(let t in this.carousels)if(this.carousels[t]?.[e])return!0;return!1}getCarousel(e){for(let t in this.carousels)if(this.carousels[t]?.[e])return this.carousels[t][e];throw Error(`There is no carousel with the given figureId: ${e}`)}removeDeletedCharts(e,t){let n=new Set(e.definition.items.filter(e=>e.type===`chart`).map(e=>e.chartId));for(let r of t)r.type===`chart`&&!n.has(r.chartId)&&this.dispatch(`DELETE_CHART`,{chartId:r.chartId,sheetId:e.sheetId})}import(e){for(let t of e.sheets){let e=(t.figures||[]).filter(e=>e.tag===`carousel`);for(let n of e)this.history.update(`carousels`,t.id,n.id,{items:n.data.items,title:n.data.title})}}export(e){for(let t of e.sheets){let e=t.figures.filter(e=>e.tag===`carousel`);for(let n of e)this.carousels[t.id]?.[n.id]&&(n.data={...n.data,...this.carousels[t.id]?.[n.id]})}}},hW=class extends fW{static getters=[`zoneToXC`,`getCells`,`getTranslatedCellFormula`,`getCellById`,`getFormulaString`,`getFormulaMovedInSheet`];nextId=1;cells={};adaptRanges({applyChange:e},t,n){for(let r of Object.keys(this.cells))for(let i of Object.values(this.cells[r]||{}))if(i.isFormula){for(let a of i.compiledFormula.dependencies)if(a.sheetId===t||a.invalidSheetName===n.old){let t=e(a);t.changeType!==`NONE`&&this.history.update(`cells`,r,i.id,`compiledFormula`,`dependencies`,i.compiledFormula.dependencies.indexOf(a),t.range)}}}allowDispatch(e){switch(e.type){case`UPDATE_CELL`:return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessUpdateCell);case`CLEAR_CELL`:return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessClearCell);case`UPDATE_CELL_POSITION`:return!e.cellId||this.cells[e.sheetId]?.[e.cellId]?`Success`:`InvalidCellId`;default:return`Success`}}handle(e){switch(e.type){case`SET_FORMATTING`:`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.copyColumnFormat.bind(this)):this.handleAddColumnsRows(e,this.copyRowFormat.bind(this));break;case`UPDATE_CELL`:this.updateCell(e.sheetId,e.col,e.row,e);break;case`CLEAR_CELL`:this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col,row:e.row,content:``,format:``});break;case`CLEAR_CELLS`:this.clearCells(e.sheetId,e.target);break;case`DELETE_CONTENT`:this.clearZones(e.sheetId,e.target);break;case`DELETE_SHEET`:this.history.update(`cells`,e.sheetId,void 0)}}clearZones(e,t){for(let n of Qt(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++){let n=this.getters.getCell({sheetId:e,col:t,row:r});(n?.isFormula||n?.content)&&this.dispatch(`UPDATE_CELL`,{sheetId:e,content:``,col:t,row:r})}}setFormatter(e,t,n){for(let r of Qt(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 Qt(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,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:``,format:``})}handleAddColumnsRows(e,t){let n,r;e.position===`before`?(n=S(e.base,e.base+e.quantity),r=e.base+e.quantity):(n=S(e.base+1,e.base+e.quantity+1),r=e.base),t(e.sheetId,r,n)}import(e){for(let t of e.sheets){let n=t.id,r=new bF;for(let e in t.cells)if(t.cells[e]){let{col:n,row:i}=Zt(e),a={sheetId:t.id,col:n,row:i};r.set(a,{content:t.cells[e]})}for(let[e,n]of yc(t.id,t.formats)){let t=r.get(e);t?t.format=n:r.set(e,{format:n})}for(let i of r.keysForSheet(n)){let n=r.get(i);if(n?.content||n?.format){let r=this.importCell(t.id,n?.content,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={};for(let n of e.sheets){let e=[],r={},i=Object.keys(this.cells[n.id]||{}).map(e=>this.getters.getCellPosition(e)).sort((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col);for(let n of i){let i=this.getters.getCell(n),a=T(n.col,n.row);if(i.format){let r=_c(i.format,t);e[r]??=[],e[r].push(n)}i.content&&(r[a]=i.content)}n.formats=vc(e),n.cells=r}e.formats=t}importCell(e,t,n){let r=this.getNextUid();return this.createCell(r,t||``,n,e)}exportForExcel(e){this.export(e);let t=[];for(let n in e.formats||[])Cs(e.formats[n])||(t.push(Number(n)),delete e.formats[n]);if(t.length)for(let n of e.sheets)for(let e in n.formats){let r=n.formats[e];r&&t.includes(r)&&delete n.formats[e]}}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 pt(t.map(e=>e.value));let i=0;return pt(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(uU(r).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),t,n,e);return this.getFormulaString(e,r,i)}getFormulaMovedInSheet(e,t,n){let r=uU(n).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),i=this.getters.removeRangesSheetPrefix(t,r);return this.getFormulaString(t,n,i)}zoneToXC(e,t,n=[{colFixed:!1,rowFixed:!1}]){t=this.getters.expandZone(e,t);let r=T(t.left,t.top,n[0]),i=T(t.right,t.bottom,n.length>1?n[1]:n[0]),a=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),o=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),s=a.col===o.col&&a.row===o.row;return r!==i&&!s?r+`:`+i:r}copyColumnFormat(e,t,n){for(let r=0;r<this.getters.getNumberRows(e);r++){let i=this.getFormat(e,t,r);if(i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,...i})}}copyRowFormat(e,t,n){for(let r=0;r<this.getters.getNumberCols(e);r++){let i=this.getFormat(e,r,t);if(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.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?Tt(r?.content):i?.content||``,s=r.format===void 0?i&&i.format:r.format;if((a&&!o&&!r.formula||!a&&(!i||i.content===``))&&!s){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 c=i?.id||this.getNextUid(),l=this.createCell(c,o,s,e);this.history.update(`cells`,e,l.id,l),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:l.id,col:t,row:n,sheetId:e})}createCell(e,t,n,r){return t.startsWith(`=`)?this.createFormulaCell(e,t,n,r):this.createLiteralCell(e,t,n)}createLiteralCell(e,t,n){let r=this.getters.getLocale(),i=nc(t,r);return n||=typeof i==`number`?ss(t,r)||cs(t):void 0,!ws(n)&&!t.startsWith(`'`)&&!M(t)&&(t=P(i)),{id:e,content:t,format:n,isFormula:!1,parsedValue:i}}createFormulaCell(e,t,n,r){let i=lU(t);return i.dependencies.length?this.createFormulaCellWithDependencies(e,i,n,r):{id:e,content:t,format:n,isFormula:!0,compiledFormula:{...i,dependencies:[]}}}createFormulaCellWithDependencies(e,t,n,r){let i=[];for(let e of t.dependencies)i.push(this.getters.getRangeFromSheetXC(r,e));return new gW(e,t,n,i,r,this.getters.getRangeString)}checkCellOutOfSheet(e){let{sheetId:t,col:n,row:r}=e;return this.getters.tryGetSheet(t)?En(n,r,this.getters.getSheetZone(t))?`Success`:`TargetOutOfSheet`:`InvalidSheetId`}checkUselessClearCell(e){let t=this.getters.getCell(e),n=this.getters.getCellStyle(e);return!t||!t.content&&!n&&!t.format?`NoChanges`:`Success`}checkUselessUpdateCell(e){let t=this.getters.getCell(e),n=`content`in e||`formula`in e,r=`style`in e,i=r&&this.getters.getCellStyle(e),a=`format`in e;return(!n||t?.content===e.content)&&(!r||w(i,e.style))&&(!a||t?.format===e.format)?`NoChanges`:`Success`}},gW=class{id;format;sheetId;getRangeString;isFormula=!0;compiledFormula;constructor(e,t,n,r,i,a){this.id=e,this.format=n,this.sheetId=i,this.getRangeString=a;let o=0,s=t.tokens.map(e=>e.type===`REFERENCE`?new _W(r,o++,this.sheetId,this.getRangeString):e);this.compiledFormula={...t,dependencies:r,tokens:s}}get content(){return pt(this.compiledFormula.tokens.map(e=>e.value))}get contentWithFixedReferences(){let e=0;return pt(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}))}},_W=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)}},vW=class extends fW{static getters=[`isChartDefined`,`getChartDefinition`,`getChartType`,`getChartIds`,`getChart`,`getFigureIdFromChartId`,`getContextCreationChart`];charts={};createChart=m_(this.getters);validateChartDefinition=e=>g_(this,e.definition);adaptRanges(e){for(let[t,n]of Object.entries(this.charts)){if(!n)continue;let r=n.chart.updateRanges(e);this.history.update(`charts`,t,r?{figureId:n.figureId,chart:r}:void 0)}}allowDispatch(e){switch(e.type){case`CREATE_CHART`:return this.checkValidations(e,this.chainValidations(this.checkFigureArguments,this.validateChartDefinition,this.checkChartDuplicate));case`UPDATE_CHART`:return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartExists,this.checkChartChanged));case`DELETE_CHART`:return this.checkChartExists(e);default:return`Success`}}handle(e){switch(e.type){case`CREATE_CHART`:let{col:t,row:n,offset:r,size:i,sheetId:a,figureId:o}=e;!this.getters.getFigure(a,o)&&r!==void 0&&t!==void 0&&n!==void 0&&this.addFigure(o,a,t,n,r,i),this.addChart(e.figureId,e.chartId,e.definition);break;case`UPDATE_CHART`:this.addChart(e.figureId,e.chartId,e.definition);break;case`DUPLICATE_SHEET`:for(let t of this.getChartIds(e.sheetId)){let{chart:n,figureId:r}=this.charts[t]||{};if(!n||!r)continue;let i=this.getters.getFigure(e.sheetId,r);if(!i)continue;let a=r.split(`??`).pop(),o=`${e.sheetIdTo}??${a}`,s=t.split(`??`).pop(),c=`${e.sheetIdTo}??${s}`,l=n.duplicateInDuplicatedSheet(e.sheetIdTo);l&&this.dispatch(`CREATE_CHART`,{figureId:o,chartId:c,col:i.col,row:i.row,offset:i.offset,size:{width:i.width,height:i.height},definition:l.getDefinition(),sheetId:e.sheetIdTo})}break;case`DELETE_FIGURE`:for(let t in this.charts)this.charts[t]?.figureId===e.figureId&&this.dispatch(`DELETE_CHART`,{chartId:t,sheetId:e.sheetId});break;case`DELETE_CHART`:this.isChartDefined(e.chartId)&&this.history.update(`charts`,e.chartId,void 0);break;case`DELETE_SHEET`:for(let t of this.getChartIds(e.sheetId))this.history.update(`charts`,t,void 0);break}}getContextCreationChart(e){return this.charts[e]?.chart.getContextCreation()}getChart(e){return this.charts[e]?.chart}getFigureIdFromChartId(e){if(!this.charts[e])throw Error(`Chart with id ${e} does not exist.`);return this.charts[e].figureId}getChartType(e){let t=this.charts[e]?.chart.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?.chart.sheetId===e).map(([e])=>e)}getChartDefinition(e){let t=this.charts[e]?.chart.getDefinition();if(!t)throw Error(`There is no chart with the given id: ${e}`);return t}import(e){for(let t of e.sheets)if(t.figures){for(let e of t.figures)if(e.tag===`chart`){let n=e.data.chartId,r=this.createChart(e.id,e.data,t.id);this.charts[n]={chart:r,figureId:e.id}}else if(e.tag===`carousel`)for(let n in e.data.chartDefinitions||{}){let r=e.data.chartDefinitions[n],i=this.createChart(e.id,r,t.id);this.charts[n]={chart:i,figureId:e.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,r=Object.keys(this.charts).find(e=>this.charts[e]?.figureId===t.id);if(e&&e.tag===`chart`&&r){let t=this.charts[r]?.chart.getDefinition();t&&(e.data={...t,chartId:r},n.push(e))}else if(e&&e.tag===`carousel`){let r=Object.keys(this.charts).filter(e=>this.charts[e]?.figureId===t.id),i={};for(let e of r)i[e]=this.charts[e]?.chart.getDefinition();e.data={chartDefinitions:i},n.push(e)}else n.push(e)}t.figures=n}}addFigure(e,t,n,r,i,a={width:536,height:335}){this.dispatch(`CREATE_FIGURE`,{sheetId:t,figureId:e,col:n,row:r,offset:i,size:a,tag:`chart`})}addChart(e,t,n){let r=this.getters.getFigureSheetId(e);if(r){let i=this.createChart(e,n,r);this.history.update(`charts`,t,{figureId:e,chart:i})}}checkChartDuplicate(e){return this.isChartDefined(e.chartId)?`DuplicatedChartId`:`Success`}checkChartExists(e){return this.isChartDefined(e.chartId)?`Success`:`ChartDoesNotExist`}checkChartChanged(e){return e.figureId===this.charts[e.chartId]?.figureId&&w(this.getChartDefinition(e.chartId),e.definition)?`NoChanges`:`Success`}checkFigureArguments(e){return this.getters.getFigure(e.sheetId,e.figureId)||e.offset!==void 0&&e.col!==void 0&&e.row!==void 0?`Success`:`MissingFigureArguments`}};function yW(e){return e===``?NaN:Number(e)}var bW=class extends fW{static getters=[`getConditionalFormats`,`getRulesSelection`,`getRulesByCell`,`getAdaptedCfRanges`];cfRules={};adaptCFFormulas({applyChange:e,adaptFormulaString:t}){for(let n in this.cfRules)for(let r of this.cfRules[n])if(r.rule.type===`DataBarRule`&&r.rule.rangeValues){let t=e(r.rule.rangeValues);switch(t.changeType){case`REMOVE`:this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`rangeValues`,void 0);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`rangeValues`,t.range);break}}else if(r.rule.type===`CellIsRule`)for(let e=0;e<r.rule.values.length;e++)this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`values`,e,t(n,r.rule.values[e]));else if(r.rule.type===`IconSetRule`)for(let e of[`lowerInflectionPoint`,`upperInflectionPoint`])r.rule[e].type===`formula`&&this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,e,`value`,t(n,r.rule[e].value));else if(r.rule.type===`ColorScaleRule`)for(let e of[`minimum`,`maximum`,`midpoint`]){let i=r.rule[e];i?.type===`formula`&&i?.value&&this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,e,`value`,t(n,i.value))}}adaptCFRanges(e,{applyChange:t}){for(let n of this.cfRules[e])for(let r of n.ranges){let i=t(r);switch(i.changeType){case`REMOVE`:let t=n.ranges.slice();t.splice(n.ranges.indexOf(r),1),t.length>=1?this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,t):this.removeConditionalFormatting(n.id,e);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,n.ranges.indexOf(r),i.range);break}}}adaptRanges(e,t){let n=t?[t]:Object.keys(this.cfRules);for(let t of n)this.adaptCFRanges(t,e);this.adaptCFFormulas(e)}allowDispatch(e){switch(e.type){case`ADD_CONDITIONAL_FORMAT`:return e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkValidations(e,this.checkCFRule,this.checkEmptyRange,this.checkCFHasChanged);case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:return this.checkValidPriorityChange(e.cfId,e.delta,e.sheetId)}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.cfRules[e.sheetId]=[];break;case`DUPLICATE_SHEET`:this.history.update(`cfRules`,e.sheetIdTo,[]);for(let t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case`DELETE_SHEET`:let t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update(`cfRules`,t);break;case`ADD_CONDITIONAL_FORMAT`:let n={...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))};this.addConditionalFormatting(n,e.sheetId);break;case`REMOVE_CONDITIONAL_FORMAT`:this.removeConditionalFormatting(e.id,e.sheetId);break;case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:this.changeCFPriority(e.cfId,e.delta,e.sheetId);break}}import(e){for(let t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map(e=>this.mapToConditionalFormatInternal(t.id,e))}export(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e)))}exportForExcel(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e,{useBoundedReference:!0})))}getConditionalFormats(e){return this.cfRules[e]?.map(t=>this.mapToConditionalFormat(e,t))||[]}getRulesSelection(e,t){let n=new Set;return t.forEach(t=>{this.getRulesByZone(e,t).forEach(e=>{n.add(e)})}),Array.from(n)}getRulesByZone(e,t){let n=new Set;for(let r=t.top;r<=t.bottom;r++)for(let i=t.left;i<=t.right;i++)this.getRulesByCell(e,i,r).forEach(e=>{n.add(e.id)});return n}getRulesByCell(e,t,n){let r=[];for(let i of this.cfRules[e])for(let e of i.ranges)En(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(ln));let s=Qt(o,r);return Qt([...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 Nm.has(t.operator)?this.checkValidations(t,this.checkOperatorArgsNumber,this.checkCFValues):`InvalidConditionalFormatType`;case`ColorScaleRule`:return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case`IconSetRule`:return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)));case`DataBarRule`:return`Success`}return`InvalidConditionalFormatType`}checkCFHasChanged(e){let t=this.mapToConditionalFormatInternal(e.sheetId,{...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))}),n=this.cfRules[e.sheetId]?.find(t=>t.id===e.cf.id);return n&&w(t,n)?`NoChanges`:`Success`}checkOperatorArgsNumber(e){let t=W.get(e.operator).numberOfValues({type:e.operator,values:e.values});if(t===void 0||t>2)throw Error(`Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.`);let n=[],r=e=>e===void 0||e===``;return t>=1&&r(e.values[0])&&n.push(`FirstArgMissing`),t>=2&&r(e.values[1])&&n.push(`SecondArgMissing`),n.length?n:`Success`}checkNaN(e,t){if([`number`,`percentage`,`percentile`].includes(e.type)&&(e.value===``||isNaN(e.value)))switch(t){case`min`:return`MinNaN`;case`max`:return`MaxNaN`;case`mid`:return`MidNaN`;case`upperInflectionPoint`:return`ValueUpperInflectionNaN`;case`lowerInflectionPoint`:return`ValueLowerInflectionNaN`}return`Success`}checkFormulaCompilation(e,t){if(e.type!==`formula`)return`Success`;if(lU(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&&yW(t)>=yW(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&&yW(t)>=yW(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&&yW(t)>=yW(n)?`MinBiggerThanMid`:`Success`}checkCFValues(e){for(let t of e.values)if(t.startsWith(`=`)&&lU(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)}},xW=class extends fW{static getters=[`cellHasListDataValidationIcon`,`getDataValidationRule`,`getDataValidationRules`,`getValidationRuleForCell`];rules={};adaptRanges(e,t){this.adaptDVRanges(t,e),this.adaptDVFormulas(e)}adaptDVFormulas({adaptFormulaString:e}){for(let t in this.rules){let n=this.rules[t];for(let r=n.length-1;r>=0;r--){let n=this.rules[t][r];for(let i=0;i<n.criterion.values.length;i++){let a=e(t,n.criterion.values[i]);this.history.update(`rules`,t,r,`criterion`,`values`,i,a)}}}}adaptDVRanges(e,{applyChange:t}){let n=this.rules[e];for(let r=n.length-1;r>=0;r--){let n=this.rules[e][r];for(let i=n.ranges.length-1;i>=0;i--){let a=n.ranges[i],o=t(a);switch(o.changeType){case`REMOVE`:if(n.ranges.length===1)this.removeDataValidationRule(e,n.id);else{let t=n.ranges.slice();t.splice(i,1),this.history.update(`rules`,e,r,`ranges`,t)}break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`rules`,e,r,`ranges`,i,o.range);break}}}}allowDispatch(e){switch(e.type){case`ADD_DATA_VALIDATION_RULE`:return!this.getters.tryGetSheet(e.sheetId)||e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkValidations(e,this.chainValidations(this.checkEmptyRange,this.checkValidRange,this.checkCriterionTypeIsValid,this.checkCriterionHasValidNumberOfValues,this.checkCriterionValuesAreValid));case`REMOVE_DATA_VALIDATION_RULE`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;if(!this.rules[e.sheetId].find(t=>t.id===e.id))return`UnknownDataValidationRule`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`rules`,e.sheetId,[]);break;case`DUPLICATE_SHEET`:{let t=b(this.rules[e.sheetId]).map(t=>({...t,ranges:t.ranges.map(t=>Xc(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=Qt(e.target),n=e.sheetId;for(let e of t)for(let t=e.top;t<=e.bottom;t++)for(let r=e.left;r<=e.right;r++){let e=this.getValidationRuleForCell({sheetId:n,col:r,row:t});if(e&&(e.criterion.type===`isBoolean`||e.criterion.type===`isValueInList`&&!this.getters.getCell({sheetId:n,col:r,row:t})?.content)){let e=this.rules[n],i=[this.getters.getRangeFromSheetXC(n,T(r,t))],a=this.removeRangesFromRules(n,i,e);this.history.update(`rules`,n,a)}}}}}getDataValidationRules(e){return this.rules[e]}getDataValidationRule(e,t){return this.rules[e].find(e=>e.id===t)}getValidationRuleForCell({sheetId:e,col:t,row:n}){if(this.rules[e]){for(let r of this.rules[e])for(let e of r.ranges)if(En(t,n,e.zone))return r}}cellHasListDataValidationIcon(e){let t=this.getValidationRuleForCell(e);return t?(t.criterion.type===`isValueInList`||t.criterion.type===`isValueInRange`)&&(t.criterion.displayStyle===`arrow`||t.criterion.displayStyle===`chip`):!1}addDataValidationRule(e,t){let n=this.rules[e];t.criterion.type===`isBoolean`?this.setCenterStyleToBooleanCells(t):t.criterion.type===`isValueInList`&&(t.criterion.values=Array.from(new Set(t.criterion.values)));let r=this.removeRangesFromRules(e,t.ranges,n,t.id),i=r.findIndex(e=>e.id===t.id);i===-1?this.history.update(`rules`,e,[...r,t]):(r[i]=t,this.history.update(`rules`,e,r))}removeRangesFromRules(e,t,n,r){n=b(n);for(let e of n)e.id!==r&&(e.ranges=this.getters.recomputeRanges(e.ranges,t));return n.filter(e=>e.ranges.length>0)}removeDataValidationRule(e,t){let n=this.rules[e].filter(e=>e.id!==t);this.history.update(`rules`,e,n)}setCenterStyleToBooleanCells(e){for(let t of Qc(e.ranges)){let e=this.getters.getCellStyle(t),n={...e,align:e?.align??`center`,verticalAlign:e?.verticalAlign??`middle`};this.dispatch(`UPDATE_CELL`,{...t,style:n})}}checkEmptyRange(e){return e.ranges.length?`Success`:`EmptyRange`}import(e){for(let t of e.sheets)if(this.rules[t.id]=[],t.dataValidationRules)for(let e of t.dataValidationRules)this.rules[t.id].push({...e,ranges:e.ranges.map(e=>this.getters.getRangeFromSheetXC(t.id,e))})}export(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id])t.dataValidationRules.push({...e,ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id))})}}exportForExcel(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id]){let n={...b(e),ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id,{useBoundedReference:!0}))};e.criterion.type===`isValueInRange`&&(n.criterion.values=e.criterion.values.map(e=>{let n=this.getters.getRangeFromSheetXC(t.id,e);return this.getters.getRangeString(n,t.id,{useBoundedReference:!0,useFixedReference:!0})})),t.dataValidationRules.push(n)}}}checkCriterionTypeIsValid(e){return W.contains(e.rule.criterion.type)?`Success`:`UnknownDataValidationCriterionType`}checkCriterionHasValidNumberOfValues(e){let t=e.rule.criterion,n=W.get(t.type).numberOfValues(t);return n!==void 0&&t.values.length!==n?`InvalidNumberOfCriterionValues`:`Success`}checkCriterionValuesAreValid(e){let t=e.rule.criterion,n=W.get(t.type);return t.values.some(e=>n.allowedValues===`onlyFormulas`&&!e.startsWith(`=`)?!0:e.startsWith(`=`)?n.allowedValues===`onlyLiterals`||lU(e).isBadExpression:!n.isCriterionValueValid(e))?`InvalidDataValidationCriterionValue`:`Success`}checkValidRange(e){return e.ranges.map(e=>this.getters.getRangeFromRangeData(e)).map(t=>this.getters.getRangeString(t,e.sheetId)).some(e=>!this.getters.isRangeValid(e))?`InvalidRange`:`Success`}},SW=class extends fW{static getters=[`getFigures`,`getFigure`,`getFigureSheetId`];figures={};insertionOrders=[];adaptRanges({applyChange:e},t){for(let n of this.getFigures(t)){let r=e(this.getters.getRangeFromZone(t,{left:n.col,right:n.col,top:n.row,bottom:n.row}));if(r.changeType===`MOVE`)this.history.update(`figures`,t,n.id,`col`,r.range.zone.right),this.history.update(`figures`,t,n.id,`row`,r.range.zone.bottom);else if(r.changeType===`REMOVE`){let r=e(this.getters.getRangeFromZone(t,{left:0,right:n.col-1,top:0,bottom:n.row-1})),{offset:i,col:a,row:o}=n;r.changeType!==`NONE`&&(a=r.range.zone.right+1,o=r.range.zone.bottom+1),{offset:i,col:a,row:o}=this.getPositionInSheet(t,{...n,col:a,row:o}),this.history.update(`figures`,t,n.id,`offset`,i),this.history.update(`figures`,t,n.id,`col`,a),this.history.update(`figures`,t,n.id,`row`,o)}}}allowDispatch(e){switch(e.type){case`CREATE_FIGURE`:return this.checkValidations(e,this.checkFigureDuplicate,this.checkFigureAnchorOffset);case`UPDATE_FIGURE`:return this.checkValidations(e,this.checkFigureExists,this.checkFigureAnchorOffset);case`DELETE_FIGURE`:return this.checkFigureExists(e);default:return`Success`}}beforeHandle(e){switch(e.type){case`DELETE_SHEET`:this.getters.getFigures(e.sheetId).forEach(t=>{this.dispatch(`DELETE_FIGURE`,{figureId:t.id,sheetId:e.sheetId})});break}}handle(e){switch(e.type){case`CREATE_SHEET`:this.figures[e.sheetId]={};break;case`DELETE_SHEET`:this.deleteSheet(e.sheetId);break;case`CREATE_FIGURE`:let t={id:e.figureId,col:e.col,row:e.row,offset:e.offset,width:e.size.width,height:e.size.height,tag:e.tag};this.addFigure(t,e.sheetId);break;case`UPDATE_FIGURE`:this.updateFigure(e);break;case`DELETE_FIGURE`:this.removeFigure(e.figureId,e.sheetId);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.onColRemove(e.sheetId):this.onRowRemove(e.sheetId);break;case`DUPLICATE_SHEET`:for(let t of this.getFigures(e.sheetId)){let n=t.id,r=this.figures[e.sheetId]?.[n];if(!r)continue;let i=n.split(`??`).pop(),a=`${e.sheetIdTo}??${i}`;this.dispatch(`CREATE_FIGURE`,{figureId:a,...r,size:{width:r.width,height:r.height},sheetId:e.sheetIdTo})}break}}onColRemove(e){let t=this.getters.getNumberCols(e),n=Array(t+1);n[t]=0;for(let r=t-1;r>=0;r--)n[r]=n[r+1]+this.getters.getColSize(e,r);for(let t of this.getFigures(e))if(t.offset.x+t.width>n[t.col]){let r=t.offset.x,i=t.col;for(r=Math.min(r,n[i]-t.width);r<0&&i>0;)i--,r=n[i]-t.width;r!==t.offset.x&&this.history.update(`figures`,e,t.id,`offset`,{x:Math.max(r,0),y:t.offset.y}),i!==t.col&&this.history.update(`figures`,e,t.id,`col`,i)}}onRowRemove(e){let t=this.getters.getNumberRows(e),n=Array(t+1);n[t]=0;for(let r=t-1;r>=0;r--)n[r]=n[r+1]+(this.getters.getUserRowSize(e,r)??23);for(let t of this.getFigures(e))if(t.offset.y+t.height>n[t.row]){let r=t.offset.y,i=t.row;for(let t=this.getters.getUserRowSize(e,i)??23;t<r;t=this.getters.getUserRowSize(e,i)??23)i+=1,r-=t;for(r=Math.min(r,n[i]-t.height);r<0&&i>0;)i--,r=n[i]-t.height;r!==t.offset.y&&this.history.update(`figures`,e,t.id,`offset`,{x:t.offset.x,y:Math.max(0,r)}),i!==t.row&&this.history.update(`figures`,e,t.id,`row`,i)}else t.offset.y+t.height>n[0]&&this.history.update(`figures`,e,t.id,`offset`,{x:t.offset.x,y:Math.max(n[0]-t.height,0)})}getPositionInSheet(e,t){let{numberOfRows:n,numberOfCols:r}=this.getters.getSheetSize(e),i=0,a=0,o,s,{col:c,row:l}=t,u={...t.offset};for(o=n;i<t.height&&o>0;o--)i+=this.getters.getUserRowSize(e,o-1)??23;for(l>o?(l=o,u.y=Math.max(i-t.height,0)):l===o&&(u.y=x(u.y,0,Math.max(i-t.height,0))),s=r;a<t.width&&s>0;s--)a+=this.getters.getColSize(e,s-1);return c>s?(c=s,u.x=Math.max(a-t.width,0)):s===c&&(u.x=x(u.x,0,Math.max(a-t.width,0))),{col:c,row:l,offset:u}}updateFigure(e){if(!(`figureId`in e)||!(`sheetId`in e))return;let{figureId:t,sheetId:n,...r}=e,i={...this.getFigure(n,t),...r};for(let[e,t]of Object.entries(r))switch(e){case`tag`:this.history.update(`figures`,n,i.id,e,t);break;case`offset`:this.history.update(`figures`,n,i.id,e,t);break;case`col`:case`row`:case`width`:case`height`:t!==void 0&&this.history.update(`figures`,n,i.id,e,t);break}}addFigure(e,t){this.history.update(`figures`,t,e.id,e),this.history.update(`insertionOrders`,this.insertionOrders.length,e.id)}deleteSheet(e){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>!this.figures[e]?.[t])),this.history.update(`figures`,e,void 0)}removeFigure(e,t){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>t!==e)),this.history.update(`figures`,t,e,void 0)}checkFigureExists(e){return this.figures[e.sheetId]?.[e.figureId]===void 0?`FigureDoesNotExist`:`Success`}checkFigureDuplicate(e){return Object.values(this.figures).find(t=>t?.[e.figureId])?`DuplicatedFigureId`:`Success`}checkFigureAnchorOffset(e){return e.col<0||e.row<0||e.offset&&(e.offset.x<0||e.offset.y<0)?`WrongSheetPosition`:`Success`}getFigures(e){let t=[];for(let n of this.insertionOrders){let r=this.figures[e]?.[n];r&&t.push(r)}return t}getFigure(e,t){return this.figures[e]?.[t]}getFigureSheetId(e){return Object.keys(this.figures).find(t=>this.figures[t]?.[e]!==void 0)}import(e){for(let t of e.sheets)for(let e of t.figures)this.addFigure(e,t.id)}export(e){for(let t of e.sheets)for(let e of this.getFigures(t.id))t.figures.push({...e,data:void 0})}exportForExcel(e){return this.export(e)}},CW=class extends fW{static getters=[`getHeaderGroups`,`getGroupsLayers`,`getVisibleGroupLayers`,`getHeaderGroup`,`getHeaderGroupsInZone`,`isGroupFolded`,`isRowFolded`,`isColFolded`];groups={};allowDispatch(e){switch(e.type){case`GROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;if(this.findGroupWithStartEnd(e.sheetId,e.dimension,t,n))return`HeaderGroupAlreadyExists`;break}case`UNGROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;break}case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUP`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);if(!t)return`UnknownHeaderGroup`;if(S(0,this.getters.getNumberHeaders(e.sheetId,e.dimension)).every(n=>n>=t.start&&n<=t.end||this.getters.isHeaderHiddenByUser(e.sheetId,e.dimension,n)))return`NotEnoughElements`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`groups`,e.sheetId,{ROW:[],COL:[]});break;case`GROUP_HEADERS`:this.groupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`UNGROUP_HEADERS`:this.unGroupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`DUPLICATE_SHEET`:{let t=b(this.groups[e.sheetId]);this.history.update(`groups`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.groups};delete t[e.sheetId],this.history.update(`groups`,t);break}case`ADD_COLUMNS_ROWS`:let t=gt(e.position,e.base);this.moveGroupsOnHeaderInsertion(e.sheetId,e.dimension,t,e.quantity);break;case`REMOVE_COLUMNS_ROWS`:this.moveGroupsOnHeaderDeletion(e.sheetId,e.dimension,e.elements);break;case`UNFOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.unfoldHeaderGroup(e.sheetId,e.dimension,t);break}case`FOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.foldHeaderGroup(e.sheetId,e.dimension,t);break}case`UNFOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.unfoldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.foldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:{let t=e.type===`UNFOLD_HEADER_GROUPS_IN_ZONE`?`unfold`:`fold`,n=this.getGroupsLayers(e.sheetId,e.dimension);t===`fold`&&n.reverse();let r=n.flat(),i=e.dimension===`ROW`?e.zone.top:e.zone.left,a=e.dimension===`ROW`?e.zone.bottom:e.zone.right,o=new Set;for(let e=i;e<=a;e++){let n=r.filter(t=>t.start-1<=e&&e<=t.end);for(let e of n)if(!(t===`fold`&&e.isFolded||t===`unfold`&&!e.isFolded)){o.add(e);break}}for(let n of o)t===`unfold`?this.unfoldHeaderGroup(e.sheetId,e.dimension,n):this.foldHeaderGroup(e.sheetId,e.dimension,n);break}}}getHeaderGroups(e,t){return this.groups[e][t]}getHeaderGroup(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}getHeaderGroupsInZone(e,t,n){return this.getHeaderGroups(e,t).filter(e=>{let r=t===`ROW`?n.top:n.left,i=t===`ROW`?n.bottom:n.right;return this.doGroupOverlap(e,r,i)})}getGroupsLayers(e,t){let n=this.getHeaderGroups(e,t);return this.bricksFallingAlgorithm(n,0,0)}getVisibleGroupLayers(e,t){let n=this.getGroupsLayers(e,t);for(let r of n)for(let n=r.length-1;n>=0;n--){let i=r[n];i.start!==0&&S(i.start-1,i.end+1).every(n=>this.getters.isHeaderHiddenByUser(e,t,n))&&r.splice(n,1)}return n.filter(e=>e.length>0)}isGroupFolded(e,t,n,r){return this.getHeaderGroup(e,t,n,r)?.isFolded||!1}isRowFolded(e,t){return this.getters.getHeaderGroups(e,`ROW`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}isColFolded(e,t){return this.getters.getHeaderGroups(e,`COL`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}getGroupId(e){return`${e.start}-${e.end}}`}bricksFallingAlgorithm(e,t,n,r=0){let i={};for(let t of e)i[this.getGroupId(t)]=t.isFolded;let a={};for(let t of e)for(let e=t.start;e<=t.end;e++)a[e]=a[e]?a[e]+1:1;for(let e=t;e<=n;e++)a[e]=a[e]?a[e]+r:r;let o=Math.max(...Object.values(a),0),s=Array.from({length:o},()=>[]),c=Math.max(n,...e.map(e=>e.end)),l=Math.min(t,...e.map(e=>e.start));for(let e=l;e<=c;e++){let t=a[e]||0;for(let n=0;n<t;n++){let t=s[n].at(-1);if(t&&Et([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]=ml(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=hl(n,S(e.start,e.end+1));t.length!==0&&i.push({...e,start:Math.min(...t),end:Math.max(...t)})}this.history.update(`groups`,e,t,this.bricksFallingAlgorithm(i,0,0).flat())}doGroupOverlap(e,t,n){return e.start<=n&&e.end>=t}removeDuplicateGroups(e){let t={};for(let n of e)t[this.getGroupId(n)]=n;return Object.values(t)}findGroupWithStartEnd(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}foldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!0);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end<=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!0)}}unfoldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!1);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end>=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!1)}}getGroupIndex(e,t,n,r){let i=this.groups[e][t].findIndex(e=>e.start===n&&e.end===r);return i===-1?void 0:i}import(e){for(let t of e.sheets)if(this.groups[t.id]={ROW:[],COL:[]},t.headerGroups)for(let e of[`ROW`,`COL`])for(let n of t.headerGroups[e]||[])this.groups[t.id][e].push({...n})}export(e){for(let t of e.sheets)t.headerGroups=this.groups[t.id]}exportForExcel(e){for(let t of e.sheets)for(let e of[`ROW`,`COL`]){let n=this.getGroupsLayers(t.id,e);for(let r=0;r<n.length;r++){let i=n[r];for(let n of i){for(let i=n.start;i<=n.end;i++){let a=hj(t,e,i);a.outlineLevel=r+1,n.isFolded&&(a.isHidden=!0)}if(n.isFolded){let r=hj(t,e,n.end+1);r.collapsed=!0}}}}}},wW=class extends fW{static getters=[`getUserRowSize`,`getColSize`];sizes={};handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`sizes`,e.sheetId,{COL:Array(this.getters.getNumberCols(e.sheetId)).fill(void 0),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(void 0)});break;case`DUPLICATE_SHEET`:this.history.update(`sizes`,e.sheetIdTo,b(this.sizes[e.sheetId]));break;case`DELETE_SHEET`:let t={...this.sizes};delete t[e.sheetId],this.history.update(`sizes`,t);break;case`REMOVE_COLUMNS_ROWS`:{let t=this.sizes[e.sheetId][e.dimension],n=Ot(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=gt(e.position,e.base),r=t[e.base],i=kt(t,Array(e.quantity).fill(r),n);this.history.update(`sizes`,e.sheetId,e.dimension,i);break}case`RESIZE_COLUMNS_ROWS`:if(e.dimension===`ROW`)for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);else for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);break}}getColSize(e,t){return Math.round(this.sizes[e]?.COL[t]||96)}getUserRowSize(e,t){let n=this.sizes[e]?.ROW[t];return n?Math.round(n):void 0}import(e){for(let t of e.sheets){let e={COL:Array(t.colNumber).fill(void 0),ROW:Array(t.rowNumber).fill(void 0)};for(let[n,r]of Object.entries(t.rows))r.size&&(e.ROW[n]=r.size);for(let[n,r]of Object.entries(t.cols))r.size&&(e.COL[n]=r.size);this.sizes[t.id]=e}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e of S(0,this.getters.getNumberRows(n.id)))(t||this.sizes[n.id].ROW[e])&&(n.rows[e]={...n.rows[e],size:this.getUserRowSize(n.id,e)??23});n.cols===void 0&&(n.cols={});for(let e of S(0,this.getters.getNumberCols(n.id)))(t||this.sizes[n.id].COL[e])&&(n.cols[e]={...n.cols[e],size:this.getColSize(n.id,e)})}}},TW=class extends fW{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`:Ft(e.elements)<0||Pt(e.elements)>n?`InvalidHeaderIndex`:`Success`}case`REMOVE_COLUMNS_ROWS`:return this.getters.tryGetSheet(e.sheetId)?this.checkElementsIncludeAllVisibleHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`:`InvalidSheetId`}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:let t={COL:Array(this.getters.getNumberCols(e.sheetId)).fill(!1),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(!1)};this.history.update(`hiddenHeaders`,e.sheetId,t);break;case`DUPLICATE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetIdTo,b(this.hiddenHeaders[e.sheetId]));break;case`DELETE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetId,void 0);break;case`REMOVE_COLUMNS_ROWS`:{let t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(let n of[...e.elements].sort((e,t)=>t-e))t.splice(n,1);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t);break}case`ADD_COLUMNS_ROWS`:{let t=gt(e.position,e.base),n=kt([...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 yt(n,this.getAllVisibleHeaders(e,t))}isHeaderHiddenByUser(e,t,n){return t===`COL`?this.isColHiddenByUser(e,n):this.isRowHiddenByUser(e,n)}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]||this.getters.isRowFolded(e,t)}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]||this.getters.isColFolded(e,t)}getHiddenColsGroups(e){let t=[[]],n=this.hiddenHeaders[e].COL;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getHiddenRowsGroups(e){let t=[[]],n=this.hiddenHeaders[e].ROW;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getAllVisibleHeaders(e,t){let n=S(0,this.getters.getNumberHeaders(e,t)),r=[];return this.getters.getHeaderGroups(e,t).forEach(e=>{e.isFolded&&r.push(...S(e.start,e.end+1))}),n.filter(n=>!this.hiddenHeaders[e][t][n]&&!r.includes(n))}import(e){for(let t of e.sheets){this.hiddenHeaders[t.id]={COL:[],ROW:[]};for(let e=0;e<t.rowNumber;e++)this.hiddenHeaders[t.id].ROW[e]=!!t.rows[e]?.isHidden;for(let e=0;e<t.colNumber;e++)this.hiddenHeaders[t.id].COL[e]=!!t.cols[e]?.isHidden}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e=0;e<this.getters.getNumberRows(n.id);e++)(t||this.hiddenHeaders[n.id].ROW[e])&&(n.rows[e]===void 0&&(n.rows[e]={}),n.rows[e].isHidden||=this.hiddenHeaders[n.id].ROW[e]);n.cols===void 0&&(n.cols={});for(let e=0;e<this.getters.getNumberCols(n.id);e++)(t||this.hiddenHeaders[n.id].COL[e])&&(n.cols[e]===void 0&&(n.cols[e]={}),n.cols[e].isHidden||=this.hiddenHeaders[n.id].COL[e])}}},EW=class extends fW{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.getters.getFigure(e.sheetId,e.figureId)||this.addFigure(e.figureId,e.sheetId,e.col,e.row,e.offset,e.size),this.history.update(`images`,e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`image`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.getImage(n.id);if(i){let t={width:n.width,height:n.height};this.dispatch(`CREATE_IMAGE`,{sheetId:e.sheetIdTo,figureId:r,offset:n.offset,col:n.col,row:n.row,size:t,definition:b(i)})}}break}case`DELETE_FIGURE`:this.history.update(`images`,e.sheetId,e.figureId,void 0);break;case`DELETE_SHEET`:this.history.update(`images`,e.sheetId,void 0);break}}getImage(e){for(let t of Object.values(this.images))if(t&&t[e])return t[e];throw Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addFigure(e,t,n,r,i,a){this.dispatch(`CREATE_FIGURE`,{sheetId:t,figureId:e,col:n,row:r,offset:i,size:a,tag:`image`})}import(e){for(let t of e.sheets){let e=(t.figures||[]).filter(e=>e.tag===`image`);for(let n of e)this.history.update(`images`,t.id,n.id,n.data),this.syncedImages.add(n.data.path)}}export(e){for(let t of e.sheets){let e=t.figures.filter(e=>e.tag===`image`);for(let n of e)n.data=this.images[t.id]?.[n.id]}}exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let t of e)if(t?.tag===`image`){let e=this.getImage(t.id);e&&n.push({...t,data:b(e)})}t.images=[...t.images,...n]}}},DW=class extends fW{static getters=[`isInMerge`,`isInSameMerge`,`isMergeHidden`,`getMainCellPosition`,`expandZone`,`doesIntersectMerge`,`doesColumnsHaveCommonMerges`,`doesRowsHaveCommonMerges`,`getMerges`,`getMerge`,`getMergesInZone`,`isSingleCellOrMerge`,`getSelectionRangeString`,`isMainCellPosition`];nextId=1;merges={};mergeCellMap={};allowDispatch(e){let t=`force`in e?!!e.force:!1;switch(e.type){case`ADD_MERGE`:return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case`UPDATE_CELL`:return this.checkMergedContentUpdate(e);case`REMOVE_MERGE`:return this.checkMergeExists(e);default:return`Success`}}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DELETE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DUPLICATE_SHEET`:let t=this.merges[e.sheetId];if(!t)break;for(let n of Object.values(t).filter(C))this.addMerge(e.sheetIdTo,n.zone);break;case`ADD_MERGE`:for(let t of e.target)this.addMerge(e.sheetId,t);break;case`REMOVE_MERGE`:for(let t of e.target)this.removeMerge(e.sheetId,t);break}}adaptRanges(e,t){this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map(t=>this.getMergeById(e,parseInt(t,10))).filter(C)}getMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e],i=r?t in r&&r[t]?.[n]:void 0;return i?this.getMergeById(e,i):void 0}getMergesInZone(e,t){let n=this.mergeCellMap[e];if(!n)return[];let r=new Set;for(let e=t.left;e<=t.right;e++)for(let i=t.top;i<=t.bottom;i++){let t=n[e]?.[i];t&&r.add(t)}return Array.from(r).map(t=>this.getMergeById(e,t)).filter(C)}getSelectionRangeString(e,t){let n=this.getters.expandZone(e.sheetId,e.zone),r=Wc({...e,zone:{...n,bottom:qc(e)?void 0:n.bottom,right:Jc(e)?void 0:n.right}},this.getters.getSheetSize),i=this.getters.getRangeString(r,t);if(this.isSingleCellOrMerge(e.sheetId,e.zone)){let{sheetName:e,xc:t}=Pc(i);return Fc(e,t.split(`:`)[0])}return i}doesIntersectMerge(e,t){for(let n of this.getMerges(e))if(wn(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&&wn(n,o)&&(o=bn(n,o))}return Cn(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:Cn(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 Cn(t,n);let{numberOfCols:r,numberOfRows:i}=On(t);return r===1&&i===1}isMainCellPosition(e){return w(this.getMainCellPosition(e),e)}isMergeDestructive(e,t){let{left:n,right:r,top:i,bottom:a}=t;r=x(r,0,this.getters.getNumberCols(e)-1),a=x(a,0,this.getters.getNumberRows(e)-1);for(let t=i;t<=a;t++)for(let a=n;a<=r;a++)if(a!==n||t!==i){let n=this.getters.getCell({sheetId:e,col:a,row:t});if(n&&n.content!==``)return!0}return!1}getMergeById(e,t){let n=this.merges[e]?.[t];return n===void 0?void 0:kW(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&&wn(t,n))return`MergeOverlap`;return`Success`}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return`Success`;let{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(e);return Un(t,n,r)?`FrozenPaneOverlap`:`Success`}checkMergedContentUpdate(e){let{col:t,row:n,content:r}=e;if(r===void 0)return`Success`;let{col:i,row:a}=this.getMainCellPosition(e);return i===t&&a===n?`Success`:`CellIsMerged`}checkMergeExists(e){let{sheetId:t,target:n}=e;for(let e of n){let{left:n,top:r}=e,i=this.getMerge({sheetId:t,col:n,row:r});if(i===void 0||!Cn(e,i))return`InvalidTarget`}return`Success`}addMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t;if(r=x(r,0,this.getters.getNumberCols(e)-1),a=x(a,0,this.getters.getNumberRows(e)-1),T(n,i)===T(r,a))return;let o=this.nextId++;this.history.update(`merges`,e,o,this.getters.getRangeFromSheetXC(e,hn({left:n,top:i,right:r,bottom:a})));let s=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,content:``});let r=this.getMerge({sheetId:e,col:a,row:t});r&&s.add(r.id),this.history.update(`mergeCellMap`,e,a,t,o)}for(let t of s){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!==o)&&(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||!Cn(t,o))){this.history.update(`merges`,e,o.id,void 0);for(let t=r;t<=i;t++)for(let r=n;r<=a;r++)this.history.update(`mergeCellMap`,e,r,t,void 0)}}applyRangeChangeOnSheet(e,{applyChange:t}){let n=Object.entries(this.merges[e]||{});for(let[r,i]of n)if(i){let n=i.zone,a=t(i);switch(a.changeType){case`NONE`:break;case`REMOVE`:this.removeMerge(e,n);break;default:let{numberOfCols:t,numberOfRows:i}=On(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 jn(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,un(n))}export(e){for(let t of e.sheets){let e=this.merges[t.id];e&&t.merges.push(...OW(e))}}exportForExcel(e){this.export(e)}};function OW(e){return Object.entries(e).map(([e,t])=>t?kW(parseInt(e,10),t):void 0).filter(C).map(e=>T(e.left,e.top)+`:`+T(e.right,e.bottom))}function kW(e,t){return{...t.zone,id:e}}var AW=class extends fW{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 e.pivotId in this.pivots?`PivotIdTaken`:this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid);case`UPDATE_PIVOT`:return e.pivotId in this.pivots?w(e.pivot,this.pivots[e.pivotId]?.definition)?`NoChanges`:e.pivot.name===``?`EmptyName`:this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid):`PivotIdNotFound`;case`RENAME_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;if(e.name===``)return`EmptyName`;break;case`REMOVE_PIVOT`:case`DUPLICATE_PIVOT`:case`INSERT_PIVOT`: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 zL(s,c,l,u||{}),f=this.getPivotFormulaId(i);this.insertPivot(o,f,d);break}case`RENAME_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,`name`,e.name);break;case`REMOVE_PIVOT`:{let t={...this.pivots};delete t[e.pivotId];let n=this.getPivotFormulaId(e.pivotId);this.history.update(`formulaIds`,n,void 0),this.history.update(`pivots`,t);break}case`DUPLICATE_PIVOT`:{let{pivotId:t,newPivotId:n}=e,r=b(this.getPivotCore(t).definition);r.name=e.duplicatedPivotName??r.name+` (copy)`,this.addPivot(n,r);break}case`UPDATE_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,b(e.pivot)),this.compileCalculatedMeasures(e.pivotId,e.pivot.measures);break}}adaptRanges({applyChange:e,adaptFormulaString:t}){for(let t in this.pivots){let n=b(this.pivots[t]?.definition);if(!n)continue;let r=ZL.get(n.type)?.adaptRanges?.(this.getters,n,e);r&&!w(n,r)&&this.history.update(`pivots`,t,`definition`,r)}for(let n in this.compiledMeasureFormulas)for(let r in this.compiledMeasureFormulas[n]){let i=this.pivots[n]?.definition.measures.find(e=>e.id===r);if(!i||!i.computedBy)continue;let a=i.computedBy.sheetId,{formula:o,dependencies:s}=this.compiledMeasureFormulas[n][r];this.history.update(`compiledMeasureFormulas`,n,r,`formula`,`dependencies`,o.dependencies.map(t=>e(t).range)),this.history.update(`compiledMeasureFormulas`,n,i.id,`dependencies`,s.map(t=>e(t).range));let c=i.computedBy.formula,l=t(a,c);l!==c&&this.replaceMeasureFormula(n,i,l)}}getPivotDisplayName(e){return`(#${this.getPivotFormulaId(e)}) ${this.getPivotName(e)}`}getPivotName(e){return this.getPivotCore(e).definition.name}getPivotCoreDefinition(e){return this.getPivotCore(e).definition}getPivotId(e){return this.formulaIds[e]}getPivotFormulaId(e){return this.getPivotCore(e).formulaId}getPivotIds(){return Object.keys(this.pivots)}isExistingPivot(e){return e in this.pivots}getMeasureCompiledFormula(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].formula}getMeasureFullDependencies(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].dependencies}addPivot(e,t,n=this.nextFormulaId.toString()){this.history.update(`pivots`,e,{definition:b(t),formulaId:n}),this.compileCalculatedMeasures(e,t.measures),this.history.update(`formulaIds`,n,e),this.history.update(`nextFormulaId`,this.nextFormulaId+1)}compileCalculatedMeasures(e,t){for(let n of t)if(n.computedBy){let t=this.compileMeasureFormula(n.computedBy.sheetId,n.computedBy.formula);this.history.update(`compiledMeasureFormulas`,e,n.id,`formula`,t)}for(let n of t)if(n.computedBy){let t=this.computeMeasureFullDependencies(e,n);this.history.update(`compiledMeasureFormulas`,e,n.id,`dependencies`,t)}}computeMeasureFullDependencies(e,t,n=new Set){let r=[],i=this.getPivotCoreDefinition(e),a=this.getMeasureCompiledFormula(e,t);n.add(t.id);for(let o of a.tokens){if(o.type!==`SYMBOL`)continue;let a=i.measures.find(e=>Ye(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:gh(t,a)})}}resizeSheet(e,{col:t,row:n},r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:s-l,position:`after`})}getPivotCore(e){let t=this.pivots[e];if(!t)throw Error(`Pivot with id ${e} not found`);return t}compileMeasureFormula(e,t){let n=lU(t),r=n.dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t));return{...n,dependencies:r}}replaceMeasureFormula(e,t,n){let r=this.pivots[e];if(!r)return;let i=r.definition.measures.indexOf(t);this.history.update(`pivots`,e,`definition`,`measures`,i,`computedBy`,{formula:n,sheetId:t.computedBy.sheetId})}checkSortedColumnInMeasures(e){let t=e.measures.map(e=>e.id);return e.sortedColumn&&!t.includes(e.sortedColumn.measure)?`InvalidDefinition`:`Success`}checkDuplicatedMeasureIds(e){let t=new Set(e.measures.map(e=>e.id));return e.measures.length===t.size?`Success`:`InvalidDefinition`}checkCustomFieldsAreValid(e){for(let t in e.customFields){let n=e.customFields[t],r=new Set,i=new Set,a=!1;for(let e of n.groups){if(!e.name||i.has(e.name)||e.values.some(e=>r.has(e))||e.isOtherGroup&&a)return`InvalidPivotCustomField`;e.values.forEach(e=>r.add(e)),i.add(e.name),a||=!!e.isOtherGroup}}return`Success`}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||lh(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}},jW=class extends fW{static getters=[`getLocale`];locale=R;allowDispatch(e){switch(e.type){case`UPDATE_LOCALE`:return Uv(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===oy(e)&&(n=oy(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??R}export(e){e.settings={locale:this.locale}}},MW=class extends fW{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||Tr(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=Ft(e.elements),n=Pt(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`}}beforeHandle(e){switch(e.type){case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break}}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`,vl(t.name),t.id);break;case`MOVE_SHEET`:this.moveSheet(e.sheetId,e.delta);break;case`RENAME_SHEET`:this.renameSheet(this.sheets[e.sheetId],e.newName);break;case`COLOR_SHEET`:this.history.update(`sheets`,e.sheetId,`color`,e.color);break;case`HIDE_SHEET`:this.hideSheet(e.sheetId);break;case`SHOW_SHEET`:this.showSheet(e.sheetId);break;case`DUPLICATE_SHEET`:this.duplicateSheet(e.sheetId,e.sheetIdTo,e.sheetNameTo);break;case`DELETE_SHEET`:this.deleteSheet(this.sheets[e.sheetId]);break;case`ADD_COLUMNS_ROWS`: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[vl(t.name)]=t.id;for(let t of e.sheets){let e=t.name||`Sheet`+(Object.keys(this.sheets).length+1),{colNumber:n,rowNumber:r}=this.getImportedSheetSize(t),i={id:t.id,name:e,numberOfCols:n,rows:pl(r),areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,panes:{xSplit:t.panes?.xSplit||0,ySplit:t.panes?.ySplit||0},color:t.color};this.orderedSheetIds.push(i.id),this.sheets[i.id]=i}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(C).map(e=>{let t=this.sheets[e],n={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},styles:{},formats:{},borders:{},conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,color:t.color};return(t.panes.xSplit||t.panes.ySplit)&&(n.panes=t.panes),n})}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){let t=this.sheets[e];if(!t)throw Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){return this.tryGetSheet(e)?.name}getSheetIdByName(e){if(e)return this.sheetIdsMapName[vl(e)]}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}doesHeaderExist(e,t,n){return t===`COL`?n>=0&&n<this.getNumberCols(e):n>=0&&n<this.getNumberRows(e)}doesHeadersExist(e,t,n){return n.every(n=>this.doesHeaderExist(e,t,n))}getCell({sheetId:e,col:t,row:n}){let r=this.tryGetSheet(e)?.rows[n]?.cells[t];if(r!==void 0)return this.getters.getCellById(r)}getColsZone(e,t,n){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:n}}getRowCells(e,t){return Object.values(this.getSheet(e).rows[t]?.cells).filter(C)}getRowsZone(e,t,n){return{top:t,bottom:n,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){let t=this.cellPosition[e];if(!t)throw Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return t===`COL`?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e=`Sheet`){return gl(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?yt(n,S(i,a)):!1}getCommandZones(e){let t=[];return`zone`in e&&t.push(e.zone),`target`in e&&t.push(...e.target),`ranges`in e&&t.push(...e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone)),`col`in e&&e.col!==void 0&&`row`in e&&e.row!==void 0&&t.push({top:e.row,left:e.col,bottom:e.row,right:e.col}),t}checkZonesExistInSheet(e,t){if(!t.every(pn))return`InvalidRange`;if(t.length){let n=this.getSheetZone(e);return t.every(e=>Dn(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:pl(r),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0}},o=this.orderedSheetIds.slice();o.splice(i,0,a.id);let s=this.sheets;return this.history.update(`orderedSheetIds`,o),this.history.update(`sheets`,Object.assign({},s,{[a.id]:a})),a}moveSheet(e,t){let n=this.orderedSheetIds.slice(),r=n.findIndex(t=>t===e),i=n.splice(r,1),a=this.findIndexOfTargetSheet(r,t);n.splice(a,0,i[0]),this.history.update(`orderedSheetIds`,n)}findIndexOfTargetSheet(e,t){for(;t!==0&&0<=e&&e<=this.orderedSheetIds.length;)t>0?(e++,this.isSheetVisible(this.orderedSheetIds[e])&&t--):t<0&&(e--,this.isSheetVisible(this.orderedSheetIds[e])&&t++);if(t===0)return e;throw Error(`There is not enough visible sheets`)}checkSheetName(e){let t=this.getters.tryGetSheetName(e.sheetId),n=e.type===`RENAME_SHEET`?e.newName:e.name;if(t!==void 0&&n===t)return`UnchangedSheetName`;let{orderedSheetIds:r,sheets:i}=this,a=n&&n.trim().toLowerCase();return r.find(t=>yl(i[t]?.name,a)&&t!==e.sheetId)?`DuplicatedSheetName`:Me.test(a)?`ForbiddenCharactersInSheetName`:`Success`}checkSheetPosition(e){let{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?`WrongSheetPosition`:`Success`}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkRowFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.top<e.quantity&&e.quantity<=n.bottom)return`MergeOverlap`;return`Success`}checkColFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.left<e.quantity&&e.quantity<=n.right)return`MergeOverlap`;return`Success`}isRenameAllowed(e){return e.newName&&e.newName.trim().toLowerCase()?this.checkSheetName(e):`MissingSheetName`}renameSheet(e,t){let n=e.name;this.history.update(`sheets`,e.id,`name`,t.trim());let r=Object.assign({},this.sheetIdsMapName);delete r[vl(n)],r[vl(t)]=e.id,this.history.update(`sheetIdsMapName`,r)}hideSheet(e){this.history.update(`sheets`,e,`isVisible`,!1)}showSheet(e){this.history.update(`sheets`,e,`isVisible`,!0)}duplicateSheet(e,t,n){let r=b(this.getSheet(e));r.id=t,r.name=n;for(let e=0;e<=r.numberOfCols;e++)for(let t=0;t<=r.rows.length;t++)r.rows[t]&&(r.rows[t].cells[e]=void 0);let i=this.orderedSheetIds.slice(),a=i.indexOf(e);i.splice(a+1,0,r.id),this.history.update(`orderedSheetIds`,i),this.history.update(`sheets`,Object.assign({},this.sheets,{[r.id]:r}));for(let t of Object.values(this.getters.getCells(e))){let{sheetId:e,col:n,row:i}=this.getCellPosition(t.id),a=this.getters.getCellStyle({sheetId:e,col:n,row:i});this.dispatch(`UPDATE_CELL`,{sheetId:r.id,col:n,row:i,content:t.content,format:t.format,style:a})}let o=Object.assign({},this.sheetIdsMapName);o[vl(r.name)]=r.id,this.history.update(`sheetIdsMapName`,o)}getDuplicateSheetName(e){return _l(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[vl(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 Ze(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(Zt),n=e.rowNumber,r=e.colNumber;for(let{col:e,row:i}of t)n=Math.max(n,i+1),r=Math.max(r,e+1);return{rowNumber:n,colNumber:r}}checkSheetExists(e){return e.type!==`CREATE_SHEET`&&`sheetId`in e&&this.sheets[e.sheetId]===void 0?`InvalidSheetId`:e.type===`CREATE_SHEET`&&this.sheets[e.sheetId]!==void 0?`DuplicatedSheetId`:`Success`}checkZonesAreInSheet(e){return`sheetId`in e?`ranges`in e&&e.ranges.some(e=>e._sheetId!==``&&!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkZonesExistInSheet(e.sheetId,this.getCommandZones(e)):`Success`}},NW=class extends fW{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||!pn(t)?`InvalidDataSet`:this.getters.checkZonesExistInSheet(n,[t])}return`Success`}};let PW={verticalAlign:`bottom`,wrapping:`overflow`,bold:!1,italic:!1,strikethrough:!1,underline:!1,fontSize:10,fillColor:``,textColor:``};var FW=class extends fW{static getters=[`getCellStyle`,`getCellStyleInZone`,`getZoneStyles`,`getStyleColors`];styles={};allowDispatch(e){switch(e.type){case`SET_FORMATTING`:return this.checkUselessSetFormatting(e)}return`Success`}handle(e){switch(e.type){case`ADD_MERGE`:for(let t of e.target)this.onMerge(e.sheetId,t);break;case`SET_FORMATTING`:e.style!==void 0&&(e.style===null?this.clearStyle(e.sheetId,e.target):this.setStyles(e.sheetId,e.target,e.style));break;case`CLEAR_FORMATTING`:this.clearStyle(e.sheetId,e.target);break;case`UPDATE_CELL`:e.style!==void 0&&(e.style===null?this.clearStyle(e.sheetId,[E(e)]):this.setStyles(e.sheetId,[E(e)],e.style,{force:!0}));break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumnn(e):this.handleAddRows(e);break;case`CLEAR_CELL`:this.clearStyle(e.sheetId,[E(e)]);break;case`CLEAR_CELLS`:this.clearStyle(e.sheetId,e.target);break;case`DELETE_SHEET`:this.history.update(`styles`,e.sheetId,void 0);break}}adaptRanges({applyChange:e},t){let n=[];for(let r of this.styles[t]??[]){let i=e(this.getters.getRangeFromZone(t,r.zone));switch(i.changeType){case`RESIZE`:case`CHANGE`:case`MOVE`:n.push({style:r.style,zone:i.range.unboundedZone});break;case`NONE`:n.push(r);break}}this.history.update(`styles`,t,n)}handleAddColumnn(e){let t=this.styles[e.sheetId]??[];for(let n=0;n<t.length;n++){let r=t[n];r.zone.left-e.quantity===e.base&&e.position===`before`?this.history.update(`styles`,e.sheetId,n,`zone`,`left`,r.zone.left-e.quantity):r.zone.right===e.base&&e.position===`after`&&this.history.update(`styles`,e.sheetId,n,`zone`,`right`,r.zone.right+e.quantity)}}handleAddRows(e){let t=this.styles[e.sheetId]??[];for(let n=0;n<t.length;n++){let r=t[n];r.zone.top-e.quantity===e.base&&e.position===`before`?this.history.update(`styles`,e.sheetId,n,`zone`,`top`,r.zone.top-e.quantity):r.zone.bottom===e.base&&e.position===`after`&&this.history.update(`styles`,e.sheetId,n,`zone`,`bottom`,r.zone.bottom+e.quantity)}}styleIsDefault(e){for(let t in e)if(PW[t]!==e[t])return!1;return!0}removeDefaultStyleValues(e){let t={...e};for(let n in e)(t[n]===void 0||t[n]===PW[n])&&delete t[n];return Object.keys(t).length>0?t:void 0}onMerge(e,t){this.setStyle(e,t,this.getCellStyle({sheetId:e,col:t.left,row:t.top}),{force:!0})}setStyles(e,t,n,r={force:!1}){for(let i of t)this.setStyle(e,i,n,r)}setStyle(e,t,n,r={force:!1}){let i=[],a=[this.getters.expandZone(e,t)];for(let o of this.styles[e]??[]){let e=Sn(o.zone,t);if(!e){i.push(o);continue}let s=r.force?n:{...o.style,...n};if(s=this.removeDefaultStyleValues(s),w(o.style,s))i.push(o);else{s&&!this.styleIsDefault(s)&&i.push({zone:e,style:s});for(let t of Qt([o.zone],[e]))i.push({zone:t,style:o.style})}a=Qt(a,[e])}n=this.removeDefaultStyleValues(n),n&&i.push(...a.map(e=>({zone:e,style:n}))),this.history.update(`styles`,e,i)}clearStyle(e,t){this.setStyles(e,t,void 0,{force:!0})}getCellStyle(e){return this.styles[e.sheetId]?.find(t=>En(e.col,e.row,t.zone))?.style}getCellStyleInZone(e,t){let n=new bF;for(let{zone:r,style:i}of this.styles[e]??[]){let a=Sn(r,t);if(a)for(let t=a.left;t<=a.right;t++)for(let r=a.top;r<=a.bottom;r++)n.set({sheetId:e,col:t,row:r},i)}return n}getZoneStyles(e,t){let n=[];for(let r of this.styles[e]??[]){let e=Sn(r.zone,t);e&&n.push({zone:e,style:r.style})}return n}getStyleColors(e){let t=new Set;for(let n of this.styles[e]??[])n.style.textColor&&t.add(n.style.textColor),n.style.fillColor&&t.add(n.style.fillColor);return[...t]}import(e){if(Object.keys(e.styles||{}).length){for(let t of e.sheets)for(let n in t.styles){let r=t.styles[n];this.setStyle(t.id,un(n),e.styles[r])}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.onMerge(t.id,un(e))}}export(e){let t={};for(let n of e.sheets){n.styles={};for(let e of this.styles[n.id]??[])n.styles[hn(e.zone)]=_c(e.style,t)}e.styles=t}exportForExcel(e){this.export(e)}checkUselessSetFormatting(e){let{sheetId:t,target:n}=e,r=`style`in e,i=`format`in e;if(!r&&!i)return`NoChanges`;for(let a of Qt(n))for(let n=a.left;n<=a.right;n++)for(let o=a.top;o<=a.bottom;o++){let a={sheetId:t,col:n,row:o},s=this.getters.getCell(a),c=this.getCellStyle(a);if(r&&!w(c,e.style)||i&&s?.format!==e.format)return`Success`}return`NoChanges`}},IW=class extends fW{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(!LA[e.templateName])return`InvalidTableStyle`;try{wr(e.primaryColor)}catch{return`InvalidTableStyle`}break}return`Success`}handle(e){switch(e.type){case`CREATE_TABLE_STYLE`:let t=RA(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:SA.styleId}});break}}getTableStyle(e){if(!this.styles[e])throw Error(`Table style ${e} does not exist`);return this.styles[e]}getTableStyles(){return this.styles}getNewCustomTableStyleName(){return zt(k(`Custom Table Style`),Object.values(this.styles).map(e=>e.displayName),{compute:(e,t)=>`${e} ${t}`,start:2})}isTableStyleEditable(e){return!IA[e]}import(e){for(let e in IA)this.styles[e]=IA[e];for(let t in e.customTableStyles){let n=e.customTableStyles[t];this.styles[t]=RA(n.displayName,n.templateName,n.primaryColor)}}export(e){let t={};for(let e in this.styles)IA[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}},LW=class extends fW{static getters=[`getCoreTable`,`getCoreTables`,`getCoreTableMatchingTopLeft`];tables={};nextTableId=1;adaptRanges({applyChange:e},t){for(let n of this.getCoreTables(t))this.applyRangeChangeOnTable(t,n,e)}allowDispatch(e){switch(e.type){case`CREATE_TABLE`:if(e.ranges.some(t=>!this.getters.tryGetSheet(t._sheetId)||t._sheetId!==e.sheetId))return`InvalidSheetId`;let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone);return Gn(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(wn(n,t))return`MergeInTable`}break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`tables`,e.sheetId,{});break;case`DELETE_SHEET`:{let t={...this.tables};delete t[e.sheetId],this.history.update(`tables`,t);break}case`DUPLICATE_SHEET`:{let t={};for(let n of this.getCoreTables(e.sheetId))t[n.id]=n.type===`dynamic`?this.copyDynamicTableForSheet(e.sheetIdTo,n):this.copyStaticTableForSheet(e.sheetIdTo,n);this.history.update(`tables`,e.sheetIdTo,t);break}case`CREATE_TABLE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e)),n=this.getters.getRangesUnion(t),r=this.getters.getMergesInZone(e.sheetId,n.zone);r.length&&this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:r});let i=this.consumeNextId(),a=e.config||SA,o=e.tableType===`dynamic`?this.createDynamicTable(i,n,a):this.createStaticTable(i,e.tableType,n,a);this.history.update(`tables`,e.sheetId,o.id,o);break}case`REMOVE_TABLE`:{let t={};for(let n of this.getCoreTables(e.sheetId))e.target.every(e=>!Sn(n.range.zone,e))&&(t[n.id]=n);this.history.update(`tables`,e.sheetId,t);break}case`UPDATE_TABLE`:this.updateTable(e);break;case`UPDATE_CELL`:{let t=e.sheetId;for(let n of this.getCoreTables(t)){if(n.type===`dynamic`)continue;let r=this.canUpdateCellCmdExtendTable(e,n);r===`down`?this.extendTableDown(t,n):r===`right`&&this.extendTableRight(t,n)}break}case`DELETE_CONTENT`:{let t={...this.tables[e.sheetId]};for(let n in t){let r=t[n];r&&e.target.some(e=>Dn(r.range.zone,e))&&this.dispatch(`REMOVE_TABLE`,{sheetId:e.sheetId,target:[r.range.zone]})}break}}}getCoreTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(C):[]}getCoreTable({sheetId:e,col:t,row:n}){return this.getCoreTables(e).find(e=>En(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter(e=>t.some(t=>wn(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,[E(r)]).length)return`none`}return o}getCoreTableMatchingTopLeft(e,t){for(let n of this.getCoreTables(e)){let e=n.range.zone;if(e.left===t.left&&e.top===t.top)return n}}checkUpdatedTableZoneIsValid(e){if(!e.newTableRange)return`Success`;let t=this.getters.getRangeFromRangeData(e.newTableRange).zone,n=this.getters.checkZonesExistInSheet(e.sheetId,[t]);if(n!==`Success`)return n;let r=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);return r?this.getTablesOverlappingZones(e.sheetId,[t]).filter(e=>e.id!==r.id).length?`TableOverlap`:`Success`:`TableNotFound`}checkTableConfigUpdateIsValid(e){return e&&(e.numberOfHeaders!==void 0&&e.numberOfHeaders<0||e.hasFilters&&e.numberOfHeaders===0)?`InvalidTableConfig`:`Success`}createStaticTable(e,t,n,r,i){let a=n.zone;if(!i){i=[];for(let e of S(a.left,a.right+1)){let t={...a,left:e,right:e},o=this.consumeNextId();i.push(this.createFilterFromZone(o,n.sheetId,t,r))}}return{id:e,range:n,filters:i,config:r,type:t}}createDynamicTable(e,t,n){let r=Rn(t.zone);return{id:e,range:this.getters.getRangeFromZone(t.sheetId,r),config:n,type:`dynamic`}}updateTable(e){let t=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return;let n=e.newTableRange?this.getters.getRangeFromRangeData(e.newTableRange):void 0;if(n){let t=this.getters.getMergesInZone(e.sheetId,n.zone);this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:t})}let r=n||t.range,i=this.updateTableConfig(e.config,t.config),a=e.tableType??t.type;if(a===`dynamic`&&t.type!==`dynamic`||a!==`dynamic`&&t.type===`dynamic`){let n=a===`dynamic`?this.createDynamicTable(t.id,r,i):this.createStaticTable(t.id,a,r,i);this.history.update(`tables`,e.sheetId,t.id,n)}else{let n=t.type===`dynamic`?this.updateDynamicTable(t,r,i):this.updateStaticTable(t,r,i,a);this.history.update(`tables`,e.sheetId,t.id,n)}}updateStaticTable(e,t,n,r=e.type){if(r===`dynamic`)throw Error(`Cannot use updateStaticTable to update a dynamic table`);let i=t||e.range,a=i.zone,o=this.updateTableConfig(n,e.config),s=o||e.config,c=[];if(t||o&&`numberOfHeaders`in o)for(let t of S(a.left,a.right+1)){let n=a.top===e.range.zone.top?e.filters.find(e=>e.col===t):void 0,r={...a,left:t,right:t},o=n?.id||this.consumeNextId();c.push(this.createFilterFromZone(o,i.sheetId,r,s))}return{...e,range:i,config:s,filters:c.length?c:e.filters,type:r}}updateDynamicTable(e,t,n){let r=t?this.getters.getRangeFromZone(t.sheetId,Rn(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 eI(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 eI(n.id,r,t.config,this.getters.getRangeFromZone)});return{id:t.id,range:n,filters:r,config:b(t.config),type:t.type}}copyDynamicTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone);return{id:t.id,range:n,config:b(t.config),type:`dynamic`}}applyRangeChangeOnTable(e,t,n){let r=n(t.range),i;switch(r.changeType){case`REMOVE`:this.history.update(`tables`,e,t.id,void 0);return;case`NONE`:return;default:i=r.range}if(t.type===`dynamic`){let n=this.updateDynamicTable(t,i);this.history.update(`tables`,e,t.id,n);return}let a=[];for(let e of t.filters){let r=n(e.rangeWithHeaders);switch(r.changeType){case`REMOVE`:continue;case`NONE`:a.push(e);break;default:let n=r.range,i=eI(e.id,n,t.config,this.getters.getRangeFromZone);a.push(i)}}let o=i.zone;if(a.length<On(o).numberOfCols){for(let n=o.left;n<=o.right;n++)if(!a.find(e=>e.col===n)){let r=this.consumeNextId(),i={...o,left:n,right:n};a.push(this.createFilterFromZone(r,e,i,t.config))}a.sort((e,t)=>e.col-t.col)}let s=this.createStaticTable(t.id,t.type,i,t.config,a);this.history.update(`tables`,e,t.id,s)}consumeNextId(){let e=`${this.nextTableId}`;return this.history.update(`nextTableId`,this.nextTableId+1),e}import(e){for(let t of e.sheets)for(let e of t.tables||[]){let n=this.consumeNextId(),r=e.config||SA,i=this.getters.getRangeFromSheetXC(t.id,e.range),a=e.type||`static`,o=a===`dynamic`?this.createDynamicTable(n,i,r):this.createStaticTable(n,a,i,r);this.history.update(`tables`,t.id,o.id,o)}}export(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n={range:hn(e.range.zone),type:e.type};w(e.config,SA)||(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=hn(e.range.zone);t.tables.push({range:n,filters:[],config:e.config})}}},RW=class extends sb{getters;constructor({getters:e,stateObserver:t}){super(t),this.getters=e}};let zW=yO.mapping;function BW(e,t,n){return new VW(e,t,n).getParameters()}var VW=class{getters;computeCell;evalContext;rangeCache={};constructor(e,t,n){this.getters=t,this.computeCell=n,this.evalContext=Object.assign(Object.create(zW),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;let r={sheetId:e.sheetId,col:e.zone.left,row:e.zone.top};return t?(this.computeCell(r),{value:Fc(this.getters.getSheetName(e.sheetId),hn(e.zone))}):this.computeCell(r)}range(e,t){let n=this.getRangeError(e);if(n)return[[n]];let r=e.sheetId,i=e.zone,a=Sn(i,this.getters.getSheetZone(r));if(!a)return[[]];let{top:o,left:s,bottom:c,right:l}=i,u=`${r}-${o}-${s}-${c}-${l}-${t}`;if(u in this.rangeCache)return this.rangeCache[u];let d=a.bottom-a.top+1,f=a.right-a.left+1,p=Array(f),m=this.getters.getSheetName(e.sheetId);for(let e=a.left;e<=a.right;e++){let n=e-a.left;p[n]=Array(d);for(let i=a.top;i<=a.bottom;i++){let o=i-a.top,s=this.computeCell({sheetId:r,col:e,row:i});p[n][o]=t?{value:Fc(m,T(e,i))}:s}}return this.rangeCache[u]=p,p}getRangeError(e){if(!pn(e.zone))return new ma;if(e.invalidSheetName)return new ma(k(`Invalid sheet name: %s`,e.invalidSheetName))}},HW=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),UW=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 WW,this.rTrees[e].load(t[e])}insert(e){let t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new WW),this.rTrees[t].insert(e)}search({zone:e,sheetId:t}){return this.rTrees[t]?this.rTrees[t].search({minX:e.left,minY:e.top,maxX:e.right,maxY:e.bottom}):[]}remove(e){let t=e.boundingBox.sheetId;this.rTrees[t]&&this.rTrees[t].remove(e,this.rtreeItemComparer)}rtreeItemComparer(e,t){return e.boundingBox.sheetId===t.boundingBox.sheetId&&e.boundingBox?.zone.left===t.boundingBox.zone.left&&e.boundingBox?.zone.top===t.boundingBox.zone.top&&e.boundingBox?.zone.right===t.boundingBox.zone.right&&e.boundingBox?.zone.bottom===t.boundingBox.zone.bottom&&w(e.data,t.data)}},WW=class extends HW.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}},GW=class e{profilesStartingPosition=[0];profiles=new Map([[0,[]]]);constructor(e=[]){for(let t of e)this.add(t)}isEmpty(){return this.profiles.size===1&&this.profiles.get(0)?.length===0}add(e){$t(this.profilesStartingPosition,this.profiles,[e])}delete(e){$t(this.profilesStartingPosition,this.profiles,[e],!0)}has(e){return en(this.profilesStartingPosition,this.profiles,e)}difference(e){let t=this.copy();for(let n of e)t.delete(n);return t}copy(){let t=new e;t.profilesStartingPosition=[...this.profilesStartingPosition],t.profiles=new Map;for(let[e,n]of this.profiles)t.profiles.set(e,[...n]);return t}[Symbol.iterator](){return an(this.profilesStartingPosition,this.profiles)[Symbol.iterator]()}},KW=class e{setsBySheetId={};constructor(e=[]){for(let t of e)this.add(t)}add(e){this.setsBySheetId[e.sheetId]||(this.setsBySheetId[e.sheetId]=new GW),this.setsBySheetId[e.sheetId].add(e.zone)}addMany(e){for(let t of e)this.add(t)}addPosition(e){this.add(el(e))}addManyPositions(e){for(let t of e)this.addPosition(t)}has(e){return this.setsBySheetId[e.sheetId]?this.setsBySheetId[e.sheetId].has(e.zone):!1}hasPosition(e){return this.has(el(e))}delete(e){this.setsBySheetId[e.sheetId]&&this.setsBySheetId[e.sheetId].delete(e.zone)}deleteMany(e){for(let t of e)this.delete(t)}deleteManyPositions(e){for(let t of e)this.delete(el(t))}difference(t){let n=new e;for(let e in this.setsBySheetId)n.setsBySheetId[e]=this.setsBySheetId[e];for(let e in t.setsBySheetId)n.setsBySheetId[e]&&(n.setsBySheetId[e]=n.setsBySheetId[e].difference(t.setsBySheetId[e]));return n}copy(){let t=new e;for(let e in this.setsBySheetId)t.setsBySheetId[e]=this.setsBySheetId[e].copy();return t}clear(){this.setsBySheetId={}}isEmpty(){for(let e in this.setsBySheetId)if(!this.setsBySheetId[e].isEmpty())return!1;return!0}[Symbol.iterator](){let e=[];for(let t in this.setsBySheetId)for(let n of this.setsBySheetId[t])e.push({sheetId:t,zone:n});return e[Symbol.iterator]()}},qW=class{rTree;constructor(e=[]){let t=JW(e);this.rTree=new UW(t)}insert(e){let t=this.rTree.search(e.boundingBox),n=e.boundingBox,r=t.find(({boundingBox:e})=>e.sheetId===n.sheetId&&e.zone.left===n.zone.left&&e.zone.top===n.zone.top&&e.zone.right===n.zone.right&&e.zone.bottom===n.zone.bottom);r?r.data.add(e.data):this.rTree.insert({...e,data:new KW([e.data])})}search({zone:e,sheetId:t}){let n=new KW;for(let{data:r}of this.rTree.search({zone:e,sheetId:t}))n.addMany(r);return n}remove(e){let t=this.rTree.search(e.boundingBox),n=e.boundingBox,r=t.find(({boundingBox:e})=>e.sheetId===n.sheetId&&e.zone.left===n.zone.left&&e.zone.top===n.zone.top&&e.zone.right===n.zone.right&&e.zone.bottom===n.zone.bottom);r?r.data.delete(e.data):this.rTree.remove({...e,data:new KW([e.data])})}};function JW(e){let t=0,n=0;for(let r=0;r<e.length;r++){let i=e[r].boundingBox.zone;i.right>t&&(t=i.right),i.bottom>n&&(n=i.bottom)}t+=1,n+=1;let r=(((n+1)*t+1)*n+1)*t<=2**53-1;r||console.warn(`Max col/row size exceeded, using slow zone key`);let i={};for(let a of e){let e=a.boundingBox.sheetId;i[e]||(i[e]={});let o=a.boundingBox.zone,s=0;s=r?o.left+o.top*t+o.right*t*n+o.bottom*t*n*t:`${o.left},${o.top},${o.right},${o.bottom}`,i[e][s]?i[e][s].data.add(a.data):i[e][s]={boundingBox:a.boundingBox,data:new KW([a.data])}}let a=[];for(let e in i){let t=i[e];for(let e in t)a.push(t[e])}return a}var YW=class{dependencies=new bF;rTree;constructor(e=[]){this.rTree=new qW(e)}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:{sheetId:e.sheetId,zone:E(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=new KW){t=t.copy();let n=Array.from(e).reverse();for(;n.length>0;){let e=n.pop();t.add(e);let r=this.rTree.search(e);n.push(...r.difference(t))}for(let n of e)t.delete(n);return t}},XW=class extends Uint32Array{columnOffset=0;cols=0;rows=0;static create(e,t){let n=ZW(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 ZW(e){return e===0?-1/0:e<0?NaN:32-Math.clz32(--e)}var QW=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]=XW.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)}},$W=class{resultsToArrayFormulas=new UW;arrayFormulasToResults=new bF;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map(e=>e.data)||eG}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 eG=[],tG=new B;tG.add(`pivots`,e=>{for(let t of e.getPivotIds())e.getPivot(t).markAsDirtyForEvaluation?.()});let nG=Object.freeze(rc({...new pa,origin:void 0})),rG=Object.freeze(rc({value:null}));var iG=class{context;getters;compilationParams;evaluatedCells=new bF;formulaDependencies=mt(new YW);blockedArrayFormulas=new QW({});spreadingRelations=new $W;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=BW(this.context,this.getters,this.computeAndSave.bind(this))}getEvaluatedCell(e){return this.evaluatedCells.get(e)||rG}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===A.SpilledBlocked)?E(e):bn(E(e),n)}getEvaluatedPositions(){return this.evaluatedCells.keys()}getEvaluatedPositionsInSheet(e){return this.evaluatedCells.keysForSheet(e)}getArrayFormulaSpreadingOn(e){if(this.getEvaluatedCell(e).type!==`empty`)return this.spreadingRelations.searchFormulaPositionsSpreadingOn(e.sheetId,E(e)).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,!1)}updateCompilationParametersForIsolatedFormula(e){this.compilationParams=BW(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.__originCellPosition=e,this.compilationParams.evalContext.updateDependencies=void 0,this.compilationParams.evalContext.addDependencies=void 0,this.compilationParams.evalContext.lookupCaches=this.compilationParams.evalContext.lookupCaches||{forwardSearch:new Map,reverseSearch:new Map}}updateCompilationParameters(){this.compilationParams=BW(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 QW(e)}evaluateCells(e){let t=performance.now(),n=new KW;n.addManyPositions(e);let r=this.getArrayFormulasImpactedByChangesOf(e);n.addMany(this.getCellsDependingOn(n)),n.addMany(r),n.addMany(this.getCellsDependingOn(r)),this.evaluate(n),console.debug(`evaluate Cells`,performance.now()-t,`ms`)}getArrayFormulasImpactedByChangesOf(e){let t=new KW;for(let n of e){let e=this.getters.getCell(n)?.content,r=this.getArrayFormulaSpreadingOn(n);r!==void 0&&t.addPosition(r),e||t.addPosition(n)}for(let e of[...t])t.addMany(this.getArrayFormulasBlockedBy(e.sheetId,e.zone));return t}buildDependencyGraph(){this.blockedArrayFormulas=this.createEmptyPositionSet(),this.spreadingRelations=new $W,this.formulaDependencies=mt(()=>{let e=[];for(let t of this.getters.getSheetIds()){let n=this.getters.getCells(t);for(let r in n){let i=n[r];if(i.isFormula){let n=i.compiledFormula.dependencies;for(let i of n)i.invalidSheetName||i.invalidXc||e.push({data:{sheetId:t,zone:E(this.getters.getCellPosition(r))},boundingBox:{sheetId:i.sheetId,zone:i.zone}})}}}return new YW(e)})}evaluateAllCells(){let e=performance.now();this.evaluatedCells=new bF;let t=[];for(let e of this.getters.getSheetIds()){let n=this.getters.getSheetZone(e);t.push({sheetId:e,zone:n})}this.evaluate(t),console.debug(`evaluate all cells`,performance.now()-e,`ms`)}evaluateFormulaResult(e,t,n){let r=lU(t),i=r.dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t));return this.updateCompilationParametersForIsolatedFormula(n),this.evaluateCompiledFormula(e,{...r,dependencies:i})}evaluateCompiledFormula(e,t,n){try{let r=cG(t,this.compilationParams,e,this.buildSafeGetSymbolValue(n),this.compilationParams.evalContext.__originCellPosition);return xa(r)?Ga(r,oG):oG(r)}catch(e){return Sy(e,``)}}getArrayFormulasBlockedBy(e,t){let n=new KW,r=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e,t);n.addManyPositions(r);let i=[...r].filter(e=>!this.blockedArrayFormulas.has(e));return i.length&&n.deleteManyPositions(i),n.addMany(this.getCellsDependingOn(n)),n}nextRangesToUpdate=new KW;cellsBeingComputed=new Set;symbolsBeingComputed=new Set;evaluate(e){this.cellsBeingComputed=new Set,this.nextRangesToUpdate=new KW(e);let t=0;for(;!this.nextRangesToUpdate.isEmpty()&&t++<30;){this.updateCompilationParameters();let e=[...this.nextRangesToUpdate];this.nextRangesToUpdate.clear(),this.clearEvaluatedRanges(e);for(let t of e){let{left:e,bottom:n,right:r,top:i}=t.zone;for(let a=e;a<=r;a++)for(let e=i;e<=n;e++){let n={sheetId:t.sheetId,col:a,row:e};if(this.nextRangesToUpdate.hasPosition(n))continue;let r=this.computeCell(n);r!==rG&&this.evaluatedCells.set(n,r)}}tG.getAll().forEach(e=>e(this.getters))}t>=30&&console.warn(`Maximum iteration reached while evaluating cells`)}clearEvaluatedRanges(e){for(let t of e){let{left:e,bottom:n,right:r,top:i}=t.zone;for(let a=e;a<=r;a++)for(let e=i;e<=n;e++)this.evaluatedCells.delete({sheetId:t.sheetId,col:a,row:e})}}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 rG;let r=n.id,i={format:n.format,locale:this.getters.getLocale()};try{return this.cellsBeingComputed.has(r)?nG:(this.cellsBeingComputed.add(r),n.isFormula?this.computeFormulaCell(e,n):tc(n,i,e))}catch(t){return t.value=t?.value||A.GenericError,t.message=t?.message||Ty,t.origin=e,t.errorOriginPosition=t?.errorOriginPosition,rc(t)}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=cG(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e);if(!xa(n)){let r=rc(sG(n),this.getters.getLocale(),t,e);return r.type===`error`&&(r.errorOriginPosition=n.errorOriginPosition??e),r}this.assertSheetHasEnoughSpaceToSpreadFormulaResult(e,n);let r=n.length,i=n[0].length;if(i===0)return rc({value:0},this.getters.getLocale(),t);if(i===1&&r===1)return rc(sG(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),aG(r,i,this.checkCollision(e)),aG(r,i,this.spreadValues(e,n)),this.invalidatePositionsDependingOnSpread(e.sheetId,a),rc(sG(n[0][0]),this.getters.getLocale(),t)}invalidatePositionsDependingOnSpread(e,t){let n=this.getCellsDependingOn(An(t).map(t=>({sheetId:e,zone:t})));n.delete({sheetId:e,zone:t}),this.nextRangesToUpdate.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 _a(k(`Result couldn't be automatically expanded. Please insert more rows.`)):s?new _a(k(`Result couldn't be automatically expanded. Please insert more columns.`)):new _a(k(`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 _a(k(`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 _a(k(`Array result was not expanded because it would overwrite data.`),o);this.blockedArrayFormulas.delete(e)}}spreadValues({sheetId:e,col:t,row:n},r){return(i,a)=>{let o={sheetId:e,col:i+t,row:a+n},s=this.getters.getCell(o),c=rc(sG(r[i][a]),this.getters.getLocale(),s,o);c.type===`error`&&(c.errorOriginPosition=r[i][a].errorOriginPosition??o),this.evaluatedCells.set(o,c)}}invalidateSpreading(e){let t=this.spreadingRelations.getArrayResultZone(e);if(!t)return;for(let n=t.left;n<=t.right;n++)for(let r=t.top;r<=t.bottom;r++){let t={sheetId:e.sheetId,col:n,row:r};this.getters.getCell(t)?.content||this.evaluatedCells.delete(t)}let n=e.sheetId;this.invalidatePositionsDependingOnSpread(n,t),this.nextRangesToUpdate.addMany(this.getArrayFormulasBlockedBy(n,t))}buildSafeGetSymbolValue(e){return t=>{if(this.symbolsBeingComputed.has(t))return nG;this.symbolsBeingComputed.add(t);try{return e?.(t)||new fa(k(`Invalid formula`))}finally{this.symbolsBeingComputed.delete(t)}}}getDirectDependencies(e){let t=this.getters.getCell(e);return t?.isFormula?t.compiledFormula.dependencies:[]}getCellsDependingOn(e){return this.formulaDependencies().getCellsDependingOn(e,this.nextRangesToUpdate)}};function aG(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 oG(e){return e.value===null||e.value===void 0?{...e,value:0}:e}function sG(e){return typeof e.value==`number`&&Math.abs(e.value)>Number.MAX_VALUE?new ya:oG(e)}function cG(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 lG=class extends RW{static getters=[`evaluateFormula`,`evaluateFormulaResult`,`evaluateCompiledFormula`,`getCorrespondingFormulaCell`,`getRangeFormattedValues`,`getRangeValues`,`getRangeFormats`,`getEvaluatedCell`,`getEvaluatedCells`,`getEvaluatedCellsInZone`,`getEvaluatedCellsPositionInZone`,`getEvaluatedCellsPositions`,`getSpreadZone`,`getArrayFormulaSpreadingOn`,`isArrayFormulaSpillBlocked`,`isEmpty`];shouldRebuildDependenciesGraph=!0;evaluator;positionsToUpdate=[];constructor(e){super(e),this.evaluator=new iG(e.custom,this.getters)}beforeHandle(e){(Ps.has(e.type)||Is.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`:if(e.cellIds)for(let t=0;t<e.cellIds.length;t++)this.positionsToUpdate.push(this.getters.getCellPosition(e.cellIds[t]));else this.evaluator.evaluateAllCells();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 xa(r)?Ga(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 Mn(e,t).map(this.getters.getEvaluatedCell)}getEvaluatedCellsPositionInZone(e,t){return Mn(e,t).map(e=>[e,this.getters.getEvaluatedCell(e)])}getSpreadZone(e,t={ignoreSpillError:!1}){return this.evaluator.getSpreadZone(e,t)}getArrayFormulaSpreadingOn(e){return this.evaluator.getArrayFormulaSpreadingOn(e)}isArrayFormulaSpillBlocked(e){return this.evaluator.isArrayFormulaSpillBlocked(e)}isEmpty(e,t){return jn(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 jn(r).reduce((e,r)=>{let{col:i,row:a}=r;return!this.getters.isColHidden(n,i)&&!this.getters.isRowHidden(n,a)&&e.push(t({sheetId:n,...r})),e},[])}exportForExcel(e){for(let t of e.sheets)t.cellValues={},t.formulaSpillRanges={};for(let t of this.evaluator.getEvaluatedPositions()){let n=this.evaluator.getEvaluatedCell(t),r=T(t.col,t.row),i=n.value,a=!1,o,s=!0,c=e.sheets.find(e=>e.id===t.sheetId),l=this.getCorrespondingFormulaCell(t);if(l){let u=this.getters.getCell(t);if(s=SU(l.compiledFormula.tokens),a=s&&u?.content===l.content,!s&&i!==``){o=(i??``).toString();let t=n.format;if(t){let n=_c(t,e.formats);c.formats[r]=n}}}let u=c.cells[r],d;d=s&&a&&l instanceof gW?l.contentWithFixedReferences:s?u:o,c.cells[r]=d,c.cellValues[r]=i===A.BadExpression?void 0:i;let f=this.getSpreadZone(t);f&&(c.formulaSpillRanges[r]=this.getters.getRangeString(this.getters.getRangeFromZone(t.sheetId,f),t.sheetId))}}getCorrespondingFormulaCell(e){let t=this.getters.getCell(e);if(t&&t.isFormula)return t.compiledFormula.isBadExpression?void 0:t;if(t&&t.content)return;let n=this.getArrayFormulaSpreadingOn(e);if(n===void 0)return;let r=this.getters.getCell(n);if(r?.isFormula)return r}};let uG=new B;uG.add(`data_validation_checkbox`,(e,t)=>{if(e.isCellValidCheckbox(t)){let n=!!e.getEvaluatedCell(t).value;return{svg:n?aj:rj,hoverSvg:n?aj:ij,priority:2,horizontalAlign:`center`,size:17,margin:2,position:t,type:`data_validation_checkbox`,onClick:(e,t)=>{let r=t.model.getters.getCell(e);if(t.model.getters.isReadonly()||r?.isFormula)return;let i=n?`FALSE`:`TRUE`;t.model.dispatch(`UPDATE_CELL`,{...e,content:i})}}}}),uG.add(`data_validation_chip_icon`,(e,t)=>{let n=e.getDataValidationChipStyle(t);if(n){let r=e.getCellComputedStyle(t);return{svg:tj(n),hoverSvg:nj(n),priority:10,horizontalAlign:`right`,size:Pl(r),margin:4,position:t,onClick:(e,t)=>{let{col:n,row:r}=e;t.model.selection.selectCell(n,r),t.startCellEdition()},type:`data_validation_chip_icon`}}}),uG.add(`data_validation_list_icon`,(e,t)=>{if(!e.isReadonly()&&e.cellHasListDataValidationIcon(t)){let n=e.getCellComputedStyle(t);return{svg:ZA(n),hoverSvg:$A(n),priority:2,horizontalAlign:`right`,size:17,margin:2,position:t,onClick:(e,t)=>{let{col:n,row:r}=e;t.model.selection.selectCell(n,r),t.startCellEdition()},type:`data_validation_list_icon`}}}),uG.add(`conditional_formatting`,(e,t)=>{let n=e.getConditionalIcon(t);if(n){let r=e.getCellStyle(t);return{type:`conditional_formatting`,svg:cj[n].svg,priority:1,horizontalAlign:`left`,size:Pl(r),margin:4,position:t}}}),uG.add(`pivot_collapse`,(e,t)=>{if(!e.isSpillPivotFormula(t))return;let n=e.getPivotCellFromPosition(t),r=e.getPivotIdFromPosition(t);if(n.type===`HEADER`&&r&&n.domain.length){let i=e.getPivotCoreDefinition(r),a=e.isDashboard(),o=n.dimension===`COL`?i.columns:i.rows,s=!a&&n.domain.length!==o.length,c=(i.collapsedDomains?.[n.dimension]??[]).some(e=>w(e,n.domain)),l=n.dimension===`ROW`?(n.domain.length-1)*15:0;return{type:`pivot_collapse`,priority:4,horizontalAlign:`left`,size:s||!a&&n.dimension===`ROW`&&i.rows.length>1?12:0,margin:s?4+l:l,svg:s?oj(c,!1):void 0,hoverSvg:s?oj(c,!0):void 0,position:t,onClick:Mh}}}),uG.add(`pivot_dashboard_sorting`,(e,t)=>{if(!e.isDashboard()||e.getPivotCellFromPosition(t).type!==`MEASURE_HEADER`)return;let n=e.getPivotCellSortDirection(t);if(n!==`asc`&&n!==`desc`)return;let r=e.getCellComputedStyle(t);return{type:`pivot_dashboard_sorting_${n}`,priority:5,horizontalAlign:`right`,size:17,margin:2,svg:n===`asc`?QA(r):ZA(r),position:t,onClick:void 0}});var dG=class extends RW{static getters=[`doesCellHaveGridIcon`,`getCellIcons`,`getCellIconRect`];cellIconsCache={};handle(e){e.type!==`SET_VIEWPORT_OFFSET`&&(this.cellIconsCache={})}getCellIcons(e){return this.cellIconsCache[e.sheetId]||(this.cellIconsCache[e.sheetId]={}),this.cellIconsCache[e.sheetId][e.col]||(this.cellIconsCache[e.sheetId][e.col]={}),this.cellIconsCache[e.sheetId][e.col][e.row]||(this.cellIconsCache[e.sheetId][e.col][e.row]=this.computeCellIcons(e)),this.cellIconsCache[e.sheetId][e.col][e.row]}getCellIconRect(e,t){let n=e.position,r=this.getters.getCellStyle(n)?.verticalAlign;return{x:this.getIconHorizontalPosition(t,e.horizontalAlign,e),y:this.getters.computeTextYCoordinate(t,e.size,r),width:e.size,height:e.size}}getIconHorizontalPosition(e,t,n){let r=e.x,i=e.x+e.width;switch(t){case`right`:return i-n.margin-n.size;case`left`:return r+n.margin;default:let e=Math.floor((i-r-n.size)/2);return i-n.size-e}}computeCellIcons(e){let t={left:void 0,right:void 0,center:void 0},n=uG.getAll();for(let r of n){let n=r(this.getters,e);n&&(!t[n.horizontalAlign]||n.priority>t[n.horizontalAlign].priority)&&(t[n.horizontalAlign]=n)}if(t.center&&(t.left||t.right)){let e=Math.max(t.left?.priority||0,t.right?.priority||0);t.center.priority<e?t.center=void 0:(t.left=void 0,t.right=void 0)}return Object.values(t).filter(C)}doesCellHaveGridIcon(e){return!!this.getCellIcons(e).length}};let fG=/"(#[0-9a-fA-F]{6})"/g;function pG(e){let t=[{leadColor:Or(255,0,0),colors:[]},{leadColor:Or(255,128,0),colors:[]},{leadColor:Or(128,128,0),colors:[]},{leadColor:Or(128,255,0),colors:[]},{leadColor:Or(0,255,0),colors:[]},{leadColor:Or(0,255,128),colors:[]},{leadColor:Or(0,255,255),colors:[]},{leadColor:Or(0,127,255),colors:[]},{leadColor:Or(0,0,255),colors:[]},{leadColor:Or(127,0,255),colors:[]},{leadColor:Or(128,0,128),colors:[]},{leadColor:Or(255,0,128),colors:[]}];for(let n of e.map(Mr)){let e=500,r=0;t.forEach((t,i)=>{let a=mG(n,t.leadColor);e>a&&(e=a,r=i)}),t[r].colors.push(n)}return t.map(e=>e.colors.sort((e,t)=>Pr(e).s-Pr(t).s)).flat().map(jr)}function mG(e,t){return Math.sqrt((e.r-t.r)**2+(e.g-t.g)**2+(e.b-t.b)**2)}var hG=class extends RW{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.chartId));break;case`UPDATE_CELL`:case`ADD_CONDITIONAL_FORMAT`:case`SET_BORDER`:case`SET_ZONE_BORDERS`:case`SET_FORMATTING`:case`CREATE_TABLE`:case`UPDATE_TABLE`:this.history.update(`shouldUpdateColors`,!0);break}}finalize(){this.shouldUpdateColors&&(this.history.update(`shouldUpdateColors`,!1),this.tryToAddColors(this.computeCustomColors()))}getCustomColors(){return pG(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=new Set;for(let n of this.getters.getStyleColors(e))t.add(n);for(let n of this.getters.getBordersColors(e))t.add(n);return[...t]}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(Sr(t.minimum.color)),n.push(t.midpoint?Sr(t.midpoint.color):void 0),n.push(Sr(t.maximum.color)))}return n.filter(C)}getChartColors(e){let t=this.getters.getChart(e);return t===void 0?[]:[...JSON.stringify(t.getDefinition()).matchAll(fG)].map(e=>e[1])}getTableColors(e){return this.getters.getTables(e).flatMap(e=>{let t=e.config,n=this.getters.getTableStyle(t.styleId);return[this.getTableStyleElementColors(n.wholeTable),t.numberOfHeaders>0?this.getTableStyleElementColors(n.headerRow):[],t.totalRow?this.getTableStyleElementColors(n.totalRow):[],t.bandedColumns?this.getTableStyleElementColors(n.firstColumnStripe):[],t.bandedColumns?this.getTableStyleElementColors(n.secondColumnStripe):[],t.bandedRows?this.getTableStyleElementColors(n.firstRowStripe):[],t.bandedRows?this.getTableStyleElementColors(n.secondRowStripe):[],t.firstColumn?this.getTableStyleElementColors(n.firstColumn):[],t.lastColumn?this.getTableStyleElementColors(n.lastColumn):[]].flat()})}getTableStyleElementColors(e){return e?[e.style?.fillColor,e.style?.textColor,e.border?.bottom?.color,e.border?.top?.color,e.border?.left?.color,e.border?.right?.color,e.border?.horizontal?.color,e.border?.vertical?.color].filter(C):[]}tryToAddColors(e){for(let t of e){if(!Tr(t))continue;let e=wr(t);t&&!_e.includes(e)&&this.history.update(`customColors`,e,!0)}}},gG=class extends RW{static getters=[`canCreateDynamicTableOnZones`,`doesZonesContainFilter`,`getFilter`,`getFilters`,`getTable`,`getTables`,`getTablesOverlappingZones`,`getFilterId`,`getFilterHeaders`,`isFilterHeader`];tables={};handle(e){if(Ps.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;wn(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=>En(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getTables(e).filter(e=>t.some(t=>wn(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(!Gn(t))return!1;let n=bn(...t),r={col:n.left,row:n.top,sheetId:e},i=this.getters.getArrayFormulaSpreadingOn(r);if(!i){let e=this.getters.getEvaluatedCell(r);return e.value===A.SpilledBlocked&&!e.errorOriginPosition}else if(w(i,r)&&Vn(n)===1)return!0;return w(n,this.getters.getSpreadZone(i))}coreTableToTable(e,t){if(t.type!==`dynamic`)return t;let n=t.range.zone,r={sheetId:e,col:n.left,row:n.top},i=this.getters.getSpreadZone(r)??t.range.zone,a=this.getters.getRangeFromZone(e,i),o=this.getDynamicTableFilters(e,t,i);return{id:t.id,range:a,filters:o,config:t.config}}getDynamicTableFilters(e,t,n){let r=[],{top:i,bottom:a,left:o,right:s}=n;for(let n=o;n<=s;n++){let s=n-o,c={left:n,right:n,top:i,bottom:a},l=eI(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:!jn(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=un(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 jn(s.range.zone)){let r={sheetId:t.id,...n},i=this.getters.getCellComputedStyle(r),a=this.getters.getCellComputedBorder(r),o=T(n.col,n.row);if(!ut(i)){let n=_c(i,e.styles);t.styles[o]=n}if(a){let n=_c(a,e.borders);t.borders[o]=n}}}t.tables=n}}},_G=class extends RW{static getters=[`getChartRuntime`,`getStyleOfSingleCellChart`];charts={};createRuntimeChart=h_(this.getters);handle(e){if(Ps.has(e.type)||Ls.has(e.type)||Fs.has(e.type))for(let e in this.charts)this.charts[e]=void 0;switch(e.type){case`UPDATE_CHART`:case`CREATE_CHART`:this.charts[e.chartId]=void 0;break;case`DELETE_CHART`:this.charts[e.chartId]=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:od(e)};if(!t)return{background:oe,fontColor:od(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||od(o)}}async 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=this.getters.getChartIds(t.id).find(e=>this.getters.getFigureIdFromChartId(e)===r.id);if(!e)continue;let i=this.getters.getChart(e),a=i?.getDefinitionForExcel(this.getters);if(a)n.push({...r,data:a});else{if(!i)continue;let n=this.getters.getChartType(e),a=await Hp(this.getters.getChartRuntime(e),r,n);a&&t.images.push({...r,tag:`image`,data:{mimetype:`image/png`,path:a,size:{width:r.width,height:r.height}}})}}t.charts=n}}},vG=class extends RW{static getters=[`getConditionalIcon`,`getCellConditionalFormatStyle`,`getConditionalDataBar`];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(Ps.has(e.type)||Ls.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]=mt(()=>this.getComputedStyles(e)),this.computedIcons[e]=mt(()=>this.getComputedIcons(e)),this.computedDataBars[e]=mt(()=>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(`=`)?lU(e):void 0);for(let i of n.ranges){let a=this.getters.getRangeFromSheetXC(e,i).zone;for(let i=a.top;i<=a.bottom;i++)for(let o=a.left;o<=a.right;o++){let s={sheetId:e,col:o,row:i},c=n.rule.values.map((t,n)=>{let s=r[n];return s?this.getters.getTranslatedCellFormula(e,o-a.left,i-a.top,s.tokens):t});this.getRuleResultForTarget(s,{...n.rule,values:c})&&(t[o]||(t[o]=[]),t[o][i]=Object.assign(t[o]?.[i]||{},n.rule.style))}}break}return t}getComputedIcons(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`IconSetRule`)for(let r of n.ranges)this.applyIcon(e,r,n.rule,t);return t}getComputedDataBars(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`DataBarRule`)for(let r of n.ranges)this.applyDataBar(e,r,n.rule,t);return t}parsePoint(e,t,n,r){let i=this.getters.getRangeFromSheetXC(e,t).zone,a=this.getters.getEvaluatedCellsInZone(e,i).filter(e=>e.type===`number`).map(e=>e.value);switch(n.type){case`value`:return r===`max`?Pt(a):Ft(a);case`number`:return Number(n.value);case`percentage`:let t=Ft(a);return t+(Pt(a)-t)*Number(n.value)/100;case`percentile`:return na(a,Number(n.value)/100,!0);case`formula`:let i=n.value&&this.getters.evaluateFormula(e,n.value);return typeof i==`number`?i: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=Pt(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});!En(i,l,c)||u.type!==`number`||u.value<=0||(r[n]||(r[n]=[]),r[n][t]={color:Sr(o),percentage:u.value*100/a})}}applyColorScale(e,t,n,r){let i=this.parsePoint(e,t,n.minimum,`min`),a=n.midpoint?this.parsePoint(e,t,n.midpoint):null,o=this.parsePoint(e,t,n.maximum,`max`);if(i===null||o===null||i>=o||a&&(i>=a||a>=o))return;let s=this.getters.getRangeFromSheetXC(e,t).zone,c=[{value:i,color:n.minimum.color}];n.midpoint&&a&&c.push({value:a,color:n.midpoint.color}),c.push({value:o,color:n.maximum.color});let l=ai(c);for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let a=this.getters.getEvaluatedCell({sheetId:e,col:n,row:t});if(a.type===`number`){let e=x(a.value,i,o);r[n]||(r[n]=[]),r[n][t]=r[n]?.[t]||{},r[n][t].fillColor=l(e)}}}getRuleResultForTarget(e,t){let n=this.getters.getEvaluatedCell(e);if(n.type===`error`)return!1;let{sheetId:r}=e,i=W.get(t.operator),a=t.values.map(t=>t.startsWith(`=`)?this.getters.evaluateFormula(r,t,e)??``:nc(t,R));if(a.some(gm))return!1;let o={type:t.operator,values:a.map(mm),dateValue:t.dateValue||`exactDate`};return i.isValueValid(n.value??``,o,this.getters,r)}};let yG={isValid:!0};var bG=class extends RW{static getters=[`getDataValidationInvalidCriterionValueMessage`,`getInvalidDataValidationMessage`,`getValidationResultForCellValue`,`getDataValidationRangeValues`,`isCellValidCheckbox`,`getDataValidationCellStyle`,`getDataValidationChipStyle`,`isDataValidationInvalid`];validationResults={};handle(e){if(Ps.has(e.type)||e.type===`EVALUATE_CELLS`||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)){this.validationResults={};return}switch(e.type){case`ADD_DATA_VALIDATION_RULE`:case`REMOVE_DATA_VALIDATION_RULE`:delete this.validationResults[e.sheetId];break}}isDataValidationInvalid(e){return!this.getValidationResultForCell(e).isValid}getDataValidationCellStyle(e){if(!this.hasChip(e))return this.getDataValidationStyle(e)}getDataValidationChipStyle(e){if(this.hasChip(e))return this.getDataValidationStyle(e)??{fillColor:`#E7E9ED`}}getInvalidDataValidationMessage(e){let t=this.getValidationResultForCell(e);return t.isValid?void 0:t.error}getDataValidationInvalidCriterionValueMessage(e,t){let n=W.get(e);return t.startsWith(`=`)?n.allowedValues===`onlyLiterals`?k(`The value must not be a formula`):this.isValidFormula(t)?void 0:H.CriterionError.validFormula:n.allowedValues===`onlyFormulas`?k(`The value must be a formula`):n.isCriterionValueValid(t)?void 0:n.criterionValueErrorString}getDataValidationRangeValues(e,t){let n=this.getters.getRangeFromSheetXC(e,String(t.values[0])),r=[],i=new Set;for(let e of jn(n.zone)){let t=this.getters.getEvaluatedCell({...e,sheetId:n.sheetId});t.formattedValue&&!i.has(t.formattedValue)&&(i.add(t.formattedValue),r.push({label:t.formattedValue,value:t.value?.toString()||``}))}return r}isCellValidCheckbox(e){if(!this.getters.isMainCellPosition(e))return!1;let t=this.getters.getValidationRuleForCell(e);return!t||t.criterion.type!==`isBoolean`?!1:this.getValidationResultForCell(e).isValid}getValidationResultForCellValue(e,t){let n=this.getters.getValidationRuleForCell(t);if(!n)return yG;let r=this.getRuleErrorForCellValue(e,t,n);return r?{error:r,rule:n,isValid:!1}:yG}hasChip(e){let t=this.getters.getValidationRuleForCell(e);return(t?.criterion.type===`isValueInList`||t?.criterion.type===`isValueInRange`)&&t.criterion.displayStyle===`chip`}getDataValidationStyle(e){let t=this.getters.getValidationRuleForCell(e);if(!t||this.isDataValidationInvalid(e))return;let n=this.getters.getEvaluatedCell(e),r=this.getValueColor(t,n.value);if(r)return{fillColor:r,textColor:Ur(r)}}getValueColor(e,t){if(!(e.criterion.type!==`isValueInList`&&e.criterion.type!==`isValueInRange`)){for(let n in e.criterion.colors)if(n.toLowerCase()===String(t).toLowerCase())return e.criterion.colors[n]}}isValidFormula(e){return!lU(e).isBadExpression}getValidationResultForCell(e){let{col:t,row:n,sheetId:r}=e;return this.validationResults[r]||(this.validationResults[r]=this.computeSheetValidationResults(r)),this.validationResults[r][t]?.[n]?.()||yG}computeSheetValidationResults(e){let t={},n=this.getters.getDataValidationRules(e).map(e=>e.ranges);for(let e of Qc(n.flat())){let{col:n,row:r}=e;t[n]||(t[n]=[]),t[n][r]=mt(()=>{let t=this.getters.getEvaluatedCell(e);return t.type===`empty`?yG:this.getValidationResultForCellValue(t.value,e)})}return t}getRuleErrorForCellValue(e,t,n){let{sheetId:r}=t,i=n.criterion,a=W.get(i.type),o=this.getCellOffsetInRule(t,n),s=this.getEvaluatedCriterionValues(r,t,o,i);if(s.some(gm))return;let c={...i,values:s.map(mm)};if(!a.isValueValid(e,c,this.getters,r))return a.getErrorString(c,this.getters,r)}getCellOffsetInRule(e,t){let n=t.ranges.find(t=>En(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,r){return r.values.map(r=>{if(!r.startsWith(`=`))return nc(r,R);let i=lU(r),a=this.getters.getTranslatedCellFormula(e,n.col,n.row,i.tokens);return this.getters.evaluateFormula(e,a,t)})}},xG=class extends RW{static getters=[`getRowSize`,`getHeaderSize`,`getMaxAnchorOffset`];tallestCellInRow={};ctx=Sl();beforeHandle(e){switch(e.type){case`ADD_COLUMNS_ROWS`:if(e.dimension===`COL`)return;let t=gt(e.position,e.base),n=Array(e.quantity).fill(void 0),r=kt(this.tallestCellInRow[e.sheetId],n,t);this.history.update(`tallestCellInRow`,e.sheetId,r);break}}handle(e){switch(e.type){case`START`:case`UPDATE_LOCALE`:for(let e of this.getters.getSheetIds())this.initializeSheet(e);break;case`CREATE_SHEET`:this.initializeSheet(e.sheetId);break;case`DUPLICATE_SHEET`:{let t=b(this.tallestCellInRow[e.sheetId]);this.history.update(`tallestCellInRow`,e.sheetIdTo,t);break}case`DELETE_SHEET`:let t={...this.tallestCellInRow};delete t[e.sheetId],this.history.update(`tallestCellInRow`,t);break;case`REMOVE_COLUMNS_ROWS`:{if(e.dimension===`COL`)return;let t=Ot(this.tallestCellInRow[e.sheetId],e.elements);this.history.update(`tallestCellInRow`,e.sheetId,t);break}case`RESIZE_COLUMNS_ROWS`:{let t=e.sheetId;if(e.dimension===`ROW`)for(let n of e.elements){let e=this.getRowTallestCell(t,n);this.history.update(`tallestCellInRow`,t,n,e)}else for(let n of S(0,this.getters.getNumberRows(t)))for(let r of e.elements)this.updateRowSizeForCellChange(t,n,r)}break;case`SET_FORMATTING`:if(e.style&&(`fontSize`in e.style||`wrapping`in e.style||`rotation`in e.style))for(let t of e.target)this.updateRowSizeForZoneChange(e.sheetId,t);break;case`UPDATE_CELL`:this.updateRowSizeForCellChange(e.sheetId,e.row,e.col);break;case`ADD_MERGE`:case`REMOVE_MERGE`:for(let t of e.target)for(let n of jn(t))this.updateRowSizeForCellChange(e.sheetId,n.row,n.col)}}getRowSize(e,t){return Math.round(this.getters.getUserRowSize(e,t)??this.tallestCellInRow[e][t]?.size??23)}getMaxAnchorOffset(e,t,n){let{numberOfRows:r,numberOfCols:i}=this.getters.getSheetSize(e),a=0;for(;a<t&&r>0;r--)a+=this.getRowSize(e,r-1);let o=0;for(;o<n&&i>0;i--)o+=this.getters.getColSize(e,i-1);return{col:i,row:r,offset:{x:o-n,y:a-t}}}getHeaderSize(e,t,n){return this.getters.isHeaderHidden(e,t,n)?0:t===`ROW`?this.getRowSize(e,n):this.getters.getColSize(e,n)}updateRowSizeForZoneChange(e,t){for(let n=t.top;n<=t.bottom;n++){let t=this.getRowTallestCell(e,n);this.history.update(`tallestCellInRow`,e,n,t)}}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.getCellStyle(e),r=this.getters.getColSize(e.sheetId,e.col);return Cl(this.ctx,t,n,this.getters.getLocale(),r)}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 SG=`0.00%`;function CG(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=ch[e.aggregator];if(!r)return{value:0};try{return r([n],this.getters.getLocale())}catch(t){return Sy(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}=bL(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new ha:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}if(r.find(t=>t.nameWithGranularity===e)){let{rowDomain:n}=bL(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new ha:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}return this.getPivotCellValueAndFormat(e,t)});return xa(a)?a[0][0]:a}getValuesToAggregate(e,t){let{rowDomain:n,colDomain:r}=bL(this,t),i=super.getExpandedTableStructure(),a=[];if(r.length===0&&n.length<this.definition.rows.length&&this.definition.rows.length&&this.definition.columns.length){let t=this.treeToLeafDomains(i.getColTree()),r=this.getSubTreeMatchingDomain(i.getRowTree(),n),o=this.treeToLeafDomains(r);for(let r of t)for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t).concat(r)));return a}else if(n.length===this.definition.rows.length&&r.length===0){let t=i.getColTree(),o=this.getSubTreeMatchingDomain(t,r),s=this.treeToLeafDomains(o,r);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else if(n.length===this.definition.rows.length&&r.length&&r.length<this.definition.columns.length){let t=this.getSubTreeMatchingDomain(i.getColTree(),r),o=this.treeToLeafDomains(t,r);for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else{let t=i.getRowTree(),o=this.getSubTreeMatchingDomain(t,n),s=this.treeToLeafDomains(o,n);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,t.concat(r)));return a}}getSubTreeMatchingDomain(e,t,n=0){if(n>t.length)return[];if(t.length===n)return e;for(let r of e){let e=_h(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:A.NotAvailable,message:k(`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 Sy(e,`COMPUTE_MEASURE_DISPLAY_VALUE`)}}asPercentOfGrandTotal(e,t){let n=this.getGrandTotal(t.id);return n===0?{value:A.DivisionByZero}:{value:this.measureValueToNumber(e)/n,format:SG}}asPercentOfRowTotal(e,t,n){let r=this.getRowTotal(t.id,n);return r===0?{value:A.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:SG}}asPercentOfColumnTotal(e,t,n){let r=this.getColumnTotal(t.id,n);return r===0?{value:A.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:SG}}asPercentOfParentRowTotal(e,t,n){let r=vL(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:SG}}asPercentOfParentColumnTotal(e,t,n){let r=yL(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:SG}}asPercentOfParentTotal(e,t,n,r){let{fieldNameWithGranularity:i}=r;if(!i)return e;if(!OL(i,n))return{value:``};let a=EL(this,i,n),o=this._getPivotCellValueAndFormat(t.id,a),s=this.measureValueToNumber(o);return s===0?{value:``}:{value:this.measureValueToNumber(e)/s,format:SG}}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:A.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}=bL(this,n),u=jL(l),d=jL(c);return{value:s[u]?.[d]??``,format:i===`running_total`?e.format:SG}}asPercentOf(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!OL(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0||o===`sameValue`&&s===0?{value:A.DivisionByZero}:!o||o===`sameValue`&&!s?{value:``}:o===`sameValue`?{value:1,format:SG}:s===void 0?{value:A.NullError}:{value:s/o,format:SG}}asDifferenceFrom(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!OL(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(!OL(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0?{value:A.DivisionByZero}:!o||o===`sameValue`?{value:``}:s===void 0?{value:A.NullError}:{value:(s-o)/o,format:SG}}asRank(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;if(!OL(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}=bL(this,n),u=jL(l),d=jL(c);return{value:s[u]?.[d]??``}}computeRank(e,t,n){let r={},i=kL(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=qa(o));for(let s of o){let o=jL(xL(this,a,s[0].domain)),c=s.map(t=>({...t,value:this.strictMeasureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain)),rowDomain:xL(this,i,t.domain)})).filter(e=>OL(t,e.rowDomain)),l=Object.groupBy(c,e=>NL(e.rowDomain,t));for(let e in l)l[e]=Lt(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=jL(xL(this,i,e.domain)),a=l[NL(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:Rt(r)}computeRunningTotal(e,t,n){let r={},i=kL(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=qa(o));for(let s of o){let o=jL(xL(this,a,s[0].domain));r[o]={};let c={},l=s.map(t=>({...t,rowDomain:xL(this,i,t.domain),value:this.measureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain))})).filter(e=>OL(t,e.rowDomain));for(let e of l){let n=jL(e.rowDomain),i=PL(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=jL(n),a=PL(n,t),s=r[o][i]||0,l=c[a];r[o][i]=l?s/l:void 0}}return i===`row`?r:Rt(r)}getGrandTotal(e){let t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){let n=bL(this,t).rowDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}getColumnTotal(e,t){let n=bL(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)`?AL(this,t,n,r):DL(t,n,r);if(w(i,t))return`sameValue`;if(!i||!CL(this,i))throw new ha;let a=this._getPivotCellValueAndFormat(e.id,i);return this.strictMeasureValueToNumber(a)}getPivotValueCells(e){return this.getCollapsedTableStructure().getPivotCells().map(t=>t.filter(t=>t.type===`VALUE`&&t.measure===e)).filter(e=>e.length>0)}measureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(!e.value)return 0;throw Error(`Value ${e.value} is not a number`)}strictMeasureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(e.value)throw Error(`Value ${e.value} is not a number`)}getCollapsedTableStructure(){let e=super.getCollapsedTableStructure();return this.sortTableStructure(e),e}getExpandedTableStructure(){let e=super.getExpandedTableStructure();return this.sortTableStructure(e),e}sortTableStructure(e){if(!this.definition.sortedColumn||e.isSorted)return;let t=this.definition.sortedColumn.measure;Th(this.definition.sortedColumn,this)&&e.sort(t,this.definition.sortedColumn,(e,t)=>this._getPivotCellValueAndFormat(e,t))}}return t}let wG=[`ADD_PIVOT`,`UPDATE_PIVOT`,`REMOVE_PIVOT`];function TG(e){return wG.includes(e.type)}var EG=class extends RW{static getters=[`getPivot`,`getFirstPivotFunction`,`getPivotCellSortDirection`,`getPivotIdFromPosition`,`getPivotIdsFromPosition`,`getPivotCellFromPosition`,`generateNewCalculatedMeasureName`,`isPivotUnused`,`isSpillPivotFormula`];pivots={};unusedPivotsInFormulas;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(Ps.has(e.type))for(let e of this.getters.getPivotIds())this.setupPivot(e,{recreate:!0});switch(e.type){case`REFRESH_PIVOT`:this.refreshPivot(e.id);break;case`ADD_PIVOT`:this.setupPivot(e.pivotId);break;case`DUPLICATE_PIVOT`:this.setupPivot(e.newPivotId);break;case`UPDATE_PIVOT`:this.setupPivot(e.pivotId,{recreate:!0});break;case`DELETE_SHEET`:case`UPDATE_CELL`:this.unusedPivotsInFormulas=void 0;break;case`UNDO`:case`REDO`:{this.unusedPivotsInFormulas=void 0;let t=e.commands.filter(TG);for(let e of t){let t=e.pivotId;this.getters.isExistingPivot(t)&&this.setupPivot(t,{recreate:!0})}break}case`UPDATE_LOCALE`:Rh();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(C)}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=DU(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=yB(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||OU(t.compiledFormula.tokens)===0)return BL;let n=this.getters.getCellPosition(t.id),r=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(!r)return BL;let{functionName:i,args:a}=r,o=a[0];if(!o)return BL;let s=this.getters.getPivotId(o.toString());if(!s)return BL;let c=this.getPivot(s);if(!c.isValid()||i===`PIVOT`&&!t.content.replaceAll(` `,``).toUpperCase().startsWith(`=PIVOT`))return BL;try{if(i===`PIVOT`){let t=Nh(this.getters.getPivotCoreDefinition(s),mm(a[1]),mm(a[2]),mm(a[3]),mm(a[4]),mm(a[5]),this.getters.getLocale()),r=c.getCollapsedTableStructure().getPivotCells(t),i=e.col-n.col,o=e.row-n.row;return r[i][o]}let t=e.row-n.row,r=e.col-n.col;if(a=a.map(e=>xa(e)?e[r][t]:e),i===`PIVOT.HEADER`&&a.at(-2)===`measure`)return{type:`MEASURE_HEADER`,domain:c.parseArgsToPivotDomain(a.slice(1,-2).map(e=>({value:e}))),measure:a.at(-1)?.toString()||``};if(i===`PIVOT.HEADER`){let e=c.parseArgsToPivotDomain(a.slice(1).map(e=>({value:e})));return{type:`HEADER`,domain:e,dimension:bL(c,e).colDomain.length?`COL`:`ROW`}}let[o,...l]=a.slice(1);return{type:`VALUE`,domain:c.parseArgsToPivotDomain(l.map(e=>({value:e}))),measure:o?.toString()||``}}catch{return BL}}generateNewCalculatedMeasureName(e){let t=e.map(e=>e.fieldName);return zt(k(`Calculated measure 1`),t,{compute:(e,t)=>k(`Calculated measure %s`,t)})}getPivot(e){if(!this.getters.isExistingPivot(e))throw Error(`pivot ${e} not found`);return this.pivots[e]}isPivotUnused(e){let{type:t}=this.getters.getPivot(e);return this._getUnusedPivotsInFormulas().includes(e)&&ZL.get(t).isPivotUnused(this.getters,e)}getPivotCellSortDirection(e){let t=this.getters.getPivotIdFromPosition(e),n=this.getters.getPivotCellFromPosition(e);if(n.type===`EMPTY`||n.type===`HEADER`||!t)return;let r=this.getters.getPivot(t),i=bL(r,n.domain).colDomain,a=r.definition.sortedColumn;return a?.measure===n.measure&&w(a.domain,i)?a.order:`none`}refreshPivot(e){this.getters.getPivot(e).init({reload:!0})}setupPivot(e,{recreate:t}={recreate:!1}){let n=b(this.getters.getPivotCoreDefinition(e));if(e in this.pivots)t&&this.pivots[e].onDefinitionChange(n);else{let t=CG(ZL.get(n.type).ui);this.pivots[e]=new t(e,this.custom,{definition:n,getters:this.getters})}}_getUnusedPivotsInFormulas(){if(this.unusedPivotsInFormulas!==void 0)return this.unusedPivotsInFormulas;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.unusedPivotsInFormulas=[],[]}for(let t of this.getters.getPivotIds()){let n=this.getters.getPivot(t);for(let r of n.definition.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.unusedPivotsInFormulas=[],[]}}return this.unusedPivotsInFormulas=[...e],this.unusedPivotsInFormulas}},DG=class{getters;dispatch;constructor(e,t){this.getters=e,this.dispatch=t}copy(e,t,n=`copyPaste`){}paste(e,t,n){}isPasteAllowed(e,t,n,r){return`Success`}isCutAllowed(e){return`Success`}getPasteTarget(e,t,n,r){return{zones:[],sheetId:e}}convertTextToClipboardData(e){}},OG=class extends DG{copy(e,t,n=`copyPaste`){}pasteFromCopy(e,t,n,r){if(t.length===1)for(let i of rA(t,n))this.pasteZone(e,i.left,i.top,n,r);else for(let i of Qt(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){}},kG=class extends OG{isCutAllowed(e){return e.zones.length===1?`Success`:`WrongCutSelection`}copy(e,t,n=`copyPaste`){let r=e.sheetId,{clippedZones:i,rowsIndexes:a,columnsIndexes:o}=e,s=[],c=a.length===1&&o.length===1;for(let t of a){let i=[];for(let s of o){let l={col:s,row:t,sheetId:r},u=this.getters.getCell(l),d=this.getters.getEvaluatedCell(l),f=this.getters.getPivotIdFromPosition(l),p=this.getters.getArrayFormulaSpreadingOn(l);if(n!==`shiftCells`&&f&&p){let t=this.getters.getSpreadZone(p);if((!w(p,l)||!c)&&t&&!e.zones.some(e=>Dn(t,e))){let e=this.getters.getPivotCellFromPosition(l),t=gh(this.getters.getPivotFormulaId(f),e);u={id:u?.id||``,format:u?.format,content:t,isFormula:!1,parsedValue:d.value}}}else if(n!==`shiftCells`&&p&&!w(p,l)){let e=a.includes(p.row)&&o.includes(p.col)?``:z(d.value,{locale:this.getters.getLocale()});u={id:u?.id||``,format:d.format,content:e,isFormula:!1,parsedValue:d.value}}i.push({content:u?.content??``,format:u?.format,tokens:u?.isFormula?u.compiledFormula.tokens.map(({value:e,type:t})=>({value:e,type:t})):[],border:this.getters.getCellBorder(l)||void 0,evaluatedCell:d,position:l})}s.push(i)}return{cells:s,zones:i,sheetId:e.sheetId}}isPasteAllowed(e,t,n,r){if(!n.cells)return`Success`;if(r?.isCutOperation&&r?.pasteOption!==void 0)return`WrongPasteOption`;if(t.length>1&&(n.cells.length>1||n.cells[0].length>1))return`WrongPasteSelection`;let i=n.cells.length,a=n.cells[0].length;for(let r of rA(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:rA(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(`
|
|
117
|
+
`).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=qv(e[n]||``,t);r.push({content:i,evaluatedCell:{formattedValue:i}})}n.cells.push(r)}return n}},AG=class extends cb{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===On(r).numberOfRows){this.notifyRowsRemovedAndRemaining(0,a);return}let o=i.map(e=>({left:r.left,top:e,right:r.right,bottom:e})),s=new kG(this.getters,this.dispatch),c=s.copy(tA(n,o),!1);if(!c)return;this.dispatch(`CLEAR_CELLS`,{target:[r],sheetId:n});let l={left:r.left,top:r.top,right:r.left,bottom:r.top};s.paste({zones:[l],sheetId:n},c,{isCutOperation:!1});let u={left:r.left,top:r.top-+!!t,right:r.right,bottom:r.top+a-1};this.selection.selectZone({cell:{col:u.left,row:u.top},zone:u});let d=r.bottom-r.top+1-a;this.notifyRowsRemovedAndRemaining(d,a)}getUniqueRowsIndexes(e,t,n,r){let i=new Map;for(let a of S(t,n+1)){let t=r.map(t=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:a}).value);Object.values(i).some(e=>w(e,t))||(i[a]=t)}return Object.keys(i).map(e=>parseInt(e))}notifyRowsRemovedAndRemaining(e,t){this.ui.notifyUI({type:`info`,text:k(`%s duplicate rows found and removed.
|
|
118
|
+
%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=Qt(this.getters.getSelectedZones()),t=this.getters.getActiveSheetId(),n=0;for(let{col:r,row:i}of e.map(jn).flat()){let e=this.getters.getCell({col:r,row:i,sheetId:t});if(!e)continue;let a=jt(e.content);a!==e.content&&(n+=1,this.dispatch(`UPDATE_CELL`,{sheetId:t,col:r,row:i,content:a}))}let r=n?k(`Trimmed whitespace from %s cells.`,n):k(`No selected cells had whitespace trimmed.`);this.ui.notifyUI({type:`info`,text:r,sticky:!1})}};let jG=new B;jG.add(`ALPHANUMERIC_INCREMENT_MODIFIER`,{apply:(e,t)=>{e.current+=e.increment;let n=Math.abs(e.current).toString();n=`0`.repeat(Math.max(e.numberPostfixLength-n.length,0))+n;let r=`${e.prefix}${n}`;return{cellData:{border:t.border,style:t.style,format:t.cell&&t.cell.format,content:r},tooltip:{props:{content:r}}}}}).add(`INCREMENT_MODIFIER`,{apply:(e,t,n)=>{e.current+=e.increment;let r=e.current.toString(),i=n.getLocale(),a=z(e.current,{format:t.cell?.format,locale:i});return{cellData:{border:t.border,style:t.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:a}}:void 0}}}).add(`DATE_INCREMENT_MODIFIER`,{apply:(e,t,n)=>{let r=I(e.current,n.getLocale());r.setFullYear(r.getFullYear()+e.increment.years||0),r.setMonth(r.getMonth()+e.increment.months||0),r.setDate(r.getDate()+e.increment.days||0);let i=Fi(r);e.current=i;let a=n.getLocale(),o=z(i,{format:t.cell?.format,locale:a});return{cellData:{border:t.border,style:t.style,format:t.cell&&t.cell.format,content:i.toString()},tooltip:i?{props:{content:o}}:void 0}}}).add(`COPY_MODIFIER`,{apply:(e,t,n)=>{let r=t.cell?.content||``,i={locale:n.getLocale(),format:t.cell?.format};return{cellData:{border:t.border,style:t.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:t.cell?tc(t.cell,i).formattedValue:``}}:void 0}}}).add(`FORMULA_MODIFIER`,{apply:(e,t,n,r)=>{e.current+=e.increment;let i=0,a=0;switch(r){case`up`:i=0,a=-e.current;break;case`down`:i=0,a=e.current;break;case`left`:i=-e.current,a=0;break;case`right`:i=e.current,a=0;break}let o=t.cell;if(!o||!o.isFormula)return{cellData:{}};let s=t.sheetId,c=n.getTranslatedCellFormula(s,i,a,o.compiledFormula.tokens);return{cellData:{border:t.border,style:t.style,format:o.format,content:c},tooltip:c?{props:{content:c}}:void 0}}});let MG=new B,NG=/(\d+)$/,PG=/^(.*\D+)/,FG=/^(.*\D+)(\d+)$/,IG=/^0*/;function LG(e,t,n){let r=[],i=!1;for(let a of t){a===e&&(i=!0);let t=a===void 0||a.isFormula?void 0:tc(a,{locale:R,format:a.format});if(t&&n(t))r.push(t);else{if(i)return r;r=[]}}return r}function RG(e){let t=[],n=e[0];for(let r=1;r<e.length;r++){let i=e[r];t.push(i-n),n=i}return t.reduce((e,t)=>e+t,0)/t.length}function zG(e){let t=1;return e.length>=2&&(t=RG(e)*e.length),t}function BG(e){return e.length<2?e[0]||{years:0,months:0,days:0}:e.every(t=>t.years===e[0].years&&t.months===e[0].months&&t.days===e[0].days)?e[0]:void 0}function VG(e){if(e.length<2)return 1;let t=e.map(e=>I(e,R)),n=BG(HG(t));if(n===void 0)return;let r=Object.values(n).filter(e=>e!==0).length===1,i=Object.values(n).every(e=>e===0);if(!r||i){let n=t.map((e,n)=>{if(n===0)return 0;let r=t[n-1];return Math.floor(e.getTime())-Math.floor(r.getTime())}).slice(1);if(n.every(e=>e===n[0]))return e.length*(e[1]-e[0])}return{years:n.years*e.length,months:n.months*e.length,days:n.days*e.length}}MG.add(`simple_value_copy`,{condition:(e,t)=>t.length===1&&!e.isFormula&&!(e.format&&ns(e.format)),generateRule:()=>({type:`COPY_MODIFIER`}),sequence:10}).add(`increment_alphanumeric_value`,{condition:e=>!e.isFormula&&tc(e,{locale:R}).type===`text`&&FG.test(e.content),generateRule:(e,t,n)=>{let r=parseInt(e.content.match(NG)[0]),i=e.content.match(PG)[0],a=LG(e,t,e=>e.type===`text`&&FG.test(e.value)).filter(e=>i===(e.value??``).toString().match(PG)[0]).map(e=>(e.value??``).toString().match(NG)[0]),o=a.reduce((e,t)=>{let n=t.match(IG)[0].length;return n>e[1]?[t,n]:e},[a[0],0]),s=o[1]?o[0].length:0,c=zG(a.map(e=>parseInt(e)));return[`up`,`left`].includes(n)&&a.length===1&&(c=-c),{type:`ALPHANUMERIC_INCREMENT_MODIFIER`,prefix:i,current:r,increment:c,numberPostfixLength:s}},sequence:15}).add(`copy_text`,{condition:e=>!e.isFormula&&tc(e,{locale:R}).type===`text`,generateRule:()=>({type:`COPY_MODIFIER`}),sequence:20}).add(`update_formula`,{condition:e=>e.isFormula,generateRule:(e,t)=>({type:`FORMULA_MODIFIER`,increment:t.length,current:0}),sequence:30}).add(`increment_dates`,{condition:(e,t)=>!e.isFormula&&tc(e,{locale:R}).type===`number`&&!!e.format&&ns(e.format),generateRule:(e,t)=>{let n=VG(LG(e,t,e=>e.type===`number`&&!!e.format&&ns(e.format)).map(e=>Number(e.value)));if(n===void 0)return{type:`COPY_MODIFIER`};let r=tc(e,{locale:R});return typeof n==`object`?{type:`DATE_INCREMENT_MODIFIER`,increment:n,current:r.type===`number`?r.value:0}:{type:`INCREMENT_MODIFIER`,increment:n,current:r.type===`number`?r.value:0}},sequence:25}).add(`increment_number`,{condition:e=>!e.isFormula&&tc(e,{locale:R}).type===`number`,generateRule:(e,t,n)=>{let r=LG(e,t,e=>e.type===`number`&&!ns(e.format||``)).map(e=>Number(e.value)),i=zG(r);[`up`,`left`].includes(n)&&r.length===1&&(i=-i);let a=tc(e,{locale:R});return{type:`INCREMENT_MODIFIER`,increment:i,current:a.type===`number`?a.value:0}},sequence:40});function HG(e){return e.length<2?[{years:0,months:0,days:0}]:e.map((t,n)=>{if(n===0)return{years:0,months:0,days:0};let r=O.fromTimestamp(e[n-1].getTime()),i=Ui(r,t),a=Vi(r,t)%12;return r.setFullYear(r.getFullYear()+i),r.setMonth(r.getMonth()+a),{years:i,months:a,days:Hi(r,t)}}).slice(1)}var UG=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}=jG.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}}}},WG=class extends cb{static layers=[`Autofill`];static getters=[`getAutofillTooltip`];autofillZone;steps;lastCellSelected={};direction;tooltip;allowDispatch(e){switch(e.type){case`AUTOFILL_SELECT`:let t=this.getters.getActiveSheetId();return this.lastCellSelected.col=e.col===-1?this.lastCellSelected.col:x(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=e.row===-1?this.lastCellSelected.row:x(e.row,0,this.getters.getNumberRows(t)),this.lastCellSelected.col!==void 0&&this.lastCellSelected.row!==void 0?`Success`:`InvalidAutofillSelection`}return`Success`}handle(e){switch(e.type){case`AUTOFILL`:this.autofill(!0);break;case`AUTOFILL_SELECT`:this.select(e.col,e.row);break;case`AUTOFILL_AUTO`:this.autofillAuto();break}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||this.direction===void 0){this.tooltip=void 0;return}let t=this.getters.getSelectedZone(),n=this.autofillZone,r=[];switch(this.direction){case`down`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.top;n<=t.bottom;n++)i.push(T(e,n));let a=this.createGenerator(i);for(let t=n.top;t<=n.bottom;t++)r.push(this.computeNewCell(a,e,t))}break;case`up`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.bottom;n>=t.top;n--)i.push(T(e,n));let a=this.createGenerator(i);for(let t=n.bottom;t>=n.top;t--)r.push(this.computeNewCell(a,e,t))}break;case`left`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.right;n>=t.left;n--)i.push(T(n,e));let a=this.createGenerator(i);for(let t=n.right;t>=n.left;t--)r.push(this.computeNewCell(a,t,e))}break;case`right`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.left;n<=t.right;n++)i.push(T(n,e));let a=this.createGenerator(i);for(let t=n.left;t<=n.right;t++)r.push(this.computeNewCell(a,t,e))}break}if(e){let e={},t={},n={},i=this.getters.getActiveSheetId();for(let a of r)this.collectBordersData(a,e),this.autofillMerge(i,a),this.autofillCell(i,a),this.collectConditionalFormatsData(i,a,t),this.collectDataValidationsData(i,a,n);this.autofillBorders(i,e),this.autofillConditionalFormats(i,t),this.autofillDataValidations(i,n),this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0}}collectBordersData(e,t){let n=JSON.stringify(e.border);n in t||(t[n]=[]),t[n].push(E({col:e.col,row:e.row}))}collectConditionalFormatsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s=this.getters.getRulesByCell(e,r,i),c=T(a,o);for(let e of s)e.id in n||(n[e.id]=[]),n[e.id].push(c)}collectDataValidationsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s={sheetId:e,col:r,row:i},c=this.getters.getValidationRuleForCell(s);c&&(c.id in n||(n[c.id]=[]),n[c.id].push(E({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:Qt(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(un),[]);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=Qt(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(En(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=MG.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}=Zt(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,a=this.getters.getCellStyle(e);t.push({data:{...e,border:r,style:a},rule:n})}return new UG(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([]))}},GG=class extends cb{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}=En(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)||kn(bn(a,t))?[{position:{col:r,row:i},zone:a}]:this.sumDimensions(e,bn(a,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,n){let r=this.getters.getSheet(e),i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.findSuitableZoneToSum(r,i.col,i.row);if(a)return this.getters.expandZone(e,a)}findSuitableZoneToSum(e,t,n){let r=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:n-1}),i=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:n});if(this.isNumber(i)&&!this.isNumber(r))return this.findHorizontalZone(e,t,n);let a=this.findVerticalZone(e,t,n);if(this.isZoneValid(a))return a;let o=this.findHorizontalZone(e,t,n);if(this.isZoneValid(o))return o}findVerticalZone(e,t,n){let r={top:0,bottom:n-1,left:t,right:t},i=this.reduceZoneStart(e,r,r.bottom);return{...r,top:i}}findHorizontalZone(e,t,n){let r={top:n,bottom:n,left:0,right:t-1},i=this.reduceZoneStart(e,r,r.right);return{...r,left:i}}reduceZoneStart(e,t,n){let r=this.getters.getEvaluatedCellsInZone(e.id,t),i=S(n,-1,-1),a=Pt(i.filter(e=>r[e]&&!r[e].isAutoSummable)),o=Ze(i.filter(e=>this.isNumber(r[e])))[0]||[];return Pt(o)<a?1/0:Ft(o)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===`number`&&!(e.format&&ns(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 kn(t)?(n.add(On(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)},jn(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)},jn(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`))}},KG=class extends cb{static getters=[`getCellTableStyle`,`getCellTableBorder`,`getCellTableBorderZone`,`getCellTableStyleZone`];tableStyles={};handle(e){if(Ps.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tableStyles={};return}if(JG(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]}getCellTableStyleZone(e,t){let n=new bF;for(let r of this.getters.getTablesOverlappingZones(e,[t])){let t=this.tableStyles[e][r.id]().styles;for(let r of Object.keys(t)){let i=t[r],a=parseInt(r);for(let t of Object.keys(i)){let r=i[t];r&&n.set({sheetId:e,col:a,row:parseInt(t)},r)}}}return n}getCellTableBorder(e){let t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().borders[e.col]?.[e.row]}getCellTableBorderZone(e,t){let n=new bF;for(let r of this.getters.getTablesOverlappingZones(e,[t])){let t=this.tableStyles[e][r.id]().borders;for(let r of Object.keys(t)){let i=t[r],a=parseInt(r);for(let t of Object.keys(i)){let r=i[t];r&&n.set({sheetId:e,col:a,row:parseInt(t)},r)}}}return n}computeTableStyle(e,t){return mt(()=>{let{config:n,numberOfCols:r,numberOfRows:i}=this.getTableRuntimeConfig(e,t),a=nI(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 qG=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 JG(e){return qG.has(e.type)}var YG=class extends cb{static getters=[`getCellComputedBorder`,`getCellComputedStyle`];styles=new bF;borders=new bF;handle(e){if(Ps.has(e.type)||e.type===`UPDATE_CELL`||e.type===`SET_FORMATTING`||e.type===`CLEAR_FORMATTING`||e.type===`ADD_DATA_VALIDATION_RULE`||e.type===`REMOVE_DATA_VALIDATION_RULE`||e.type===`EVALUATE_CELLS`){this.styles=new bF,this.borders=new bF;return}if(JG(e)){`sheetId`in e?(this.styles.clearSheet(e.sheetId),this.borders.clearSheet(e.sheetId)):(this.styles=new bF,this.borders=new bF);return}if(Ls.has(e.type)){this.styles=new bF;return}if(Rs.has(e.type)){this.borders=new bF;return}}getCellComputedBorder(e){let t=this.borders.get(e);return t===void 0&&(t=this.computeCellBorder(e),this.borders.set(e,t)),t}getCellComputedStyle(e,t){let n=this.styles.get(e);return n===void 0&&(this.precomputeCellStyle(e.sheetId,t??E(e)),n=this.styles.get(e)??{}),n}precomputeCellStyle(e,t){let n=this.getters.getCellStyleInZone(e,t),r=this.getters.getCellTableStyleZone(e,t);for(let i=t.left;i<=t.right;i++)for(let a=t.top;a<=t.bottom;a++){let t={sheetId:e,col:i,row:a};if(this.styles.get(t)!==void 0)continue;let o={...bt(r.get(t)),...bt(this.getters.getDataValidationCellStyle(t)),...bt(n.get(t)),...bt(this.getters.getCellConditionalFormatStyle(t))};this.getters.getEvaluatedCell(t).link&&!o.textColor&&(o.textColor=`#017E84`),this.styles.set(t,o)}}computeCellBorder(e){let t=this.getters.getCellBorder(e)||{},n={...bt(this.getters.getCellTableBorder(e)||{}),...bt(t)};return ut(n)?null:n}},XG=class extends cb{static getters=[`hasBooleanValidationInZones`];handle(e){switch(e.type){case`TOGGLE_CHECKBOX`:this.toggleCheckbox(e.sheetId,e.target);break}}hasBooleanValidationInZones(e){let t=this.getters.getActiveSheetId();for(let n of e)for(let e=n.left;e<=n.right;e++)for(let r=n.top;r<=n.bottom;r++)if(this.getters.isCellValidCheckbox({col:e,row:r,sheetId:t}))return!0;return!1}toggleCheckbox(e,t){for(let n of t)for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++){let n={col:t,row:r,sheetId:e};if(this.getters.isCellValidCheckbox(n)){let e=this.getters.getEvaluatedCell(n).value?`FALSE`:`TRUE`;this.dispatch(`UPDATE_CELL`,{...n,content:e})}}}};let ZG=new class extends B{addTransformation(e,t,n){this.content[e]||(this.content[e]=new Map);for(let r of t)this.content[e].set(r,n);return this}getTransformation(e,t){return this.content[t]&&this.content[t].get(e)}},QG=new class extends B{add(e,t){return super.add(e,t),this}replace(e,t){return super.replace(e,t),this}get(e){return this.content[e]}};ZG.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],dK),ZG.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],dK),ZG.addTransformation(`DELETE_SHEET`,[`MOVE_RANGES`],nK),ZG.addTransformation(`DELETE_FIGURE`,[`UPDATE_FIGURE`,`UPDATE_CHART`,`UPDATE_CAROUSEL`],rK),ZG.addTransformation(`DELETE_CHART`,[`UPDATE_CHART`],iK),ZG.addTransformation(`DELETE_CHART`,[`UPDATE_CAROUSEL`],aK),ZG.addTransformation(`CREATE_SHEET`,[`CREATE_SHEET`],oK),ZG.addTransformation(`ADD_MERGE`,[`ADD_MERGE`,`REMOVE_MERGE`],sK),ZG.addTransformation(`ADD_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],cK),ZG.addTransformation(`REMOVE_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],cK),ZG.addTransformation(`ADD_COLUMNS_ROWS`,[`UPDATE_TABLE`],lK),ZG.addTransformation(`REMOVE_COLUMNS_ROWS`,[`UPDATE_TABLE`],lK),ZG.addTransformation(`REMOVE_TABLE_STYLE`,[`CREATE_TABLE`,`UPDATE_TABLE`],uK),ZG.addTransformation(`ADD_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],fK),ZG.addTransformation(`REMOVE_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],fK),ZG.addTransformation(`REMOVE_PIVOT`,[`RENAME_PIVOT`,`DUPLICATE_PIVOT`,`INSERT_PIVOT`,`UPDATE_PIVOT`],tK),ZG.addTransformation(`DELETE_SHEET`,[`ADD_PIVOT`,`UPDATE_PIVOT`],eK),ZG.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],$G),ZG.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],$G);function $G(e,t){if(e.pivot.type!==`SPREADSHEET`||e.pivot.dataSet?.sheetId!==t.sheetId)return e;let n=Qn(e.pivot.dataSet.zone,t),r=n?{...e.pivot.dataSet,zone:n}:void 0;return{...e,pivot:{...e.pivot,dataSet:r}}}function eK(e,t){return e.pivot.type===`SPREADSHEET`&&e.pivot.dataSet?.sheetId===t.sheetId?{...e,pivot:{...e.pivot,dataSet:void 0}}:e}function tK(e,t){if(e.pivotId!==t.pivotId)return e}function nK(e,t){let n=t.sheetId;if(!(e.targetSheetId===n||e.sheetId===n))return e}function rK(e,t){if(e.figureId!==t.figureId)return e}function iK(e,t){if(e.chartId!==t.chartId)return e}function aK(e,t){return{...e,definition:{...e.definition,items:e.definition.items.filter(e=>!(e.type===`chart`&&e.chartId===t.chartId))}}}function oK(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 sK(e,t){if(e.sheetId!==t.sheetId)return e;let n=[];for(let r of e.target)t.target.every(e=>!wn(r,e))&&n.push(r);if(n.length)return{...e,target:n}}function cK(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 lK(e,t){if(e.sheetId!==t.sheetId)return e;let n=Qn(e.zone,t);if(!n)return;let r=e.newTableRange?$n(e.newTableRange,t):void 0;return{...e,newTableRange:r,zone:n}}function uK(e,t){return e.config?.styleId===t.tableStyleId?{...e,config:{...e.config,styleId:SA.styleId}}:e}function dK(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n;if(t.type===`REMOVE_COLUMNS_ROWS`?n=hl(t.elements,[e.base])[0]:t.type===`ADD_COLUMNS_ROWS`&&(n=ml(gt(t.position,t.base),t.quantity,[e.base])[0]),n!==void 0)return{...e,base:n}}function fK(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n=S(e.start,e.end+1),r=[];if(t.type===`REMOVE_COLUMNS_ROWS`?r=hl(t.elements,n):t.type===`ADD_COLUMNS_ROWS`&&(r=ml(gt(t.position,t.base),t.quantity,n)),r.length!==0)return{...e,start:Math.min(...r),end:Math.max(...r)}}function pK(e,t){let n=e.content&&Wu(e.sheetId,e.content,t);return{...e,content:n}}QG.add(`UPDATE_CELL`,pK);function mK(e,t){let n=e.cf.rule;if(e={...e,cf:{...e.cf}},n.type===`CellIsRule`)e.cf.rule={...n,values:n.values.map(n=>Wu(e.sheetId,n,t))};else if(n.type===`ColorScaleRule`){let{minimum:r,maximum:i,midpoint:a}=n;e.cf.rule={...n,minimum:{...r,value:r.value&&Wu(e.sheetId,r.value,t)},maximum:{...i,value:i.value&&Wu(e.sheetId,i.value,t)},midpoint:a?{...a,value:Wu(e.sheetId,a.value,t)}:void 0}}else if(n.type===`IconSetRule`){let{upperInflectionPoint:r,lowerInflectionPoint:i}=n;e.cf.rule={...n,upperInflectionPoint:{...r,value:Wu(e.sheetId,r.value,t)},lowerInflectionPoint:{...i,value:Wu(e.sheetId,i.value,t)}}}else n.type===`DataBarRule`&&(e.cf.rule={...n,rangeValues:n.rangeValues?Gu(e.sheetId,n.rangeValues,t).range:void 0});return e}QG.add(`ADD_CONDITIONAL_FORMAT`,mK);function hK(e,t){return e={...e,rule:{...e.rule,criterion:{...e.rule.criterion}}},e.rule.criterion.values=e.rule.criterion.values.map(n=>Wu(e.sheetId,n,t)),e}QG.add(`ADD_DATA_VALIDATION_RULE`,hK);function gK(e,t){return e=b(e),e.pivot.measures.map(e=>{e.computedBy&&(e.computedBy.formula=Wu(e.computedBy.sheetId,e.computedBy.formula,t))}),e}QG.add(`ADD_PIVOT`,gK),QG.add(`UPDATE_PIVOT`,gK),QG.add(`CREATE_CHART`,_K),QG.add(`UPDATE_CHART`,_K);function _K(e,t){return{...e,definition:__(e.sheetId,e.definition,t)}}let vK=[{match:Os,fn:CK},{match:As,fn:wK},{match:Ns,fn:TK},{match:Ms,fn:OK},{match:ks,fn:DK},{match:js,fn:EK}];function yK(e,t){let n=ZG.getTransformation(e.type,t.type),r=n?n(e,t):SK(e,t);return r&&bK(r,t)}function bK(e,t){let n=QG.get(e.type);if(!n)return e;let r=nl(t);return r?n(e,r):e}function xK(e,t){let n=[...e],r=new Set(ZG.getKeys());for(let e of t)(r.has(e.type)||rl.contains(e.type))&&(n=n.reduce((t,n)=>{let r=yK(n,e);return r&&t.push(r),t},[]));return n}function SK(e,t){for(let{match:n,fn:r}of vK)if(n(e)){let n=r(e,t);if(n===`SKIP_TRANSFORMATION`)continue;if(n===`IGNORE_COMMAND`)return;e=n}return e}function CK(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 wK(e,t){let n=CK(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=[];for(let n of e.target){let e=Qn(n,t);e&&r.push(e)}return r.length?{...e,target:r}:`IGNORE_COMMAND`}function TK(e,t){let n=CK(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=Qn(e.zone,t);return r?{...e,zone:r}:`IGNORE_COMMAND`}function EK(e,t){if(!(`sheetId`in t))return e;let n=e.ranges.map(e=>$n(e,t)).filter(C);return n.length?{...e,ranges:n}:`IGNORE_COMMAND`}function DK(e,t){let n=CK(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=hl(t.elements,e.elements):t.type===`ADD_COLUMNS_ROWS`&&(r=ml(gt(t.position,t.base),t.quantity,e.elements)),r.length===0?`IGNORE_COMMAND`:{...e,elements:r}}function OK(e,t){let n=CK(e,t);return n===`SKIP_TRANSFORMATION`?t.type===`ADD_COLUMNS_ROWS`||t.type===`REMOVE_COLUMNS_ROWS`?kK(e,t):t.type===`ADD_MERGE`?AK(e,t):`SKIP_TRANSFORMATION`:n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e}function kK(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 AK(e,t){for(let n of t.target)if(!(e.col===n.left&&e.row===n.top)&&En(e.col,e.row,n))return`IGNORE_COMMAND`;return e}var jK=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}},MK=class extends Error{},NK=class extends er{revisions;transportService;serverRevisionId;clients={};clientId=`local`;debouncedMove;pendingMessages=[];awaitingClientPosition;waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;uuidGenerator=new Gl;lastLocalOperation;constructor(e,t,n=Ee){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=n,this.debouncedMove=dt(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,n){if(!t.length||!n.length||!this.canApplyOptimisticUpdate())return;let r=new jK(this.uuidGenerator.uuidv4(),this.clientId,t,e,n,Date.now());this.revisions.append(r.id,r),e.type!==`REQUEST_REDO`&&(this.lastLocalOperation=r),this.trigger(`new-local-state-update`,{id:r.id}),this.sendUpdateMessage({type:`REMOTE_REVISION`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:r.id,clientId:r.clientId,commands:r.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_UNDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_REDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}move(e){this.debouncedMove(e)}join(e){e?(this.clients[e.id]=e,this.clientId=e.id):(this.clients.local={id:`local`,name:`local`},this.clientId=`local`),this.transportService.onNewMessage(this.clientId,this.onMessageReceived.bind(this)),this.awaitingClientPosition&&=(this._move(this.awaitingClientPosition),void 0)}loadInitialMessages(e){let t=performance.now(),n=e.reduce((e,t)=>e+(t.type===`REMOTE_REVISION`?t.commands.length:1),0);this.isReplayingInitialRevisions=!0;for(let t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1,console.debug(`Replayed`,n,`commands in`,performance.now()-t,`ms`)}async leave(e){e&&Object.keys(this.clients).length===1&&this.lastRevisionMessage&&this.lastRevisionMessage?.type!==`SNAPSHOT_CREATED`&&await this.snapshot(e()),delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.sendToTransport({type:`CLIENT_LEFT`,clientId:this.clientId,version:1})}async snapshot(e){if(this.pendingMessages.length!==0)return;let t=this.uuidGenerator.uuidv4();await this.sendToTransport({type:`SNAPSHOT`,nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getCurrentClient(){return this.getClient(this.clientId)}getClient(e){let t=this.clients[e];if(!t)throw new MK(`The client left the session`);return t}getConnectedClients(){return new Set(Object.values(this.clients).filter(C))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return this.pendingMessages.length===0}getLastLocalNonEmptyRevision(){return this.lastLocalOperation}_move(e){if(!this.clients[this.clientId]){this.awaitingClientPosition=e;return}let t=this.clients[this.clientId]?.position;if(t?.col===e.col&&t.row===e.row&&t.sheetId===e.sheetId)return;let n=t?`CLIENT_MOVED`:`CLIENT_JOINED`,r=this.getCurrentClient();this.clients[this.clientId]={...r,position:e},this.sendToTransport({type:n,version:1,client:{...r,position:e}}).then(()=>{this.pendingMessages.length>0&&!this.waitingAck&&this.sendPendingMessage()})}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 jK(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:xK(n,t)})}break;case`SNAPSHOT_CREATED`:{let t=new jK(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.sendToTransport({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()}async sendToTransport(e){return this.transportService.sendMessage(e)}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.
|
|
119
|
+
${JSON.stringify(e)}`);this.waitingAck=!0,this.sendToTransport({...e,serverRevisionId:this.serverRevisionId}).catch(e=>{if(!(e instanceof MK))throw e.cause||e;this.waitingAck=!1})}}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`)}},PK=class extends cb{static getters=[`getClientsToDisplay`,`getClient`,`getCurrentClient`,`getConnectedClients`,`isFullySynchronized`];static layers=[`Selection`];colors=new ni(12);session;constructor(e){super(e),this.session=e.session}isPositionValid(e){return e.row<this.getters.getNumberRows(e.sheetId)&&e.col<this.getters.getNumberCols(e.sheetId)}getClient(e){return this.session.getClient(e)}getCurrentClient(){return this.session.getCurrentClient()}getConnectedClients(){return[...this.session.getConnectedClients()].map(e=>({...e,color:this.colors.get(e.id)}))}isFullySynchronized(){return this.session.isFullySynchronized()}getClientsToDisplay(){try{this.getters.getCurrentClient()}catch(e){if(e instanceof MK)return[];throw e}let e=this.getters.getActiveSheetId(),t=[];for(let n of this.getters.getConnectedClients())n.id!==this.getters.getCurrentClient().id&&n.position&&n.position.sheetId===e&&this.isPositionValid(n.position)&&t.push({...n,position:n.position});return t}drawLayer(e){if(this.getters.isDashboard())return;let{ctx:t,thinLineWidth:n}=e,r=this.getters.getActiveSheetId();for(let e of this.getClientsToDisplay()){let{row:i,col:a}=e.position,o=this.getters.expandZone(r,{top:i,bottom:i,left:a,right:a}),{x:s,y:c,width:l,height:u}=this.getters.getVisibleRect(o);if(l<=0||u<=0)continue;let d=e.color;t.fillStyle=`${d}10`,t.lineWidth=4*n,t.strokeStyle=d,t.globalCompositeOperation=`multiply`,t.fillRect(s,c,l,u),t.globalCompositeOperation=`source-over`,t.strokeRect(s,c,l,u),t.font=`bold ${Ce+1}px ${we}`}}},FK=class extends cb{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 Qc(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=(xa(r)?r[0][0]:r)?.toString()}else n=t.content;(!n||!$e(n))&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}else n.type!==`boolean`&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}}}}},IK=class extends cb{static getters=[`dynamicTranslate`];dynamicTranslate(e){return e}},LK=class extends cb{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 Qt(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=Qt(r.map(E));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:Qt(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 Qt(t))for(let t of jn(i)){let i=this.getCellNumberFormat({sheetId:e,...t});if(i!==void 0){let e=ys(i,n);r[e]=r[e]||[],r[e].push(t)}}for(let t in r){let n=Qt(r[t].map(e=>E(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&&ns(e.format)))return e.format||os(e.value)}}},RK=class extends cb{static getters=[`getGeoJsonFeatures`,`geoFeatureNameToId`,`getGeoChartAvailableRegions`];geoJsonService;geoJsonCache={};constructor(e){super(e),this.geoJsonService=e.external.geoJsonService}getGeoChartAvailableRegions(){return this.geoJsonService?this.geoJsonService.getAvailableRegions()||[]:(console.error(`No geoJsonService provided to the model`),[])}getGeoJsonFeatures(e){if(!this.geoJsonService){console.error(`No geoJsonService provided to the model`);return}let t=this.geoJsonCache[e];if(!(t instanceof Promise)){if(t!==void 0)return t??void 0;this.geoJsonCache[e]=new Promise(async t=>{let n=await this.geoJsonService?.getTopoJson(e);this.geoJsonCache[e]=this.convertToGeoJson(n),this.dispatch(`EVALUATE_CHARTS`),t()})}}geoFeatureNameToId(e,t){if(!this.geoJsonService){console.error(`No geoJsonService provided to the model`);return}return this.geoJsonService.geoFeatureNameToId(e,t)}convertToGeoJson(e){if(!e)return null;if(e.type===`Topology`){let t=globalThis.ChartGeo.topojson.feature(e,Object.values(e.objects)[0]);return t.type===`FeatureCollection`?t.features:[t]}else if(e.type===`FeatureCollection`)return e.features;throw Error(`Invalid TopoJSON`)}},zK=class extends cb{static getters=[`getNextVisibleCellPosition`,`findVisibleHeader`,`findLastVisibleColRowIndex`,`findFirstVisibleColRowIndex`,`isRowHidden`,`isColHidden`,`isHeaderHidden`];isRowHidden(e,t){return this.getters.isRowHiddenByUser(e,t)||this.getters.isRowFiltered(e,t)}isColHidden(e,t){return this.getters.isColHiddenByUser(e,t)}isHeaderHidden(e,t,n){return t===`COL`?this.isColHidden(e,n):this.isRowHidden(e,n)}getNextVisibleCellPosition({sheetId:e,col:t,row:n}){return{sheetId:e,col:this.findVisibleHeader(e,`COL`,t,this.getters.getNumberCols(e)-1),row:this.findVisibleHeader(e,`ROW`,n,this.getters.getNumberRows(e)-1)}}findVisibleHeader(e,t,n,r){if(n<=r){for(let i=n;i<=r;i++)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}if(n>r){for(let i=n;i>=r;i--)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}}findLastVisibleColRowIndex(e,t,{last:n,first:r}){return S(n,r,-1).find(n=>!this.isHeaderHidden(e,t,n))||r}findFirstVisibleColRowIndex(e,t){let n=this.getters.getNumberHeaders(e,t);for(let r=0;r<n;r++)if(t===`COL`&&!this.isColHidden(e,r)||t===`ROW`&&!this.isRowHidden(e,r))return r}exportForExcel(e){for(let t of e.sheets)for(let[e,n]of Object.entries(t.rows))n.isHidden=this.isRowHidden(t.id,Number(e))}},BK=class extends cb{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){Vn(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:k(`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:k(`Pivot #%(formulaId)s`,{formulaId:i}),position:r}),this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:n,sheetIdTo:t});let a=this.getters.getPivot(e);this.insertPivotWithTable(t,0,0,e,a.getCollapsedTableStructure().export(),`dynamic`)}duplicatePivotInNewSheet(e,t,n){this.dispatch(`DUPLICATE_PIVOT`,{pivotId:e,newPivotId:t,duplicatedPivotName:k(`%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(k(`%(newPivotName)s (Pivot #%(formulaId)s)`,{newPivotName:o,formulaId:a})),position:i}).isSuccessful){this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:r,sheetIdTo:n});let i=this.getters.getPivot(e);this.insertPivotWithTable(n,0,0,t,i.getCollapsedTableStructure().export(),`dynamic`)}}getPivotDuplicateSheetName(e){let t=this.getters.getSheetIds().map(e=>this.getters.getSheetName(e));return zt(Xe(e),t)}insertPivotWithTable(e,t,n,r,i,a){let{cols:o,rows:s,measures:c,fieldsType:l}=i,u=new zL(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:{...Le,numberOfHeaders:d}})}resizeSheet(e,t,n,r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:s-l,position:`after`})}splitPivotFormula(e,t,n,r){let i=this.getters.getSpreadZone({sheetId:e,col:t,row:n});if(!i)return;let a=this.getters.getPivotFormulaId(r),o=new Map;for(let t=i.left;t<=i.right;t++)for(let n=i.top;n<=i.bottom;n++){let r={sheetId:e,col:t,row:n};o.set(r,this.getters.getPivotCellFromPosition(r))}for(let[e,t]of o)this.dispatch(`UPDATE_CELL`,{...e,content:gh(a,t)});if(this.getters.getCoreTable({sheetId:e,col:t,row:n})?.type===`dynamic`){let r=E({col:t,row:n}),a=this.getters.getRangeDataFromZone(e,i);this.dispatch(`UPDATE_TABLE`,{sheetId:e,zone:r,newTableRange:a,tableType:`static`})}}};let VK=new B,HK=new B;function UK(e,t){if(t&&VK.contains(t.type))return VK.get(t.type)(e,t)}function WK(e,t,n){if(HK.contains(t.type))return HK.get(t.type)(e,t,n)}function GK(e){return!e||!e.rootCommand||typeof e.rootCommand!=`object`?!1:Hs(e.rootCommand)?VK.contains(e.rootCommand.type):HK.contains(e.rootCommand.type)}function KK(e,t){if(!(!e.rootCommand||typeof e.rootCommand!=`object`))return Hs(e.rootCommand)?UK(t,e.rootCommand):WK(t,e.rootCommand,e.commands)}var qK=class extends cb{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=KK(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:GK(this.getPossibleRevisionToRepeat())}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}getPossibleRevisionToRepeat(){return this.session.getLastLocalNonEmptyRevision()}},JK=class{trackedValues=new Set;domainToArray(e){return e.flatMap(e=>[e.field,P(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)}},YK=class extends cb{static getters=[`getPivotPresenceTracker`];trackPresencePivotId;tracker;handle(e){switch(e.type){case`PIVOT_START_PRESENCE_TRACKING`:this.tracker=new JK,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}}},XK=class extends cb{allowDispatch(e){switch(e.type){case`SORT_CELLS`:return En(e.col,e.row,e.zone)?this.checkValidations(e,this.checkMerge,this.checkMergeSizes,this.checkArrayFormulaInSortZone):`InvalidSortAnchor`}return`Success`}handle(e){switch(e.type){case`SORT_CELLS`:this.sortZone(e.sheetId,e,e.zone,e.sortDirection,e.sortOptions||{});break}}checkMerge({sheetId:e,zone:t}){return this.getters.doesIntersectMerge(e,t)&&jn(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=>wn(e,t)),r=On(n[0]),[i,a]=[r.numberOfCols,r.numberOfRows];return n.every(e=>{let[t,n]=[e.right-e.left+1,e.bottom-e.top+1];return t===i&&n===a})?`Success`:`InvalidSortZone`}checkArrayFormulaInSortZone({sheetId:e,zone:t}){return jn(t).some(({col:t,row:n})=>{let r=this.getters.getArrayFormulaSpreadingOn({sheetId:e,col:t,row:n});return r&&!w(r,{sheetId:e,col:t,row:n})})?`SortZoneWithArrayFormulas`:`Success`}hasHeader(e,t){if(t[0].length===1)return!1;let n=t.map(t=>t.map(({col:t,row:n})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).type));return n[0][0]===`empty`&&(n=n.slice(1)),n.some(e=>e[0]===`empty`)?!1:!!n.some(e=>e[1]!==`empty`&&e[0]!==e[1])}sortZone(e,t,n,r,i){let[a,o]=this.mainCellsSteps(e,n),s=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,c=Object.assign({},n),l=this.mainCells(e,n);!i.sortHeaders&&this.hasHeader(e,l)&&(c.top+=o),l=this.mainCells(e,c);let u=l[s-c.left],d=Hw(u.map(e=>this.getters.getEvaluatedCell(e)),r,!!i.emptyCellAsZero).map(e=>e.index),[f,p]=[l.length,l[0].length],m=[];for(let t=0;t<f;t++)for(let n=0;n<p;n++){let r=l[t][d[n]],i=this.getters.getCell(r),s=this.getters.getCellStyle(r),u=c.left+t*a,f=c.top+n*o,p={sheetId:r.sheetId,col:u,row:f,content:``};if(i){let t=i.content;if(i.isFormula){let n=this.getters.getCellPosition(i.id);t=this.getters.getTranslatedCellFormula(e,0,f-n.row,i.compiledFormula.tokens)}p.style=s,p.content=t,p.format=i.format}m.push(p)}m.forEach(e=>this.dispatch(`UPDATE_CELL`,e))}mainCellsSteps(e,t){let n=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[n?n.right-n.left+1:1,n?n.bottom-n.top+1:1]}mainCells(e,t){let[n,r]=this.mainCellsSteps(e,t),i=[],a=S(t.left,t.right+1,n),o=S(t.top,t.bottom+1,r);for(let t of a){let n=[];i.push(n);for(let r of o)n.push({sheetId:e,col:t,row:r})}return i}},ZK=class extends cb{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[`
|
|
120
|
+
`,`;`,`,`,` `,`.`])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}),c=this.getters.getCellStyle({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:Wv(n,this.getters.getLocale()),format:``,style:{...PW,...c}})}}getSplittedCols(e,t){if(!t)throw Error(`Separator cannot be empty`);let n=this.getters.getActiveSheetId(),r=[];for(let i of S(e.top,e.bottom+1)){let a=this.getters.getEvaluatedCell({sheetId:n,col:e.left,row:i}).formattedValue;r.push(this.splitAndRemoveTrailingEmpty(a,t))}return r}splitAndRemoveTrailingEmpty(e,t){let n=e.split(t);for(;n.length>1&&n[n.length-1]===``;)n.pop();return n}willSplittedColsOverwriteContent(e,t){let n=this.getters.getActiveSheetId();for(let r of S(e.top,e.bottom+1)){let i=t[r-e.top];for(let t=1;t<i.length;t++){let i=this.getters.getCell({sheetId:n,col:e.left+t,row:r});if(i&&i.content)return!0}}return!1}removeMergesInSplitZone(e,t){let n=this.getters.getActiveSheetId(),r=Math.max(...t.map(e=>e.length)),i={...e,right:e.left+r-1},a=this.getters.getMergesInZone(n,i);this.dispatch(`REMOVE_MERGE`,{sheetId:n,target:a})}addColsToAvoidCollisions(e,t){let n=this.getters.getActiveSheetId(),r=0;for(let i of S(e.top,e.bottom+1)){let a={sheetId:n,col:e.left,row:i},o=t[i-e.top],s=this.getColsToAddToAvoidCollision(a,o);r=Math.max(r,s)}r&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:e.left,sheetId:n,sheetName:this.getters.getSheetName(n),quantity:r,position:`after`})}getColsToAddToAvoidCollision(e,t){let n=t.length;for(let t=1;t<n;t++){let r=e.col+t,i=this.getters.getCell({...e,col:r});if(i&&i.content)return n-t}return 0}addColumnsToNotOverflowSheet(e,t){let n=this.getters.getActiveSheetId(),r=Math.max(...t.map(e=>e.length-1)),i=this.getters.getNumberCols(n)-1;e.left+r>i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:i,sheetId:n,sheetName:this.getters.getSheetName(n),quantity:e.left+r-i,position:`after`})}checkSingleColSelected(){return this.getters.isSingleColSelected()?`Success`:`MoreThanOneColumnSelected`}checkNonEmptySelector(e){return e.separator===``?`EmptySplitSeparator`:`Success`}checkNotOverwritingContent(e){if(e.addNewColumns||e.force)return`Success`;let t=this.getters.getSelectedZones()[0],n=this.getSplittedCols(t,e.separator);return this.willSplittedColsOverwriteContent(t,n)?`SplitWillOverwriteContent`:`Success`}checkSeparatorInSelection({separator:e}){let t=this.getters.getSelectedCells();for(let n of t)if(n.formattedValue.includes(e))return`Success`;return`NoSplitSeparatorInSelection`}},QK=class extends cb{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=QF(t.range.zone,t.config);if(a&&En(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)}},$K=class extends cb{allowDispatch(e){switch(e.type){case`RESIZE_TABLE`:let t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return`TableNotFound`;let n=t.range.zone,r=this.getters.getRangeFromRangeData(e.newTableRange).zone;return r.top!==n.top||r.left!==n.left?`InvalidTableResize`:this.canDispatch(`UPDATE_TABLE`,{...e}).reasons}return`Success`}handle(e){switch(e.type){case`RESIZE_TABLE`:{let t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(this.dispatch(`UPDATE_TABLE`,{...e}),!t)return;let n=this.getters.getRangeFromRangeData(e.newTableRange).zone;if(this.selection.selectCell(n.right,n.bottom),!t.config.automaticAutofill)return;let r=t.range.zone;if(n.bottom>=r.bottom){for(let t=n.left;t<=n.right;t++){let i={col:t,row:r.bottom,sheetId:e.sheetId};this.getters.getCell(i)?.content.startsWith(`=`)&&this.dispatch(`AUTOFILL_TABLE_COLUMN`,{...i,autofillRowStart:r.bottom,autofillRowEnd:n.bottom})}break}}}}},eq=class extends cb{static getters=[`shouldShowFormulas`];showFormulas=!1;handle(e){switch(e.type){case`SET_FORMULA_VISIBILITY`:this.showFormulas=e.show;break}}shouldShowFormulas(){return this.showFormulas}},tq=class extends cb{static getters=[`getCellWidth`,`getTextWidth`,`getCellText`,`getCellMultiLineText`,`getMultilineTextSize`,`getContiguousZone`,`computeTextYCoordinate`];ctx=Sl();allowDispatch(e){return this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e)}handle(e){switch(e.type){case`AUTORESIZE_COLUMNS`:for(let t of e.cols){let n=this.getColMaxWidth(e.sheetId,t);n!==0&&this.dispatch(`RESIZE_COLUMNS_ROWS`,{elements:[t],dimension:`COL`,size:n,sheetId:e.sheetId})}break;case`AUTORESIZE_ROWS`:this.autoResizeRows(e.sheetId,e.rows);break;case`DELETE_UNFILTERED_CONTENT`:let t=[];for(let n of e.target){let r=Ze(S(n.top,n.bottom+1).filter(t=>!this.getters.isRowFiltered(e.sheetId,t)));for(let e of r)t.push({...n,top:e[0],bottom:e[e.length-1]})}this.dispatch(`DELETE_CONTENT`,{sheetId:e.sheetId,target:t});break}}getCellWidth(e){let t=this.getters.getCellComputedStyle(e),n=0,r=this.getters.getEvaluatedCell(e).formattedValue;if(r){let e=Il(this.ctx,r,t,void 0);n+=El(this.ctx,e,t).width}for(let t of this.getters.getCellIcons(e))n+=t.margin+t.size;if(this.getters.getDataValidationChipStyle(e)&&(n+=10),n===0)return 0;if(n+=8,t.wrapping===`wrap`){let t=this.getters.getColSize(this.getters.getActiveSheetId(),e.col);return Math.min(t,n)}return n}getTextWidth(e,t){return Dl(this.ctx,e,t)}getMultilineTextSize(e,t){return El(this.ctx,e,t)}getCellText(e,t){let n=this.getters.getCell(e),r=this.getters.getLocale();if(t?.showFormula&&n?.isFormula)return Yv(n.content,r);if(t?.showFormula&&!n?.content)return``;{let n=this.getters.getCellStyle(e),i=this.getters.getEvaluatedCell(e),a=t?.availableWidth?{availableWidth:t.availableWidth,measureText:e=>Dl(this.ctx,e,n||{})}:void 0;return z(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 Il(this.ctx,r,n,t.wrapText?t.maxWidth:void 0)}computeTextYCoordinate(e,t,n=xe,r=1){let i=e.y+1,a=xl(t,r);if(e.height>a+8){if(n===`middle`)return Math.ceil(i+(e.height-a)/2);if(n===`bottom`)return i+e.height-a-4}return i+4}getContiguousZone(e,t){let n=t=>{for(let n of S(t.left,t.right+1)){if(!this.isCellEmpty({sheetId:e,col:n,row:t.top-1}))return{...t,top:t.top-1};if(!this.isCellEmpty({sheetId:e,col:n,row:t.bottom+1}))return{...t,bottom:t.bottom+1}}for(let n of S(t.top,t.bottom+1)){if(!this.isCellEmpty({sheetId:e,col:t.left-1,row:n}))return{...t,left:t.left-1};if(!this.isCellEmpty({sheetId:e,col:t.right+1,row:n}))return{...t,right:t.right+1}}return t},r=!1,i=t;do{r=!1;let e=n(i);Cn(i,e)||(r=!0,i=e)}while(r);return i}isCellEmpty(e){let t=this.getters.getMainCellPosition(e);return this.getters.getEvaluatedCell(t).type===`empty`}getColMaxWidth(e,t){let n=jn(this.getters.getColsZone(e,t,t)).map(t=>this.getCellWidth({sheetId:e,...t}));return Math.max(0,Pt(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,i;for(let[n,a]of this.getters.getEvaluatedCellsPositionInZone(e,this.getters.getRowsZone(e,r,r))){if(a.value===void 0)continue;let r=this.getters.getColSize(e,n.col),o=this.getters.getCellStyle(n),s=a.formattedValue,c=wl(this.ctx,s,o,r);c>t&&c>23&&(t=c,i=n)}let a=i&&this.getters.getCell(i);a&&!a.isFormula&&(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})}},nq=class extends cb{static getters=[`getSelectedCarouselItem`,`getChartFromFigureId`,`getChartIdFromFigureId`];uuidGenerator=new Gl;carouselStates={};allowDispatch(e){switch(e.type){case`ADD_FIGURE_CHART_TO_CAROUSEL`:return!this.getters.doesCarouselExist(e.carouselFigureId)||this.getters.getFigure(e.sheetId,e.chartFigureId)?.tag!==`chart`?`InvalidFigureId`:`Success`;case`DUPLICATE_CAROUSEL_CHART`:return!this.getters.doesCarouselExist(e.carouselId)||!this.getters.getCarousel(e.carouselId).items.some(t=>t.type===`chart`&&t.chartId===e.chartId)||this.getters.getChart(e.duplicatedChartId)?`InvalidFigureId`:`Success`;case`ADD_NEW_CHART_TO_CAROUSEL`:return this.getters.doesCarouselExist(e.figureId)?`Success`:`InvalidFigureId`;case`UPDATE_CAROUSEL_ACTIVE_ITEM`:return this.getters.doesCarouselExist(e.figureId)?this.getters.getCarousel(e.figureId).items.some(t=>w(t,e.item))?`Success`:`InvalidCarouselItem`:`InvalidFigureId`}return`Success`}handle(e){switch(e.type){case`ADD_NEW_CHART_TO_CAROUSEL`:this.addNewChartToCarousel(e.figureId,e.sheetId);break;case`ADD_FIGURE_CHART_TO_CAROUSEL`:this.addFigureChartToCarousel(e.carouselFigureId,e.chartFigureId,e.sheetId);break;case`DUPLICATE_CAROUSEL_CHART`:this.duplicateCarouselChart(e);break;case`UPDATE_CAROUSEL_ACTIVE_ITEM`:this.carouselStates[e.figureId]=this.getCarouselItemId(e.item);break;case`POPOUT_CHART_FROM_CAROUSEL`:this.popOutChartFromCarousel(e.carouselId,e.chartId,e.sheetId);break;case`DELETE_FIGURE`:delete this.carouselStates[e.figureId];break;case`UPDATE_CAROUSEL`:this.fixWrongCarouselState(e.figureId);break;case`DELETE_CHART`:case`UNDO`:case`REDO`:case`DELETE_SHEET`:for(let e in this.carouselStates)this.fixWrongCarouselState(e);break}}popOutChartFromCarousel(e,t,n){let r=this.getters.getCarousel(e);if(!r)return;let i=this.getters.getFigure(n,e),a=this.getters.getChartDefinition(t);if(!a||!i)return;let o=this.getters.getFigureUI(n,i),s=this.getters.getPositionAnchorOffset({x:o.x+50,y:o.y+50}),c=this.uuidGenerator.smallUuid();this.dispatch(`CREATE_CHART`,{...s,chartId:this.uuidGenerator.smallUuid(),figureId:c,sheetId:n,size:{width:i.width,height:i.height},definition:{...a}});let l=r.items.filter(e=>e.type!==`chart`||e.chartId!==t);this.dispatch(`UPDATE_CAROUSEL`,{sheetId:n,figureId:e,definition:{...r,items:l}}),this.dispatch(`SELECT_FIGURE`,{figureId:c})}getSelectedCarouselItem(e){let t=this.getters.getCarousel(e);if(t.items.length)return this.carouselStates[e]?t.items.find(t=>this.getCarouselItemId(t)===this.carouselStates[e]):t.items[0]}getChartFromFigureId(e){if(!this.getters.getFigureSheetId(e))return;let t=this.getChartIdFromFigureId(e);return t?this.getters.getChart(t):void 0}getChartIdFromFigureId(e){let t=this.getters.getFigureSheetId(e);if(!t)return;let n=this.getters.getFigure(t,e);if(!(!n||n.tag!==`chart`&&n.tag!==`carousel`)){if(n.tag===`carousel`){let t=this.getSelectedCarouselItem(e);return t?.type===`chart`?t.chartId:void 0}return this.getters.getChartIds(t).find(t=>this.getters.getFigureIdFromChartId(t)===e)}}fixWrongCarouselState(e){if(!this.getters.doesCarouselExist(e)){delete this.carouselStates[e];return}let t=this.getters.getCarousel(e);t.items.length===0?delete this.carouselStates[e]:this.carouselStates[e]&&t.items.some(t=>this.getCarouselItemId(t)===this.carouselStates[e])||(this.carouselStates[e]=this.getCarouselItemId(t.items[0]))}addNewChartToCarousel(e,t){let n=this.getters.getCarousel(e),r=this.uuidGenerator.smallUuid();this.dispatch(`CREATE_CHART`,{chartId:r,figureId:e,sheetId:t,definition:q_});let i={...n,items:[...n.items,{type:`chart`,chartId:r}]};this.dispatch(`UPDATE_CAROUSEL`,{sheetId:t,figureId:e,definition:i})}addFigureChartToCarousel(e,t,n){let r=this.getChartIdFromFigureId(t);if(!r)return;let i=this.getters.getCarousel(e),a={...i,items:[...i.items,{type:`chart`,chartId:r}]};this.dispatch(`UPDATE_CAROUSEL`,{sheetId:n,figureId:e,definition:a}),this.dispatch(`UPDATE_CHART`,{sheetId:n,chartId:r,figureId:e,definition:this.getters.getChartDefinition(r)}),this.dispatch(`DELETE_FIGURE`,{sheetId:n,figureId:t})}duplicateCarouselChart({carouselId:e,chartId:t,sheetId:n,duplicatedChartId:r}){let i=this.getters.getChart(t);if(!i)return;let a=this.getters.getCarousel(e),o=a.items.findIndex(e=>e.type===`chart`&&e.chartId===t);if(o===-1)return;this.dispatch(`CREATE_CHART`,{chartId:r,figureId:e,sheetId:n,definition:i.getDefinition()});let s=kt(a.items,[{type:`chart`,chartId:r}],o+1);this.dispatch(`UPDATE_CAROUSEL`,{sheetId:n,figureId:e,definition:{...a,items:s}})}getCarouselItemId(e){return e.type===`chart`?e.chartId:`carouselDataView`}};async function rq(e){return new Promise((t,n)=>{let r=new Image;r.addEventListener(`load`,()=>{let e=document.createElement(`canvas`);e.width=r.width,e.height=r.height,e.getContext(`2d`)?.drawImage(r,0,0),e.toBlob(t,`image/png`)}),r.addEventListener(`error`,n),r.src=e})}var iq=class extends cb{static layers=[`Clipboard`];static getters=[`getClipboardTextAndImageContent`,`getClipboardId`,`getClipboardTextContent`,`isCutOperation`];status=`invisible`;originSheetId;copiedData;_isCutOperation=!1;clipboardId=new Gl().uuidv4();fileStore;uuidGenerator;constructor(e){super(e),this.fileStore=e.external.fileStore,this.uuidGenerator=new Gl}allowDispatch(e){switch(e.type){case`CUT`:let t=this.getters.getSelectedZones();return this.isCutAllowedOn(t);case`PASTE_FROM_OS_CLIPBOARD`:{let t=this.convertTextToClipboardData(e.clipboardContent.text??``),n=e.pasteOption;return this.isPasteAllowed(e.target,t,{pasteOption:n,isCutOperation:!1})}case`PASTE`:{if(!this.copiedData)return`EmptyClipboard`;let t=e.pasteOption;return this.isPasteAllowed(e.target,this.copiedData,{pasteOption:t,isCutOperation:this._isCutOperation})}case`COPY_PASTE_CELLS_ABOVE`:{let e=this.getters.getSelectedZones();if(e.length>1||e[0].top===0&&e[0].bottom===0)return`InvalidCopyPasteSelection`;break}case`COPY_PASTE_CELLS_ON_LEFT`:{let e=this.getters.getSelectedZones();if(e.length>1||e[0].left===0&&e[0].right===0)return`InvalidCopyPasteSelection`;break}case`INSERT_CELL`:{let{cut:t,paste:n}=this.getInsertCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);return this.isPasteAllowed(n,r,{isCutOperation:!0})}case`DELETE_CELL`:{let{cut:t,paste:n}=this.getDeleteCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);return this.isPasteAllowed(n,r,{isCutOperation:!0})}}return`Success`}handle(e){switch(e.type){case`COPY`:case`CUT`:let t=this.getters.getSelectedZones();this.status=`visible`,this.originSheetId=this.getters.getActiveSheetId(),this._isCutOperation=e.type===`CUT`,this.copiedData=this.copy(t);break;case`PASTE_FROM_OS_CLIPBOARD`:{this._isCutOperation=!1;let t=e.clipboardContent;if(t.data?.version!==iP()&&(t={...t},delete t.data),t.imageData){let n=this.getters.getActiveSheetId(),r=this.uuidGenerator.uuidv4(),i=t.imageData,a=L_(this.getters,i.size);this.dispatch(`CREATE_IMAGE`,{definition:i,size:a,col:e.target[0].left,row:e.target[0].top,offset:{x:0,y:0},sheetId:n,figureId:r})}t.data?this.copiedData=t.data:this.copiedData=this.convertTextToClipboardData(t.text??``);let n=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:n,selectTarget:!0,isCutOperation:!1}),this.status=`invisible`,this.copiedData=void 0;break}case`PASTE`:{let t=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:t,selectTarget:!0,isCutOperation:this._isCutOperation}),this.status=`invisible`,this._isCutOperation&&=(this.copiedData=void 0,!1);break}case`COPY_PASTE_CELLS_ABOVE`:{let e=this.getters.getSelectedZone(),t=e.top!==e.bottom,n={...e,bottom:t?e.top:e.top-1,top:t?e.top:e.top-1};this.originSheetId=this.getters.getActiveSheetId();let r=this.copy([n]);this.paste([e],r,{isCutOperation:!1,selectTarget:!0})}break;case`COPY_PASTE_CELLS_ON_LEFT`:{let e=this.getters.getSelectedZone(),t=e.left!==e.right,n={...e,right:t?e.left:e.left-1,left:t?e.left:e.left-1};this.originSheetId=this.getters.getActiveSheetId();let r=this.copy([n]);this.paste([e],r,{isCutOperation:!1,selectTarget:!0})}break;case`CLEAN_CLIPBOARD_HIGHLIGHT`:this.status=`invisible`;break;case`DELETE_CELL`:{let{cut:t,paste:n}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!pn(t[0])){this.dispatch(`CLEAR_CELLS`,{target:[e.zone],sheetId:this.getters.getActiveSheetId()});break}let r=this.copy(t,`shiftCells`);this.paste(n,r,{isCutOperation:!0});break}case`INSERT_CELL`:{let{cut:t,paste:n}=this.getInsertCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);this.paste(n,r,{isCutOperation:!0});break}case`ADD_COLUMNS_ROWS`:if(this.status=`invisible`,!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;this.isColRowDirtyingClipboard(e.position===`before`?e.base:e.base+1,e.dimension)&&(this.copiedData=void 0);break;case`REMOVE_COLUMNS_ROWS`:if(this.status=`invisible`,!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;for(let t of e.elements)if(this.isColRowDirtyingClipboard(t,e.dimension)){this.copiedData=void 0;break}this.status=`invisible`;break;case`REPEAT_PASTE`:this.paste(e.target,this.copiedData,{isCutOperation:!1,pasteOption:e.pasteOption,selectTarget:!0});break;case`DELETE_SHEET`:if(!this._isCutOperation)return;this.originSheetId===e.sheetId&&(this.copiedData=void 0,this.status=`invisible`);break;default:Hs(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?BB.figureHandlers:BB.cellHandlers;return t.getKeys().map(e=>({handlerName:e,handler:new(t.get(e))(this.getters,this.dispatch)}))}isCutAllowedOn(e){let t=this.getClipboardData(e);for(let{handler:e}of this.selectClipboardHandlers(t)){let n=e.isCutAllowed(t);if(n!==`Success`)return n}return`Success`}isPasteAllowed(e,t,n){for(let{handler:r}of this.selectClipboardHandlers(t)){let i=r.isPasteAllowed(this.getters.getActiveSheetId(),e,t,{...n});if(i!==`Success`)return i}return`Success`}isColRowDirtyingClipboard(e,t){if(!this.copiedData||!this.copiedData.zones)return!1;let{zones:n}=this.copiedData;for(let r of n)if(t===`COL`&&e<=r.right||t===`ROW`&&e<=r.bottom)return!0;return!1}copy(e,t=`copyPaste`){let n={},r=this.getClipboardData(e);for(let{handlerName:e,handler:i}of this.selectClipboardHandlers(r)){let a=i.copy(r,this._isCutOperation,t);n[e]=a;for(let e of[`sheetId`,`cells`,`zones`,`figureId`])a&&e in a&&(n[e]=a[e])}return n}paste(e,t,n){if(!t)return;let r=this.getters.getActiveSheetId(),i=this.selectClipboardHandlers(t),{target:a,zone:o,selectedZones:s}=sA(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),oA(i,t,a,n),n?.selectTarget&&cA(this.selection,e,s)}addMissingDimensions(e,t,n,r,i){let a=n+i-this.getters.getNumberRows(e);a>0&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:this.getters.getNumberRows(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:a,position:`after`});let o=t+r-this.getters.getNumberCols(e);o>0&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:this.getters.getNumberCols(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:o,position:`after`})}getClipboardTextContent(){return this.getPlainTextContent()}getClipboardId(){return this.clipboardId}async getClipboardTextAndImageContent(){let e=await this.getImageContent(),t=e?.type,n={"text/plain":this.getPlainTextContent(),"text/html":await this.getHTMLContent()};return t&&e&&(n[t]=e),n}getSheetData(){let e={version:iP(),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(`
|
|
121
121
|
`)||` `}async getHTMLContent(){let e=``,t=this.copiedData?.cells;if(!t)if(this.copiedData?.figureId){let t=this.copiedData.figureId,n=this.getters.getFigureSheetId(t);e=this.getters.getFigure(n,t).tag===`image`?await this.craftImageHTML(t):` `}else e=` `;else if(t.length===1&&t[0].length===1)e=`${this.getters.getCellText(t[0][0].position)}`;else if(t[0][0]){let n=`<table border="1" style="border-collapse:collapse">`;for(let e of t){n+=`<tr>`;for(let t of e){if(!t)continue;let e=U(uv(this.getters.getCellComputedStyle(t.position))),r=this.getters.getCellText(t.position);n+=`<td style="${e}">`+EN(r)+`</td>`}n+=`</tr>`}n+=`</table>`,e=n}else return``;return`<div data-osheet-clipboard='${EN(JSON.stringify(this.getSheetData()))}'>${e}</div>`}readFileAsDataURL(e){return new Promise(t=>{let n=new FileReader;n.onload=()=>t(n.result),n.readAsDataURL(e)})}async craftImageHTML(e){if(!this.fileStore)return` `;let t=this.getters.getImage(e).path,n=await this.fileStore?.getFile(t)||null;return n?`<img src="${EN(await this.readFileAsDataURL(n))}" />`:` `}async getImageContent(){let e=this.copiedData?.figureId;if(!e)return;let t=this.getters.getFigureSheetId(e),n=this.getters.getFigure(t,e),r;if(n.tag===`image`){if(!this.fileStore)return;let t=this.getters.getImage(e).path;if(r=await this.fileStore?.getFile(t),r.type!==`image/png`){if(r.size>5242880){this.ui.notifyUI({text:k(`The file you are trying to copy is too large (>%sMB).
|
|
122
122
|
It will not be added to your OS clipboard.
|
|
123
|
-
You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=await nq(t)}}if(r)return r instanceof File?r:new File([r],`image.png`,{type:`image/png`})}isCutOperation(){return this._isCutOperation??!1}getDeleteCellsTargets(e,t){let n=this.getters.getActiveSheetId(),r;return r=t===`COL`?{...e,left:e.right+1,right:this.getters.getNumberCols(n)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(n)-1},{cut:[r],paste:[e]}}getInsertCellsTargets(e,t){let n=this.getters.getActiveSheetId(),r,i;return t===`COL`?(r={...e,right:this.getters.getNumberCols(n)-1},i={...e,left:e.right+1,right:e.right+1}):(r={...e,bottom:this.getters.getNumberRows(n)-1},i={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(n)-1}),{cut:[r],paste:[i]}}getClipboardData(e){let t=this.getters.getActiveSheetId(),n=this.getters.getSelectedFigureId();if(n)return{figureId:n,sheetId:t};let r=tA(t,e);return this._isCutOperation||(r.rowsIndexes=r.rowsIndexes.filter(e=>!this.getters.isRowFiltered(t,e))),r}drawLayer(e){if(this.status!==`visible`||!this.copiedData)return;let{sheetId:t,zones:n}=this.copiedData;if(t!==this.getters.getActiveSheetId()||!n||!n.length)return;let{ctx:r,thinLineWidth:i}=e;r.setLineDash([8,5]),r.strokeStyle=ae,r.lineWidth=3.3*i;for(let e of n){let{x:t,y:n,width:i,height:a}=this.getters.getVisibleRect(e);i>0&&a>0&&r.strokeRect(t,n,i,a)}}};let iq={filterType:`criterion`,type:`none`,values:[]};var aq=class extends cb{static getters=[`getFilterValue`,`getFilterHiddenValues`,`getFilterCriterionValue`,`getFirstTableInSelection`,`isRowFiltered`,`isFilterActive`];filterValues={};hiddenRows={};isEvaluationDirty=!1;allowDispatch(e){switch(e.type){case`UPDATE_FILTER`:if(!this.getters.getFilterId(e))return`FilterNotFound`;break}return`Success`}handle(e){switch(e.type){case`UNDO`:case`REDO`:case`UPDATE_CELL`:case`EVALUATE_CELLS`:case`ACTIVATE_SHEET`:case`REMOVE_TABLE`:case`ADD_COLUMNS_ROWS`:case`REMOVE_COLUMNS_ROWS`:case`UPDATE_TABLE`:this.isEvaluationDirty=!0;break;case`START`:for(let e of this.getters.getSheetIds())this.filterValues[e]={};break;case`CREATE_SHEET`:this.filterValues[e.sheetId]={};break;case`HIDE_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`GROUP_HEADERS`:case`UNGROUP_HEADERS`:case`FOLD_HEADER_GROUP`:case`UNFOLD_HEADER_GROUP`:case`FOLD_ALL_HEADER_GROUPS`:case`UNFOLD_ALL_HEADER_GROUPS`:case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:this.updateHiddenRows(e.sheetId);break;case`UPDATE_FILTER`:this.updateFilter(e),this.updateHiddenRows(e.sheetId);break;case`DUPLICATE_SHEET`:this.filterValues[e.sheetIdTo]=b(this.filterValues[e.sheetId]);break}}finalize(){if(this.isEvaluationDirty){for(let e of this.getters.getSheetIds())this.updateHiddenRows(e);this.isEvaluationDirty=!1}}isRowFiltered(e,t){return!!this.hiddenRows[e]?.has(t)}getFilterValue(e){let t=this.getters.getFilterId(e),n=e.sheetId;return t?this.filterValues[n]?.[t]:void 0}getFilterHiddenValues(e){let t=this.getters.getFilterId(e),n=e.sheetId;if(!t||!this.filterValues[n])return[];let r=this.filterValues[n][t]||[];return r.filterType===`values`?r.hiddenValues:[]}getFilterCriterionValue(e){let t=this.getters.getFilterId(e),n=e.sheetId;if(!t||!this.filterValues[n])return iq;let r=this.filterValues[n][t];return r&&r.filterType===`criterion`?r:iq}isFilterActive(e){let t=this.getters.getFilterId(e);if(!t)return!1;let n=e.sheetId,r=this.filterValues[n]?.[t];return r?r.filterType===`values`?r.hiddenValues.length>0:r.type!==`none`:!1}getFirstTableInSelection(){let e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZones();return this.getters.getTablesOverlappingZones(e,t)[0]}updateFilter({col:e,row:t,value:n,sheetId:r}){let i=this.getters.getFilterId({sheetId:r,col:e,row:t});i&&(this.filterValues[r]||(this.filterValues[r]={}),this.filterValues[r][i]=n)}updateHiddenRows(e){let t=this.getters.getFilters(e).sort((e,t)=>e.rangeWithHeaders.zone.top-t.rangeWithHeaders.zone.top),n=new Set;for(let r of t){let t=this.filterValues[e]?.[r.id],i=r.filteredRange?.zone;if(!(!t||!i||n.has(r.rangeWithHeaders.zone.top)||this.getters.isRowHiddenByUser(e,r.rangeWithHeaders.zone.top)))if(t.filterType===`values`){let a=t.hiddenValues?.map(Rl);if(!a)continue;let o=new Set(a);for(let t=i.top;t<=i.bottom;t++){let i=this.getCellValueAsString(e,r.col,t);o.has(i)&&n.add(t)}}else{if(t.type===`none`)continue;let a=W.get(t.type),o=t.values.map(t=>t.startsWith(`=`)?this.getters.evaluateFormula(e,t)??``:nc(t,R));if(o.some(gm))continue;let s={type:t.type,values:o.map(mm),dateValue:t.dateValue};for(let t=i.top;t<=i.bottom;t++){let i={sheetId:e,col:r.col,row:t},o=this.getters.getEvaluatedCell(i).value??``;a.isValueValid(o,s,this.getters,e)||n.add(t)}}}this.hiddenRows[e]=n}getCellValueAsString(e,t,n){return this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).formattedValue.toLowerCase()}exportForExcel(e){for(let t of e.sheets){let e=t.id;for(let n of t.tables){let r=un(n.range),i=[],a=[];for(let n of S(0,On(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?jn(c.filteredRange.zone).map(t=>this.getters.getEvaluatedCell({sheetId:e,...t}).formattedValue):[];if(s.length){let e=l.filter(e=>e).filter(e=>!s.includes(e));i.push({colId:n,displayedValues:[...new Set(e)],displayBlanks:!s.includes(``)&&l.some(e=>!e)})}let u=this.getters.getEvaluatedCell(o).formattedValue,d=this.getUniqueColNameForExcel(n,u,a);a.push(d);let f=T(o.col,o.row);t.cells[f]=d,t.cellValues[f]=d}n.filters=i}}}getUniqueColNameForExcel(e,t,n){return t||=`Column${e}`,zt(t,n,{compute:(e,n)=>t+String(n),start:2})}},oq=class extends cb{static getters=[`getColDimensions`,`getRowDimensions`,`getColRowOffset`];headerPositions={};isDirty=!0;handle(e){switch(Ps.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`:case`SET_FORMATTING`:case`CLEAR_FORMATTING`:this.headerPositions={},this.isDirty=!0;break;case`UPDATE_FILTER`:case`UPDATE_TABLE`:case`REMOVE_TABLE`:this.headerPositions={},this.isDirty=!0;break;case`REMOVE_COLUMNS_ROWS`:case`RESIZE_COLUMNS_ROWS`:case`HIDE_COLUMNS_ROWS`:case`ADD_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`FOLD_HEADER_GROUP`:case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_ALL_HEADER_GROUPS`:case`FOLD_ALL_HEADER_GROUPS`:case`UNGROUP_HEADERS`:case`GROUP_HEADERS`:case`CREATE_SHEET`:this.getters.tryGetSheet(e.sheetId)&&(this.headerPositions[e.sheetId]=this.computeHeaderPositionsOfSheet(e.sheetId));break;case`DUPLICATE_SHEET`:this.headerPositions[e.sheetIdTo]=b(this.headerPositions[e.sheetId]);break}}finalize(){for(let e of this.getters.getSheetIds())(this.isDirty||!this.headerPositions[e])&&(this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e));this.isDirty=!1}getColDimensions(e,t){let n=this.headerPositions[e].COL[t],r=this.getters.getColSize(e,t);return{start:n,size:r,end:n+(this.getters.isColHidden(e,t)?0:r)}}getRowDimensions(e,t){let n=this.headerPositions[e].ROW[t],r=this.getters.getRowSize(e,t);return{start:n,size:r,end:n+(this.getters.isRowHidden(e,t)?0:r)}}getColRowOffset(e,t,n,r=this.getters.getActiveSheetId()){let i=this.headerPositions[r][e][t];return this.headerPositions[r][e][n]-i}computeHeaderPositionsOfSheet(e){return{COL:this.computePositions(e,`COL`),ROW:this.computePositions(e,`ROW`)}}computePositions(e,t){let n={},r=0;for(let i=0;i<this.getters.getNumberHeaders(e,t)+1;i++)n[i]=r,!this.getters.isHeaderHidden(e,t,i)&&(r+=this.getters.getHeaderSize(e,t,i));return n}},sq=class extends cb{static layers=[`Selection`];static getters=[`getActiveSheet`,`getActiveSheetId`,`getActiveSheetName`,`getActiveCell`,`getActiveCols`,`getActiveRows`,`getCurrentStyle`,`getSelectedZones`,`getSelectedZone`,`getSelectedCells`,`getSelectedFigureId`,`getSelection`,`getActivePosition`,`getSheetPosition`,`isSingleColSelected`,`getElementsFromSelection`,`tryGetActiveSheetId`,`isGridSelectionActive`,`getSelectecUnboundedZone`];gridSelection={anchor:{cell:{col:0,row:0},zone:{top:0,left:0,bottom:0,right:0}},zones:[{top:0,left:0,bottom:0,right:0}]};selectedFigureId=null;sheetsData={};moveClient;isUnbounded;activeSheet=null;constructor(e){super(e),this.moveClient=e.moveClient,this.isUnbounded=!1}allowDispatch(e){switch(e.type){case`ACTIVATE_SHEET`:try{if(!this.getters.getSheet(e.sheetIdTo).isVisible)return`SheetIsHidden`;break}catch{return`InvalidSheetId`}case`MOVE_COLUMNS_ROWS`:return this.isMoveElementAllowed(e)}return`Success`}handleEvent(e){let t=e.anchor,n=[...this.gridSelection.zones];switch(this.isUnbounded=e.options?.unbounded||!1,e.mode){case`overrideSelection`:n=[t.zone];break;case`updateAnchor`:let r=n.findIndex(t=>Cn(t,e.previousAnchor.zone));r>=0&&(n[r]=t.zone);break;case`newAnchor`:n.push(t.zone);break;case`commitSelection`:let i=n.find(e=>Dn(t.zone,e)&&!Cn(t.zone,e));if(n.filter(e=>Cn(t.zone,e)).length>1&&n.length>2)n=n.filter(e=>!Cn(e,t.zone));else if(i){let e=Zn(t.zone,i);n=n.filter(e=>!Cn(e,t.zone)&&!Cn(e,i)).concat(e)}n=Fn(n);let a=n[n.length-1];t={cell:En(t.cell.col,t.cell.row,a)?t.cell:{col:a.left,row:a.top},zone:a};break}this.setSelectionMixin(t,n),this.selection.resetDefaultAnchor(this,b(this.gridSelection.anchor));let{col:r,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:r,row:i}),this.selectedFigureId=null}handle(e){switch(e.type){case`ACTIVATE_SHEET`:this.selectedFigureId=null;break;case`DELETE_FIGURE`:this.selectedFigureId===e.figureId&&(this.selectedFigureId=null);break;case`DELETE_SHEET`:this.selectedFigureId&&this.getters.getFigure(e.sheetId,this.selectedFigureId)&&(this.selectedFigureId=null);break}switch(e.type){case`START`:let t=this.getters.getVisibleSheetIds()[0];this.activateSheet(t,t);let{col:n,row:r}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(n,r),this.selection.registerAsDefault(this,this.gridSelection.anchor,{handleEvent:this.handleEvent.bind(this)}),this.moveClient({sheetId:t,col:0,row:0});break;case`ACTIVATE_SHEET`:this.activateSheet(e.sheetIdFrom,e.sheetIdTo);break;case`REMOVE_COLUMNS_ROWS`:{let t=this.getters.getActiveSheetId();if(e.sheetId===t){e.dimension===`COL`?this.onColumnsRemoved(e):this.onRowsRemoved(e);let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:n,row:r})}break}case`ADD_COLUMNS_ROWS`:{let t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:n,row:r})}break}case`MOVE_COLUMNS_ROWS`:e.sheetId===this.getActiveSheetId()&&this.onMoveElements(e);break;case`SELECT_FIGURE`:this.selectedFigureId=e.figureId;break;case`ACTIVATE_NEXT_SHEET`:this.activateNextSheet(`right`);break;case`ACTIVATE_PREVIOUS_SHEET`:this.activateNextSheet(`left`);break;case`HIDE_SHEET`:e.sheetId===this.getActiveSheetId()&&this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:e.sheetId,sheetIdTo:this.getters.getVisibleSheetIds()[0]});break;case`UNDO`:case`REDO`:case`DELETE_SHEET`:let i=Object.keys(this.sheetsData).filter(e=>!this.getters.tryGetSheet(e));for(let e of i)delete this.sheetsData[e];for(let e in this.sheetsData){let t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:b(t)}}this.fallbackToVisibleSheet();let a=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map(e=>this.getters.expandZone(a,e)),this.gridSelection.anchor.zone=this.getters.expandZone(a,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones),this.selectedFigureId=null;break}}finalize(){this.fallbackToVisibleSheet(),this.selection.resetDefaultAnchor(this,b(this.gridSelection.anchor))}isGridSelectionActive(){return this.selection.isListening(this)}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}getActiveSheetName(){return this.activeSheet.name}tryGetActiveSheetId(){return this.activeSheet?.id}getActiveCell(){return this.getters.getEvaluatedCell(this.getActivePosition())}getActiveCols(){let e=new Set;for(let t of this.gridSelection.zones)if(t.top===0&&t.bottom===this.getters.getNumberRows(this.getters.getActiveSheetId())-1)for(let n=t.left;n<=t.right;n++)e.add(n);return e}getActiveRows(){let e=new Set,t=this.getters.getActiveSheetId();for(let n of this.gridSelection.zones)if(n.left===0&&n.right===this.getters.getNumberCols(t)-1)for(let t=n.top;t<=n.bottom;t++)e.add(t);return e}getCurrentStyle(){let e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();return this.getters.getCellStyle({sheetId:t,col:e.left,row:e.top})??{}}getSelectedZones(){return b(this.gridSelection.zones)}getSelectedZone(){return b(this.gridSelection.anchor.zone)}getSelectecUnboundedZone(){return b(this.isUnbounded?this.getters.getUnboundedZone(this.activeSheet.id,this.gridSelection.anchor.zone):this.gridSelection.anchor.zone)}getSelection(){return b(this.gridSelection)}getSelectedCells(){let e=this.getters.getActiveSheetId(),t=[];for(let n of this.gridSelection.zones)t.push(...this.getters.getEvaluatedCellsInZone(e,n));return t}getSelectedFigureId(){return this.selectedFigureId}getActivePosition(){return this.getters.getMainCellPosition({sheetId:this.getActiveSheetId(),col:this.gridSelection.anchor.cell.col,row:this.gridSelection.anchor.cell.row})}getSheetPosition(e){if(e===this.getters.getActiveSheetId())return this.getActivePosition();{let t=this.sheetsData[e];return t?{sheetId:e,col:t.gridSelection.anchor.cell.col,row:t.gridSelection.anchor.cell.row}:this.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0})}}isSingleColSelected(){let e=this.getters.getSelectedZones();return!(e.length!==1||e[0].left!==e[0].right)}getElementsFromSelection(e){if(e===`COL`&&this.getters.getActiveCols().size===0||e===`ROW`&&this.getters.getActiveRows().size===0)return[];let t=this.getters.getSelectedZones(),n=[],r=e===`COL`?`left`:`top`,i=e===`COL`?`right`:`bottom`;for(let e of t){let t=Array.from({length:e[i]-e[r]+1},(t,n)=>e[r]+n);n=n.concat(t)}return[...new Set(n)].sort()}activateSheet(e,t){if(this.setActiveSheet(t),this.sheetsData[e]={gridSelection:b(this.gridSelection)},t in this.sheetsData)Object.assign(this,this.sheetsData[t]),this.selection.resetDefaultAnchor(this,b(this.gridSelection.anchor));else{let{col:e,row:n}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(e,n)}let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.activeSheet.id,col:n,row:r})}setSelectionMixin(e,t){let{anchor:n,zones:r}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=n,this.gridSelection.zones=r}selectCell(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.expandZone(n,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:r,cell:{col:e,row:t}},[r])}setActiveSheet(e){this.activeSheet=this.getters.getSheet(e)}activateNextSheet(e){let t=this.getters.getSheetIds(),n=(t.findIndex(e=>e===this.activeSheet.id)+(e===`left`?t.length-1:1))%t.length;this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[n]})}onColumnsRemoved(e){let{cell:t,zone:n}=this.gridSelection.anchor,r=vn(n,`left`,[...e.elements]),i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=vn(i,`left`,[...e.elements]);let a={cell:{col:i.left,row:i.top},zone:r},o=this.gridSelection.zones.map(t=>vn(t,`left`,[...e.elements]));this.setSelectionMixin(a,o)}onRowsRemoved(e){let{cell:t,zone:n}=this.gridSelection.anchor,r=vn(n,`top`,[...e.elements]),i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=vn(i,`top`,[...e.elements]);let a={cell:{col:i.left,row:i.top},zone:r},o=this.gridSelection.zones.map(t=>vn(t,`top`,[...e.elements]));this.setSelectionMixin(a,o)}onAddElements(e){let t=e.dimension===`COL`?`left`:`top`,n=_n(this.gridSelection.anchor.zone,t,e.base,e.position,e.quantity),r=this.gridSelection.zones.map(n=>_n(n,t,e.base,e.position,e.quantity)),i={cell:{col:n.left,row:n.top},zone:n};this.setSelectionMixin(i,r)}onMoveElements(e){let t=e.elements.length,n=this.getFiguresUpdates(e);this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,sheetName:e.sheetName,base:e.base,quantity:t,position:e.position});let r=e.dimension===`COL`,i=e.elements[0],a=e.elements[t-1],o=e.base<i,s=o&&r?t:0,c=o&&!r?t:0,l=o?e.elements.map(e=>e+t):e.elements,u={};for(let t of l)u[t]=this.getters.getHeaderSize(e.sheetId,e.dimension,t);let d=[{left:r?i+s:0,right:r?a+s:this.getters.getNumberCols(e.sheetId)-1,top:r?0:i+c,bottom:r?this.getters.getNumberRows(e.sheetId)-1:a+c}],f=this.getActiveSheetId(),p=o?e.base:e.base+1,m=[{left:r?p:0,right:r?p+t-1:this.getters.getNumberCols(e.sheetId)-1,top:r?0:p,bottom:r?this.getters.getNumberRows(e.sheetId)-1:p+t-1}],h=BB.cellHandlers.getKeys().map(e=>[e,new(BB.cellHandlers.get(e))(this.getters,this.dispatch)]),g={};for(let[e,t]of h)g[e]=t.copy(tA(f,d),!1,`shiftCells`);for(let[e,t]of h)g[e]&&t.paste({zones:m,sheetId:f},g[e],{isCutOperation:!0});let _=m[0],v=_.left,y=_.top;this.setSelectionMixin({zone:_,cell:{col:v,row:y}},[_]);let ee=o?e.base:e.base+1,te={};for(let t of l){let n=u[t];n!==this.getters.getHeaderSize(e.sheetId,e.dimension,ee)&&(te[n]??=[],te[n].push(ee)),ee+=1}for(let t in te)this.dispatch(`RESIZE_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,size:parseInt(t,10),elements:te[t]});this.dispatch(`REMOVE_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,sheetName:e.sheetName,elements:l}),this.applyFigureUpdates(n)}getFiguresUpdates(e){let t=[],n={},r=e.elements[0]<e.base?e.base-e.elements.length+1:e.base;for(let t=0;t<e.elements.length;t++)n[e.elements[t]]=r+t;for(let r of this.getters.getFigures(e.sheetId))e.dimension===`COL`&&r.col in n&&t.push({type:`UPDATE_FIGURE`,sheetId:e.sheetId,figureId:r.id,col:n[r.col],row:r.row}),e.dimension===`ROW`&&r.row in n&&t.push({type:`UPDATE_FIGURE`,sheetId:e.sheetId,figureId:r.id,row:n[r.row],col:r.col});return t}applyFigureUpdates(e){for(let t of e)this.dispatch(t.type,{...t})}isMoveElementAllowed(e){let t=e.dimension===`COL`,n=e.elements[0],r=e.elements[e.elements.length-1],i=e.sheetId,a=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;if(a(i,n-1,n)||a(i,r,r+1)||a(i,e.base-1,e.base))return`WillRemoveExistingMerge`;let o=[e.base,...e.elements],s=t?this.getters.getNumberCols(i):this.getters.getNumberRows(i);return o.some(e=>e<0||e>=s)?`InvalidHeaderIndex`:!t&&!this.isTableRowMoveAllowed(i,e.elements)?`CannotMoveTableHeader`:`Success`}isTableRowMoveAllowed(e,t){let n=this.getters.getCoreTables(e);if(n.length===0)return!0;let r=new Set(t);return n.every(({range:{zone:e},config:n})=>{let{top:i,bottom:a}=e;if(n.numberOfHeaders===0)return!0;let o=i+n.numberOfHeaders-1;return t.some(e=>e>=i&&e<=o)?S(i,a+1).every(e=>r.has(e)):!0})}fallbackToVisibleSheet(){if(!this.getters.tryGetSheet(this.getters.getActiveSheetId())){let e=this.getters.getVisibleSheetIds();if(this.activeSheet=this.getters.getSheet(e[0]),this.activeSheet.id in this.sheetsData){let{anchor:e}=this.clipSelection(this.activeSheet.id,this.sheetsData[this.activeSheet.id].gridSelection);this.selectCell(e.cell.col,e.cell.row)}else this.selectCell(0,0);let{col:t,row:n}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:n})}}clipSelection(e,t){let n=this.getters.getNumberCols(e)-1,r=this.getters.getNumberRows(e)-1,i=t.zones.map(e=>({left:x(e.left,0,n),right:x(e.right,0,n),top:x(e.top,0,r),bottom:x(e.bottom,0,r)})),a=x(t.anchor.cell.col,0,n),o=x(t.anchor.cell.row,0,r),s={left:x(t.anchor.zone.left,0,n),right:x(t.anchor.zone.right,0,n),top:x(t.anchor.zone.top,0,r),bottom:x(t.anchor.zone.bottom,0,r)};return{zones:i,anchor:{cell:{col:a,row:o},zone:s}}}drawLayer(e){if(this.getters.isDashboard())return;let{ctx:t,thinLineWidth:n}=e,r=this.getSelectedZones();t.fillStyle=`#f3f7fe`,t.fillStyle=r.length===1&&r[0].left===r[0].right&&r[0].top===r[0].bottom?`#f3f7fe`:`#e9f0ff`,t.strokeStyle=ae,t.lineWidth=1.5*n;for(let e of r){let{x:n,y:r,width:i,height:a}=this.getters.getVisibleRect(e);t.globalCompositeOperation=`multiply`,t.fillRect(n,r,i,a),t.globalCompositeOperation=`source-over`,t.strokeRect(n,r,i,a)}t.globalCompositeOperation=`source-over`;let i=this.getActivePosition();t.strokeStyle=ae,t.lineWidth=3*n;let a;a=this.getters.isInMerge(i)?this.getters.getMerge(i):E(i);let{x:o,y:s,width:c,height:l}=this.getters.getVisibleRect(a);c>0&&l>0&&t.strokeRect(o,s,c,l)}},cq=class{getters;sheetId;boundaries;top;bottom;left;right;offsetX;offsetY;canScrollVertically;canScrollHorizontally;viewportWidth;viewportHeight;offsetCorrectionX;offsetCorrectionY;constructor(e,t,n,r,i,a){if(this.getters=e,this.sheetId=t,this.boundaries=n,r.width<0||r.height<0)throw Error(`Viewport size cannot be negative`);this.viewportWidth=r.height&&r.width,this.viewportHeight=r.width&&r.height,this.top=n.top,this.bottom=n.bottom,this.left=n.left,this.right=n.right,this.offsetX=a.x,this.offsetY=a.y,this.canScrollVertically=i.canScrollVertically,this.canScrollHorizontally=i.canScrollHorizontally,this.offsetCorrectionX=this.getters.getColDimensions(this.sheetId,this.boundaries.left).start,this.offsetCorrectionY=this.getters.getRowDimensions(this.sheetId,this.boundaries.top).start,this.adjustViewportOffsetX(),this.adjustViewportOffsetY()}getMaxSize(){let e=this.getters.findLastVisibleColRowIndex(this.sheetId,`COL`,{first:this.boundaries.left,last:this.boundaries.right}),t=this.getters.findLastVisibleColRowIndex(this.sheetId,`ROW`,{first:this.boundaries.top,last:this.boundaries.bottom}),{end:n}=this.getters.getColDimensions(this.sheetId,e),{end:r}=this.getters.getRowDimensions(this.sheetId,t),i=n-this.offsetCorrectionX;this.canScrollHorizontally&&(i=Math.max(i,this.viewportWidth));let a=r-this.offsetCorrectionY;return this.canScrollVertically&&(a=Math.max(a,this.viewportHeight),r+46>a&&!this.getters.isReadonly()&&(a+=46)),{width:i,height:a}}getColIndex(e){return e<this.offsetCorrectionX||e>this.offsetCorrectionX+this.viewportWidth?-1:this.searchHeaderIndex(`COL`,e-this.offsetCorrectionX+this.snapCorrection.x,this.left)}getRowIndex(e){return e<this.offsetCorrectionY||e>this.offsetCorrectionY+this.viewportHeight?-1:this.searchHeaderIndex(`ROW`,e-this.offsetCorrectionY+this.snapCorrection.y,this.top)}adjustPosition(e){let t=this.sheetId,n=this.getters.getMainCellPosition({sheetId:t,...e}),{col:r,row:i}=this.getters.getNextVisibleCellPosition(n);En(r,this.boundaries.top,this.boundaries)&&this.adjustPositionX(r),En(this.boundaries.left,i,this.boundaries)&&this.adjustPositionY(i)}adjustPositionX(e){let t=this.sheetId,{start:n,end:r}=this.getters.getColDimensions(t,e);this.offsetX+this.viewportWidth+this.offsetCorrectionX<r?this.offsetX=r-this.viewportWidth:this.offsetX+this.offsetCorrectionX>n&&(this.offsetX=n-this.offsetCorrectionX),this.adjustViewportZoneX()}adjustPositionY(e){let t=this.sheetId,{start:n,end:r}=this.getters.getRowDimensions(t,e);this.offsetY+this.viewportHeight+this.offsetCorrectionY<r?this.offsetY=r-this.viewportHeight:this.offsetY+this.offsetCorrectionY>n&&(this.offsetY=n-this.offsetCorrectionY),this.adjustViewportZoneY()}willNewOffsetScrollViewport(e,t){return this.canScrollHorizontally&&this.offsetX!==e||this.canScrollVertically&&this.offsetY!==t}setViewportOffset(e,t){this.setViewportOffsetX(e),this.setViewportOffsetY(t)}adjustViewportZone(){this.adjustViewportZoneX(),this.adjustViewportZoneY()}getVisibleRect(e){let t=Sn(e,this),n=this.snapCorrection.x,r=this.snapCorrection.y;if(t)return{x:this.getters.getColRowOffset(`COL`,this.left,t.left)+this.offsetCorrectionX-(this.left===t.left?0:n),y:this.getters.getColRowOffset(`ROW`,this.top,t.top)+this.offsetCorrectionY-(this.top===t.top?0:r),width:Math.min(this.getters.getColRowOffset(`COL`,t.left,t.right+1)-(this.left===t.left?n:0),this.viewportWidth),height:Math.min(this.getters.getColRowOffset(`ROW`,t.top,t.bottom+1)-(this.top===t.top?r:0),this.viewportHeight)}}getFullRect(e){let t=Sn(e,this.boundaries),n=this.snapCorrection.x,r=this.snapCorrection.y;if(t){let t=this.getters.getColRowOffset(`COL`,this.left,e.left)+this.offsetCorrectionX,i=this.getters.getColRowOffset(`ROW`,this.top,e.top)+this.offsetCorrectionY,a=this.getters.getColRowOffset(`COL`,e.left,e.right+1),o=this.getters.getColRowOffset(`ROW`,e.top,e.bottom+1);return{x:t-n,y:i-r,width:a,height:o}}}isVisible(e,t){return t<=this.bottom&&t>=this.top&&e>=this.left&&e<=this.right&&!this.getters.isColHidden(this.sheetId,e)&&!this.getters.isRowHidden(this.sheetId,t)}searchHeaderIndex(e,t,n=0){if(this.viewportWidth<=0||this.viewportHeight<=0)return-1;let r=this.sheetId,i=this.getters.getNumberHeaders(r,e),a=n,o=i;for(;a<=o&&a!==i&&o!==-1;){let i=Math.floor((a+o)/2),s=this.getters.getColRowOffset(e,n,i),c=this.getters.getHeaderSize(r,e,i);if(t>=s&&t<s+c)return i;t>=s+c?a=i+1:o=i-1}return-1}setViewportOffsetX(e){this.canScrollHorizontally&&(this.offsetX=e,this.adjustViewportZoneX())}setViewportOffsetY(e){this.canScrollVertically&&(this.offsetY=e,this.adjustViewportZoneY())}adjustViewportOffsetX(){if(this.canScrollHorizontally){let{width:e}=this.getMaxSize();this.viewportWidth+this.offsetX>e&&(this.offsetX=Math.max(0,e-this.viewportWidth))}this.adjustViewportZoneX()}adjustViewportOffsetY(){if(this.canScrollVertically){let{height:e}=this.getMaxSize();this.viewportHeight+this.offsetY>e&&(this.offsetY=Math.max(0,e-this.viewportHeight))}this.adjustViewportZoneY()}adjustViewportZoneX(){this.left=this.searchHeaderIndex(`COL`,this.offsetX,this.boundaries.left),this.right=Math.min(this.boundaries.right,this.searchHeaderIndex(`COL`,Math.max(this.viewportWidth+this.snapCorrection.x-.1),this.left)),this.viewportWidth&&(this.left===-1&&(this.left=this.boundaries.left),this.right===-1&&(this.right=this.boundaries.right))}adjustViewportZoneY(){this.top=this.searchHeaderIndex(`ROW`,this.offsetY,this.boundaries.top),this.bottom=Math.min(this.boundaries.bottom,this.searchHeaderIndex(`ROW`,Math.max(this.viewportHeight+this.snapCorrection.y-.1,0),this.top)),this.viewportHeight&&(this.top===-1&&(this.top=this.boundaries.top),this.bottom===-1&&(this.bottom=this.boundaries.bottom))}get snapCorrection(){return{x:Math.abs(this.offsetX-this.getters.getColRowOffset(`COL`,this.boundaries.left,Math.max(0,this.left))),y:Math.abs(this.offsetY-this.getters.getColRowOffset(`ROW`,this.boundaries.top,Math.max(0,this.top)))}}},lq=class extends cb{static getters=`getColIndex.getRowIndex.getActiveMainViewport.getSheetViewDimension.getSheetViewDimensionWithHeaders.getMainViewportRect.isVisibleInViewport.getEdgeScrollCol.getEdgeScrollRow.getVisibleFigures.getVisibleRect.getVisibleRectWithoutHeaders.getVisibleRectWithZoom.getVisibleCellPositions.getColRowOffsetInViewport.getMainViewportCoordinates.getActiveSheetScrollInfo.getSheetViewVisibleCols.getSheetViewVisibleRows.getFrozenSheetViewRatio.isPixelPositionVisible.getColDimensionsInViewport.getRowDimensionsInViewport.getAllActiveViewportsZonesAndRect.getRect.getFigureUI.getPositionAnchorOffset.getGridOffset.getViewportZoomLevel.getScrollBarWidth.getMaximumSheetOffset`.split(`.`);viewports={};sheetViewWidth=Pe();sheetViewHeight=Pe();gridOffsetX=0;gridOffsetY=0;zoomLevel=1;sheetsWithDirtyViewports=new Set;shouldAdjustViewports=!1;allowDispatch(e){switch(e.type){case`SET_VIEWPORT_OFFSET`:return this.chainValidations(this.checkScrollingDirection,this.checkIfViewportsWillChange)(e);case`RESIZE_SHEETVIEW`:return this.chainValidations(this.checkValuesAreDifferent,this.checkPositiveDimension)(e);default:return`Success`}}handleEvent(e){let t=this.getters.getActiveSheetId();if(e.options.scrollIntoView){let{col:n,row:r}=Ln(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(Ps.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`SET_ZOOM`:this.zoomLevel=e.zoom||1;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`:case`SET_FORMATTING`:for(let e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);break;case`DELETE_SHEET`:this.cleanViewports(),this.sheetsWithDirtyViewports.delete(e.sheetId);break;case`ACTIVATE_SHEET`:this.sheetsWithDirtyViewports.add(e.sheetIdTo);break;case`SCROLL_TO_CELL`:this.refreshViewport(this.getters.getActiveSheetId(),{col:e.col,row:e.row});break}}finalize(){for(let e of this.sheetsWithDirtyViewports)if(this.resetViewports(e),this.shouldAdjustViewports){let t=this.getters.getSheetPosition(e);this.getSubViewports(e).forEach(e=>{e.adjustPosition(t)})}this.sheetsWithDirtyViewports=new Set,this.shouldAdjustViewports=!1,this.setViewports()}setViewports(){let e=this.getters.getSheetIds();for(let t of e)this.viewports[t]?.bottomRight||this.resetViewports(t)}getColIndex(e){let t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map(t=>t.getColIndex(e)))}getRowIndex(e){let t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map(t=>t.getRowIndex(e)))}getSheetViewDimensionWithHeaders(){return{width:this.sheetViewWidth+this.gridOffsetX,height:this.sheetViewHeight+this.gridOffsetY}}getSheetViewDimension(){return{width:this.sheetViewWidth,height:this.sheetViewHeight}}getGridOffset(){return{x:this.gridOffsetX,y:this.gridOffsetY}}getActiveMainViewport(){let e=this.getters.getActiveSheetId();return this.getMainViewport(e)}getActiveSheetScrollInfo(){let e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetX,scrollY:t.offsetY}}getSheetViewVisibleCols(){let e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map(e=>S(e.left,e.right+1)).flat())].filter(t=>t>=0&&!this.getters.isHeaderHidden(e,`COL`,t))}getSheetViewVisibleRows(){let e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map(e=>S(e.top,e.bottom+1)).flat())].filter(t=>t>=0&&!this.getters.isHeaderHidden(e,`ROW`,t))}getVisibleCellPositions(){let e=this.getSheetViewVisibleCols(),t=this.getSheetViewVisibleRows(),n=this.getters.getActiveSheetId(),r=[];for(let i of e)for(let e of t){let t={sheetId:n,col:i,row:e},a=this.getters.getMainCellPosition(t);a.row!==e||a.col!==i||r.push(t)}return r}getMainViewportRect(){let e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e),{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(e),{width:i,height:a}=t.getMaxSize();return{x:this.getters.getColDimensions(e,n).start,y:this.getters.getRowDimensions(e,r).start,width:i,height:a}}getMaximumSheetOffset(){let e=this.getters.getActiveSheetId(),{width:t,height:n}=this.getMainViewportRect(),r=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-r.viewportWidth),maxOffsetY:Math.max(0,n-r.viewportHeight)}}getColRowOffsetInViewport(e,t,n){if(n<t)return-this.getColRowOffsetInViewport(e,n,t);let r=this.getters.getActiveSheetId(),i=e===`COL`?this.getters.getSheetViewVisibleCols():this.getters.getSheetViewVisibleRows(),a=i.findIndex(e=>t>=e),o=i.findIndex(e=>n<=e);o=o===-1?i.length:o;let s=i.slice(a,o),c=0;for(let t of s)c+=this.getters.getHeaderSize(r,e,t);return c*this.zoomLevel}isVisibleInViewport({sheetId:e,col:t,row:n}){return this.getSubViewports(e).some(e=>e.isVisible(t,n))}getScrollBarWidth(){return 15/this.zoomLevel}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=xc(e-s),i=1):e<c&&n>=c&&l>0?(r=!0,a=xc(c-e),i=-1):o&&t<c&&e>c&&(r=!0,a=xc(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=xc(e-s),i=1):e<c&&n>=c&&l>0?(r=!0,a=xc(c-e),i=-1):o&&t<c&&e>c&&(r=!0,a=xc(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}}getVisibleRectWithZoom(e){let t=this.getViewportZoomLevel(),n=this.getVisibleRectWithoutHeaders(e);return n.width*=t,n.height*=t,n.x=n.x*t+this.gridOffsetX*t,n.y=n.y*t+this.gridOffsetY*t,n}getVisibleRectWithoutHeaders(e){let t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,t=>t.getVisibleRect(e))}getRect(e){let t=this.getters.getActiveSheetId(),n=this.mapViewportsToRect(t,t=>t.getFullRect(e));return{...n,x:n.x+this.gridOffsetX,y:n.y+this.gridOffsetY}}getRectWithoutHeaders(e){let t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,t=>t.getFullRect(e))}getMainViewportCoordinates(){let e=this.getters.getActiveSheetId(),{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,n).start}}getColDimensionsInViewport(e,t){let{top:n}=this.getMainInternalViewport(e),r={left:t,right:t,top:n,bottom:n},{x:i,width:a}=this.getVisibleRect(r),o=i-this.gridOffsetX;return{start:o,size:a,end:o+a}}getRowDimensionsInViewport(e,t){let{left:n}=this.getMainInternalViewport(e),r={left:0,right:n,top:t,bottom:t},{y:i,height:a}=this.getVisibleRect(r),o=i-this.gridOffsetY;return{start:o,size:a,end:o+a}}getAllActiveViewportsZonesAndRect(){let e=this.getters.getActiveSheetId();return this.getSubViewports(e).map(e=>({zone:e,rect:{x:e.offsetCorrectionX+this.gridOffsetX,y:e.offsetCorrectionY+this.gridOffsetY,...e.getMaxSize()}}))}getViewportZoomLevel(){return this.zoomLevel}ensureMainViewportExist(e){this.viewports[e]||this.resetViewports(e)}getSubViewports(e){return this.ensureMainViewportExist(e),Object.values(this.viewports[e]).filter(C)}checkPositiveDimension(e){return e.width<0||e.height<0?`InvalidViewportSize`:`Success`}checkValuesAreDifferent(e){let{height:t,width:n}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===n&&e.height===t?`ValuesNotChanged`:`Success`}checkScrollingDirection({offsetX:e,offsetY:t}){let n=this.getMainInternalViewport(this.getters.getActiveSheetId());return!n.canScrollHorizontally&&e>0||!n.canScrollVertically&&t>0?`InvalidScrollingDirection`:`Success`}checkIfViewportsWillChange({offsetX:e,offsetY:t}){let n=this.getters.getActiveSheetId(),{maxOffsetX:r,maxOffsetY:i}=this.getMaximumSheetOffset();return this.getSubViewports(n).some(n=>n.willNewOffsetScrollViewport(x(e,0,r),x(t,0,i)))?`Success`:`ViewportScrollLimitsReached`}getMainViewport(e){let t=this.getMainInternalViewport(e);return{top:t.top,left:t.left,bottom:t.bottom,right:t.right}}getMainInternalViewport(e){return this.ensureMainViewportExist(e),this.viewports[e].bottomRight}cleanViewports(){let e={};for(let t of this.getters.getSheetIds())e[t]=this.viewports[t];this.viewports=e}resizeSheetView(e,t,n=0,r=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=n,this.gridOffsetY=r,this.recomputeViewports()}recomputeViewports(){for(let e of this.getters.getSheetIds())this.resetViewports(e)}setSheetViewOffset(e,t){let n=this.getters.getActiveSheetId(),{maxOffsetX:r,maxOffsetY:i}=this.getMaximumSheetOffset();this.getSubViewports(n).forEach(n=>n.setViewportOffset(x(e,0,r),x(t,0,i)))}getViewportOffset(e){return{x:this.viewports[e]?.bottomRight.offsetX||0,y:this.viewports[e]?.bottomRight.offsetY||0}}resetViewports(e){if(!this.getters.tryGetSheet(e))return;let{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e),r=this.getters.getNumberCols(e),i=this.getters.getNumberRows(e),a=Math.min(this.getters.getColRowOffset(`COL`,0,t,e),this.sheetViewWidth),o=Math.min(this.getters.getColRowOffset(`ROW`,0,n,e),this.sheetViewHeight),s=Math.max(this.sheetViewWidth-a,0),c=Math.max(this.sheetViewHeight-o,0),{xRatio:l,yRatio:u}=this.getFrozenSheetViewRatio(e),d=l<1,f=u<1,p=this.getViewportOffset(e),m={topLeft:n&&t&&new cq(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 cq(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 cq(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 cq(this.getters,e,{left:t,right:r-1,top:n,bottom:i-1},{width:s,height:c},{canScrollHorizontally:d,canScrollVertically:f},{x:d?p.x:0,y:f?p.y:0})};this.viewports[e]=m}refreshViewport(e,t){this.getSubViewports(e).forEach(e=>{e.adjustViewportZone(),e.adjustPosition(t)})}shiftVertically(e){let t=this.getters.getActiveSheetId(),{top:n}=this.getMainInternalViewport(t),{scrollX:r}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(r,e);let{anchor:i}=this.getters.getSelection();if(i.cell.row>=this.getters.getPaneDivisions(t).ySplit){let e=this.getMainInternalViewport(t).top-n;this.selection.selectCell(i.cell.col,i.cell.row+e)}}getColIndexLeftOfMainViewport(e){if(e>=0)return-1;let t=this.getters.getActiveSheetId(),n=this.getActiveMainViewport().left,r=-this.getActiveSheetScrollInfo().scrollX-this.getters.getColRowOffset(`COL`,n,0);for(;e<r;n--)r-=this.getters.getColSize(t,n-1);return Math.max(n,0)}getRowIndexTopOfMainViewport(e){if(e>=0)return-1;let t=this.getters.getActiveSheetId(),n=this.getActiveMainViewport().top,r=-this.getActiveSheetScrollInfo().scrollY-this.getters.getColRowOffset(`ROW`,n,0);for(;e<r;n--)r-=this.getters.getRowSize(t,n-1);return Math.max(n,0)}getVisibleFigures(){let e=this.getters.getActiveSheetId(),t=[],n=this.getters.getFigures(e),{scrollX:r,scrollY:i}=this.getters.getActiveSheetScrollInfo(),{x:a,y:o}=this.getMainViewportCoordinates(),{width:s,height:c}=this.getters.getSheetViewDimensionWithHeaders();for(let l of n){let n=this.getFigureUI(e,l),{x:u,y:d}=n;u>=a&&(u+l.width<r+a||u>s+r+a)||d>=o&&(d+l.height<i+o||d>c+i+o)||t.push(n)}return t}getFigureUI(e,t){let n=t.offset.x+this.getters.getColDimensions(e,t.col).start,r=t.offset.y+this.getters.getRowDimensions(e,t.row).start;return{...t,x:n,y:r}}getPositionAnchorOffset(e){let{scrollX:t,scrollY:n}=this.getters.getActiveSheetScrollInfo(),r=e.x-t,i=e.y-n,a=r>=0?this.getColIndex(r):this.getColIndexLeftOfMainViewport(r),o=i>=0?this.getRowIndex(i):this.getRowIndexTopOfMainViewport(i),{x:s,y:c}=this.getRect(E({col:a,row:o}));return{col:a,row:o,offset:{x:Math.max(r-s+this.gridOffsetX,0),y:Math.max(i-c+this.gridOffsetY,0)}}}isPixelPositionVisible(e){let{scrollX:t,scrollY:n}=this.getters.getActiveSheetScrollInfo(),{x:r,y:i}=this.getters.getMainViewportCoordinates(),{width:a,height:o}=this.getters.getSheetViewDimension();return!(e.x>=r&&(e.x<r+t||e.x>a+t+r)||e.y>=i&&(e.y<i+n||e.y>o+n+i))}getFrozenSheetViewRatio(e){let{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e),r=this.getters.getColDimensions(e,t).start,i=this.getters.getRowDimensions(e,n).start,a=this.sheetViewWidth+this.gridOffsetX,o=this.sheetViewHeight+this.gridOffsetY;return{xRatio:r/a,yRatio:i/o}}mapViewportsToRect(e,t){let n=1/0,r=1/0,i=0,a=0,o=!1;for(let s of this.getSubViewports(e)){let e=t(s);e&&(o=!0,n=Math.min(n,e.x),r=Math.min(r,e.y),i=Math.max(i,e.x+e.width),a=Math.max(a,e.y+e.height))}return o?{x:n,y:r,width:i-n,height:a-r}:{x:0,y:0,width:0,height:0}}};let uq=new Kl().add(`settings`,AW).add(`sheet`,jW).add(`header grouping`,SW).add(`header visibility`,wW).add(`tables`,IW).add(`dataValidation`,bW).add(`cell`,mW).add(`merge`,EW).add(`style`,PW).add(`headerSize`,CW).add(`borders`,fW).add(`conditional formatting`,yW).add(`figures`,xW).add(`chart`,_W).add(`carousel`,pW).add(`image`,TW).add(`pivot_core`,kW).add(`spreadsheet_pivot_core`,MW).add(`tableStyle`,FW),dq=new Kl().add(`ui_sheet`,eq).add(`ui_options`,$K).add(`autofill`,UG).add(`sort`,YK).add(`automatic_sum`,WG).add(`format`,IK).add(`insert_pivot`,zK).add(`pivot_presence`,JK).add(`split_to_columns`,XK).add(`subtotal_evaluation`,lb).add(`collaborative`,NK).add(`history`,KK).add(`table_autofill`,ZK).add(`table_ui_resize`,QK).add(`datavalidation_insert`,PK).add(`checkbox_toggle`,YG).add(`dynamic_translate`,FK).add(`geo_features`,LK).add(`data_cleanup`,kG),fq=new Kl().add(`selection`,sq).add(`evaluation_filter`,aq).add(`header_visibility_ui`,RK).add(`cell_computed_style`,JG).add(`table_computed_style`,GG).add(`header_positions`,oq).add(`viewport`,lq).add(`clipboard`,rq).add(`carousel_ui`,tq),pq=new Kl().add(`evaluation`,cG).add(`evaluation_chart`,gG).add(`evaluation_cf`,_G).add(`row_size`,bG).add(`data_validation_ui`,yG).add(`dynamic_tables`,hG).add(`custom_colors`,mG).add(`pivot_ui`,TG).add(`cell_icon`,uG);ak.add(`dataValidation`,{displayAllOnInitialContent:!0,canBeToggled:!1,getProposals(e,t){if(Bt(t)||!this.composer.currentEditedCell)return[];let n=this.composer.currentEditedCell,r=this.getters.getValidationRuleForCell(n);if(!r||r.criterion.type!==`isValueInList`&&r.criterion.type!==`isValueInRange`)return[];let i=this.composer.currentEditedCell.sheetId,a=r.criterion.type===`isValueInRange`?this.getters.getDataValidationRangeValues(i,r.criterion):r.criterion.values.map(e=>({label:e,value:e}));if(r.criterion.displayStyle!==`chip`)return a.map(e=>({text:e.value,fuzzySearchKey:e.label,htmlContent:[{value:e.label}]}));let o=r.criterion.colors;return a.map(e=>{let t=o?.[e.value];return{text:e.value,htmlContent:[{value:e.label,color:Ur(t||`#E7E9ED`),backgroundColor:t||`#E7E9ED`,classes:[`badge rounded-pill fs-6 fw-normal w-100 mt-1 text-start`]}],fuzzySearchKey:e.label}})},selectProposal(e,t){this.composer.setCurrentContent(t),this.composer.stopEdition()}}),ak.add(`functions`,{sequence:100,autoSelectFirstProposal:!0,maxDisplayedProposals:10,getProposals(e){if(e.type!==`SYMBOL`)return[];let t=e.value;return Bt(this.composer.currentContent)?Object.entries(yO.content).filter(([e,{hidden:t}])=>!t).map(([e,{description:n}])=>({text:e,description:n,htmlContent:YH(t,e,le,`o-semi-bold`)})).sort((e,t)=>e.text.length-t.text.length||e.text.localeCompare(t.text)):[]},selectProposal(e,t){let n=e.end,r=e.end;[`SYMBOL`,`FUNCTION`].includes(e.type)&&(n=e.start);let i=this.composer.currentTokens;t+=`(`;let a=i.map(e=>e.start).indexOf(e.start);a+1<i.length&&i[a+1]?.type===`LEFT_PAREN`&&r++,this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t)}});function mq(e,t){for(let n=0;n<t.length;n++){let r=t[n].proposalValues;r===void 0||r.length===0||ak.add(`${e}_function_${t[n].name}_argument_proposals`,{sequence:50,autoSelectFirstProposal:!0,selectProposal:hq,getProposals:t=>{let i=t.functionContext;if(!i||i.parent.toUpperCase()!==e.toUpperCase()||i.argPosition!==n)return;let a=[],o=``;for(let{value:e,label:t}of r){switch(typeof e){case`string`:o=`"${e}"`;break;case`number`:o=e.toString();break;case`boolean`:o=e?`TRUE`:`FALSE`;break;default:}a.push({text:o,description:t,htmlContent:[{value:o,color:typeof e==`string`?He.STRING:He.NUMBER}],fuzzySearchKey:o,alwaysExpanded:!0})}return a}})}}function hq(e,t){let n=e.end,r=e.end;[`LEFT_PAREN`,`ARG_SEPARATOR`].includes(e.type)||(n=e.start),this.composer.stopComposerRangeSelection(),this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t)}yO.getAll().forEach(e=>mq(e.name,e.args)),ak.add(`pivot_ids`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||![`PIVOT.VALUE`,`PIVOT.HEADER`,`PIVOT`].includes(t.parent.toUpperCase())||t.argPosition!==0)return;let n=this.getters.getPivotIds();if(!n.includes(e.value))return n.map(e=>{let t=this.getters.getPivotCoreDefinition(e),n=`${this.getters.getPivotFormulaId(e)}`;return{text:n,description:t.name,htmlContent:[{value:n,color:He.NUMBER}],fuzzySearchKey:n+t.name,alwaysExpanded:!0}}).filter(C)},selectProposal:hq}),ak.add(`pivot_measures`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(t?.parent.toUpperCase()!==`PIVOT.VALUE`||t.argPosition!==1)return[];let n=MU(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return[];let i=this.getters.getPivot(r);return i.init(),i.isValid()?i.definition.measures.map(e=>{if(e.fieldName===`__count`){let e=`"__count"`;return{text:e,description:k(`Count`),htmlContent:[{value:e,color:He.STRING}],fuzzySearchKey:k(`Count`)+e}}return kU(e)}).filter(C):[]},selectProposal:hq}),ak.add(`pivot_group_fields`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||!gq(e)&&!_q(e))return;let n=MU(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return;let i=this.getters.getPivot(r);i.init();let a=i.getFields(),{columns:o,rows:s}=i.definition,c=t.args;t?.parent.toUpperCase()===`PIVOT.VALUE`?(c=c.filter((e,t)=>t%2==0),c=c.slice(1,t.argPosition)):c=c.filter((e,t)=>t%2==1);let l=c.map(e=>e?.value).filter(C),u=o.map(e=>e.nameWithGranularity),d=s.map(e=>e.nameWithGranularity),f=[],p=[`ARG_SEPARATOR`,`SPACE`].includes(e.type)?l.at(-1):l.at(-2),m=sW.get(i.type);if(m&&p?.startsWith(`#`)&&(p=p.slice(1)),p===void 0&&(f.push(u[0]),f.push(d[0])),d.includes(p)){let e=d[d.indexOf(p)+1];f.push(e),f.push(u[0])}if(u.includes(p)){let e=u[u.indexOf(p)+1];f.push(e)}let h=f.filter(C);return h.map(e=>{let[t,n]=e.split(`:`),r=a[t];return r?OU(r,n):void 0}).concat(h.map(e=>{if(!m)return;let t=a[e.split(`:`)[0]];if(!t)return;let n=`"#${e}"`;return{text:n,description:k(`%s (positional)`,t.string)+(t.help?` (${t.help})`:``),htmlContent:[{value:n,color:He.STRING}],fuzzySearchKey:t.string+n}})).filter(C)},selectProposal:hq});function gq(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.VALUE`&&t.argPosition>=2&&t.argPosition%2==0}function _q(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.HEADER`&&t.argPosition>=1&&t.argPosition%2==1}ak.add(`pivot_group_values`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||!e||!vq(e)&&!yq(e))return;let n=MU(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return;let i=this.getters.getPivot(r);if(!i.isValid())return;let a=t.argPosition,o=e.functionContext?.args[a-1]?.value;if(!o)return;let s;try{s=i.definition.getDimension(o)}catch{return}return s.granularity===`month_number`?Object.values(Bo).map((e,t)=>({text:`${t+1}`,fuzzySearchKey:e.toString(),description:e.toString(),htmlContent:[{value:`${t+1}`,color:He.NUMBER}]})):s.granularity===`quarter_number`?[1,2,3,4].map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:k(`Quarter %s`,e),htmlContent:[{value:`${e}`,color:He.NUMBER}]})):s.granularity===`day_of_month`?S(1,32).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:He.NUMBER}]})):s.granularity===`iso_week_number`?S(0,54).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:He.NUMBER}]})):s.granularity===`day_of_week`?S(1,8).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:He.NUMBER}]})):s.granularity===`hour_number`?S(0,24).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:He.NUMBER}]})):s.granularity===`minute_number`?S(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:He.NUMBER}]})):s.granularity===`second_number`?S(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:He.NUMBER}]})):i.getPossibleFieldValues(s).map(({value:e,label:t})=>{let n=typeof e==`string`,r=n?`"${e}"`:e.toString(),i=n?He.STRING:He.NUMBER,a=t===e?``:t;return{text:r,description:a,htmlContent:[{value:r,color:i}],fuzzySearchKey:r+a}})},selectProposal:hq});function vq(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.VALUE`&&t.argPosition>=2&&t.argPosition%2==1}function yq(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.HEADER`&&t.argPosition>=1&&t.argPosition%2==0}ak.add(`sheet_names`,{sequence:150,autoSelectFirstProposal:!0,getProposals(e){return e.type===`SYMBOL`||e.type===`UNKNOWN`&&e.value.startsWith(`'`)?this.getters.getSheetIds().map(e=>{let t=Ye(this.getters.getSheetName(e));return{text:t,fuzzySearchKey:t.startsWith(`'`)?t:`'`+t}}):[]},selectProposal(e,t){let n=e.start,r=e.end;this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t+`!`)}});let bq=new B;bq.add(`link`,{condition:(e,t)=>!!t.getEvaluatedCell(e).link,execute:(e,t,n)=>$s(t.model.getters.getEvaluatedCell(e).link,t,n),title:(e,t)=>{let n=t.getEvaluatedCell(e).link;return n?n.isExternal?k(`Go to url: %(url)s`,{url:n.url}):k(`Go to %(label)s`,{label:n.label}):``},sequence:5}),bq.add(`dashboard_pivot_sorting`,{condition:(e,t)=>{if(!t.isDashboard())return!1;let n=t.getPivotCellFromPosition(e);return pR(t,e)&&n.type===`MEASURE_HEADER`},execute:(e,t)=>{mR(t,e,Sq(t.model.getters,e))},component:cW,componentProps:(e,t)=>({position:e,sortDirection:t.getPivotCellSortDirection(e)}),sequence:2});let xq={none:`asc`,asc:`desc`,desc:`none`};function Sq(e,t){return xq[e.getPivotCellSortDirection(t)??`none`]}lG.add(`filter_icon`,(e,t)=>{if(e.isFilterHeader(t)){let n=e.isFilterActive(t),r=kr(e.getCellComputedStyle(t).fillColor||`#fff`)<.45;return{type:`filter_icon`,svg:sj(n,r,!1),hoverSvg:sj(n,r,!0),priority:3,horizontalAlign:`right`,size:17,margin:2,position:t,onClick:(e,t)=>{let n=t.getStore(Bk),r=n.persistentCellPopover;if(r.isOpen&&r.col===e.col&&r.row===e.row&&r.type===`FilterMenu`){n.close();return}n.open(e,`FilterMenu`)}}}});let Cq=new B().add(`ADD_COLUMNS_ROWS`,Eq).add(`REMOVE_COLUMNS_ROWS`,jq).add(`ADD_MERGE`,Dq).add(`REMOVE_MERGE`,Oq).add(`CREATE_SHEET`,kq).add(`DELETE_SHEET`,Mq).add(`DUPLICATE_SHEET`,Aq).add(`CREATE_FIGURE`,Nq).add(`CREATE_CHART`,Pq).add(`HIDE_COLUMNS_ROWS`,Fq).add(`UNHIDE_COLUMNS_ROWS`,Iq).add(`CREATE_TABLE_STYLE`,Lq).add(`ADD_PIVOT`,Tq).add(`RENAME_SHEET`,Rq);for(let e of Vs.values())Cq.contains(e)||Cq.add(e,wq);function wq(e){return[e]}function Tq(e){return[{type:`REMOVE_PIVOT`,pivotId:e.pivotId}]}function Eq(e){let t=[],n=e.base;e.position===`after`&&n++;for(let r=0;r<e.quantity;r++)t.push(r+n);return[{type:`REMOVE_COLUMNS_ROWS`,dimension:e.dimension,elements:t,sheetId:e.sheetId,sheetName:e.sheetName}]}function Dq(e){return[{type:`REMOVE_MERGE`,sheetId:e.sheetId,target:e.target}]}function Oq(e){return[{type:`ADD_MERGE`,sheetId:e.sheetId,target:e.target}]}function kq(e){return[{type:`DELETE_SHEET`,sheetId:e.sheetId,sheetName:e.name}]}function Aq(e){return[{type:`DELETE_SHEET`,sheetId:e.sheetIdTo,sheetName:``}]}function jq(e){let t=[],n=[...e.elements].sort((e,t)=>e-t);for(let r of Ze(n)){let n=r[0]===0?0:r[0]-1,i=r[0]===0?`before`:`after`;t.push({type:`ADD_COLUMNS_ROWS`,dimension:e.dimension,quantity:r.length,base:n,sheetId:e.sheetId,sheetName:e.sheetName,position:i})}return t}function Mq(e){return[{type:`CREATE_SHEET`,sheetId:e.sheetId,position:1,name:e.sheetName}]}function Nq(e){return[{type:`DELETE_FIGURE`,figureId:e.figureId,sheetId:e.sheetId}]}function Pq(e){return[{type:`DELETE_FIGURE`,figureId:e.figureId,sheetId:e.sheetId}]}function Fq(e){return[{type:`UNHIDE_COLUMNS_ROWS`,sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}function Iq(e){return[{type:`HIDE_COLUMNS_ROWS`,sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}function Lq(e){return[{type:`REMOVE_TABLE_STYLE`,tableStyleId:e.tableStyleId}]}function Rq(e){return[{type:`RENAME_SHEET`,sheetId:e.sheetId,oldName:e.newName,newName:e.oldName}]}let zq=new B;zq.add(`format_number_automatic`,{...FR,id:`format_number_automatic`,sequence:10}).add(`format_number_plain_text`,{...IR,id:`format_number_plain_text`,sequence:15,separator:!0}).add(`format_number_number`,{...LR,id:`format_number_number`,sequence:20}).add(`format_number_percent`,{...zR,id:`format_number_percent`,sequence:30,separator:!1}).add(`format_number_scientific`,{...BR,id:`format_number_scientific`,sequence:33,separator:!0}).add(`format_number_currency`,{...VR,id:`format_number_currency`,sequence:40}).add(`format_number_accounting`,{...UR,id:`format_number_accounting`,sequence:45}).add(`format_number_currency_rounded`,{...HR,id:`format_number_currency_rounded`,sequence:50,separator:!0}).add(`format_number_date`,{...KR,id:`format_number_date`,sequence:70}).add(`format_number_time`,{...qR,id:`format_number_time`,sequence:80}).add(`format_number_date_time`,{...JR,id:`format_number_date_time`,sequence:90}).add(`format_number_duration`,{...YR,id:`format_number_duration`,sequence:100,separator:!0}).add(`format_custom_currency`,{...GR,id:`format_custom_currency`,sequence:120}).add(`format_custom_date`,{...XR,id:`format_custom_date`,sequence:130}).add(`format_custom_number`,{...ZR,id:`format_custom_number`,sequence:140});function Bq(e){let t=new Set(zq.getAll().map(t=>typeof t.format==`function`?t.format(e):t.format)),n=new Map;for(let r of e.model.getters.getSheetIds()){let i=e.model.getters.getEvaluatedCells(r);for(let e in i){let r=i[e];if(r.format&&!n.has(r.format)&&!t.has(r.format)){let e=Vq(r.format);(e===`date`||e===`currency`)&&n.set(r.format,PR({descriptionValue:e===`currency`?1e3:WR,format:r.format,name:r.format}))}}}return[...n.values()]}let Vq=Dt(e=>ns(e)?`date`:e.includes(`[$`)?`currency`:`number`),Hq={name:k(`More formats`),icon:`o-spreadsheet-Icon.NUMBER_FORMATS`,children:[e=>{let t=Bq(e).map(e=>({...e,sequence:110}));return t.length>0&&(t[t.length-1].separator=!0),[...zq.getAll(),...t]}]};function Uq(e){let t=new Zk;return t.add(`delete`,{...Wk,sequence:10}).add(`hide_sheet`,{...Xk,sequence:20}).add(`duplicate`,{...Gk,sequence:30,separator:!0}).add(`rename`,{...Kk(e),sequence:40}).add(`change_color`,{...qk(e),sequence:50,separator:!0}).add(`move_right`,{...Jk,sequence:60}).add(`move_left`,{...Yk,sequence:70}),t}let Wq=new Zk;Wq.add(`file`,{name:k(`File`),sequence:10}).addChild(`settings`,[`file`],{name:k(`Settings`),sequence:200,execute:e=>e.openSidePanel(`Settings`),isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.COG`}).add(`edit`,{name:k(`Edit`),sequence:20}).addChild(`undo`,[`edit`],{...dI,sequence:10}).addChild(`redo`,[`edit`],{...fI,sequence:20,separator:!0}).addChild(`copy`,[`edit`],{...pI,sequence:30}).addChild(`cut`,[`edit`],{...mI,sequence:40}).addChild(`paste`,[`edit`],{...hI,sequence:50}).addChild(`paste_special`,[`edit`],{...gI,sequence:60,separator:!0}).addChild(`paste_special_value`,[`edit`,`paste_special`],{..._I,sequence:10}).addChild(`paste_special_format`,[`edit`,`paste_special`],{...vI,sequence:20}).addChild(`edit_table`,[`edit`],{...jI,isVisible:uF,sequence:60}).addChild(`find_and_replace`,[`edit`],{...yI,sequence:65,separator:!0}).addChild(`delete`,[`edit`],{name:k(`Delete`),icon:`o-spreadsheet-Icon.TRASH`,sequence:70}).addChild(`edit_delete_cell_values`,[`edit`,`delete`],{...bI,sequence:10}).addChild(`edit_delete_row`,[`edit`,`delete`],{...xI,sequence:20}).addChild(`edit_delete_column`,[`edit`,`delete`],{...wI,sequence:30}).addChild(`edit_delete_cell_shift_up`,[`edit`,`delete`],{...OI,sequence:40}).addChild(`edit_delete_cell_shift_left`,[`edit`,`delete`],{...kI,sequence:50}).addChild(`edit_unhide_columns`,[`edit`],{...EF,sequence:80}).addChild(`edit_unhide_rows`,[`edit`],{...kF,sequence:80}).add(`view`,{name:k(`View`),sequence:30}).addChild(`unfreeze_panes`,[`view`],{...AF,sequence:4}).addChild(`freeze_panes`,[`view`],{...jF,sequence:5}).addChild(`unfreeze_rows`,[`view`,`freeze_panes`],{...MF,sequence:5}).addChild(`freeze_first_row`,[`view`,`freeze_panes`],{...NF,sequence:10}).addChild(`freeze_second_row`,[`view`,`freeze_panes`],{...PF,sequence:15}).addChild(`freeze_current_row`,[`view`,`freeze_panes`],{...FF,sequence:20,separator:!0}).addChild(`unfreeze_columns`,[`view`,`freeze_panes`],{...IF,sequence:25}).addChild(`freeze_first_col`,[`view`,`freeze_panes`],{...LF,sequence:30}).addChild(`freeze_second_col`,[`view`,`freeze_panes`],{...RF,sequence:35}).addChild(`freeze_current_col`,[`view`,`freeze_panes`],{...zF,sequence:40}).addChild(`group_headers`,[`view`],{name:k(`Group`),sequence:15,separator:!0,icon:`o-spreadsheet-Icon.PLUS_IN_BOX`,isVisible:gF}).addChild(`group_columns`,[`view`,`group_headers`],{...WF,sequence:5}).addChild(`ungroup_columns`,[`view`,`group_headers`],{...KF,isVisible:e=>XF(e,`COL`),sequence:10}).addChild(`group_rows`,[`view`,`group_headers`],{...GF,sequence:15}).addChild(`ungroup_rows`,[`view`,`group_headers`],{...qF,isVisible:e=>XF(e,`ROW`),sequence:20}).addChild(`show`,[`view`],{name:k(`Show`),sequence:1,icon:`o-spreadsheet-Icon.SHOW`}).addChild(`view_gridlines`,[`view`,`show`],{...BF,sequence:5}).addChild(`view_formulas`,[`view`,`show`],{...UF,sequence:10}).addChild(`zoom`,[`view`],{name:k(`Zoom`),sequence:1,icon:`o-spreadsheet-Icon.ZOOM`}).addChild(`view_irregularity_map`,[`view`],{...VF,sequence:40,separator:!0}).add(`insert`,{name:k(`Insert`),sequence:40}).addChild(`insert_row`,[`insert`],{...II,sequence:10}).addChild(`insert_row_before`,[`insert`,`insert_row`],{...RI,sequence:10}).addChild(`insert_row_after`,[`insert`,`insert_row`],{...VI,sequence:20}).addChild(`insert_column`,[`insert`],{...HI,sequence:20}).addChild(`insert_column_before`,[`insert`,`insert_column`],{...WI,sequence:10}).addChild(`insert_column_after`,[`insert`,`insert_column`],{...qI,sequence:20}).addChild(`insert_cell`,[`insert`],{...JI,sequence:30}).addChild(`insert_cell_down`,[`insert`,`insert_cell`],{...YI,name:k(`Shift down`),sequence:10}).addChild(`insert_cell_right`,[`insert`,`insert_cell`],{...XI,name:k(`Shift right`),sequence:20}).addChild(`insert_sheet`,[`insert`],{...mL,sequence:40,separator:!0}).addChild(`insert_chart`,[`insert`],{...ZI,sequence:50}).addChild(`insert_carousel`,[`insert`],{...QI,sequence:51}).addChild(`insert_pivot`,[`insert`],{...$I,sequence:52}).addChild(`insert_image`,[`insert`],{...eL,sequence:55}).addChild(`insert_table`,[`insert`],{...tL,sequence:57}).addChild(`insert_function`,[`insert`],{...nL,sequence:60}).addChild(`insert_function_sum`,[`insert`,`insert_function`],{...rL,sequence:0}).addChild(`insert_function_average`,[`insert`,`insert_function`],{...iL,sequence:10}).addChild(`insert_function_count`,[`insert`,`insert_function`],{...aL,sequence:20}).addChild(`insert_function_max`,[`insert`,`insert_function`],{...oL,sequence:30}).addChild(`insert_function_min`,[`insert`,`insert_function`],{...sL,sequence:40,separator:!0}).addChild(`categorie_function_all`,[`insert`,`insert_function`],{...cL,sequence:50}).addChild(`categories_function_list`,[`insert`,`insert_function`],uL).addChild(`insert_link`,[`insert`],{...dL,separator:!0,sequence:70}).addChild(`insert_checkbox`,[`insert`],{...fL,sequence:80}).addChild(`insert_dropdown`,[`insert`],{...pL,separator:!0,sequence:90}).add(`format`,{name:k(`Format`),sequence:50}).addChild(`format_number`,[`format`],{...Hq,name:k(`Number`),sequence:10,separator:!0}).addChild(`format_bold`,[`format`],{...ez,sequence:20}).addChild(`format_italic`,[`format`],{...tz,sequence:30}).addChild(`format_underline`,[`format`],{...nz,sequence:40}).addChild(`format_strikethrough`,[`format`],{...dz,sequence:50,separator:!0}).addChild(`format_font_size`,[`format`],{...fz,sequence:60,separator:!0}).addChild(`format_alignment`,[`format`],{...pz,sequence:70}).addChild(`format_alignment_left`,[`format`,`format_alignment`],{...hz,sequence:10}).addChild(`format_alignment_center`,[`format`,`format_alignment`],{...gz,sequence:20}).addChild(`format_alignment_right`,[`format`,`format_alignment`],{..._z,sequence:30,separator:!0}).addChild(`format_alignment_top`,[`format`,`format_alignment`],{...yz,sequence:40}).addChild(`format_alignment_middle`,[`format`,`format_alignment`],{...bz,sequence:50}).addChild(`format_alignment_bottom`,[`format`,`format_alignment`],{...xz,sequence:60,separator:!0}).addChild(`format_wrapping`,[`format`],{...Sz,sequence:80,separator:!0}).addChild(`format_wrapping_overflow`,[`format`,`format_wrapping`],{...wz,sequence:10}).addChild(`format_wrapping_wrap`,[`format`,`format_wrapping`],{...Tz,sequence:20}).addChild(`format_wrapping_clip`,[`format`,`format_wrapping`],{...Ez,sequence:30}).addChild(`format_cf`,[`format`],{...Dz,sequence:90,separator:!0}).addChild(`format_clearFormat`,[`format`],{...Oz,sequence:100,separator:!0}).add(`data`,{name:k(`Data`),sequence:60}).addChild(`sort_range`,[`data`],{...CR,sequence:10,separator:!0}).addChild(`sort_ascending`,[`data`,`sort_range`],{...wR,sequence:10}).addChild(`sort_descending`,[`data`,`sort_range`],{...OR,sequence:20}).addChild(`data_cleanup`,[`data`],{...TR,sequence:15}).addChild(`remove_duplicates`,[`data`,`data_cleanup`],{...ER,sequence:10}).addChild(`trim_whitespace`,[`data`,`data_cleanup`],{...DR,sequence:20}).addChild(`split_to_columns`,[`data`],{...jR,sequence:20}).addChild(`data_validation`,[`data`],{name:k(`Data Validation`),execute:e=>{e.openSidePanel(`DataValidation`)},isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.DATA_VALIDATION`,sequence:30,separator:!0}).addChild(`add_remove_data_filter`,[`data`],{...kR,sequence:40,separator:!0}).addChild(`pivot_data_sources`,[`data`],e=>{let t=e.model.getters.getPivotIds().length;return e.model.getters.getPivotIds().map((n,r)=>{let i={get highlights(){return GH(e.model.getters,n)}};return{id:`item_pivot_${e.model.getters.getPivotFormulaId(n)}`,name:e.model.getters.getPivotDisplayName(n),sequence:50+r/t,isReadonlyAllowed:!0,execute:e=>e.openSidePanel(`PivotSidePanel`,{pivotId:n}),isEnabled:e=>!e.isSmall,onStartHover:e=>e.getStore(sk).register(i),onStopHover:e=>e.getStore(sk).unRegister(i),icon:`o-spreadsheet-Icon.PIVOT`,separator:r===e.model.getters.getPivotIds().length-1,secondaryIcon:e=>e.model.getters.isPivotUnused(n)?`o-spreadsheet-Icon.UNUSED_PIVOT_WARNING`:void 0}})}).addChild(`reinsert_dynamic_pivot`,[`data`],MR).addChild(`reinsert_static_pivot`,[`data`],NR),ve.forEach(e=>{Wq.addChild(`zoom${e}`,[`view`,`zoom`],HF(e))});let Gq=[Kq,qq,Yq,Xq];function Kq(e,t){return`sheetId`in t?{...b(t),sheetId:e.getActiveSheetId()}:t}function qq(e,t){return!(`target`in t)||!Array.isArray(t.target)?t:{...b(t),target:e.getSelectedZones()}}function Jq(e,t){return`zone`in t?{...b(t),zone:e.getSelectedZone()}:t}function Yq(e,t){if(!(`row`in t)||!(`col`in t))return t;let{col:n,row:r}=e.getActivePosition();return{...b(t),col:n,row:r}}function Xq(e,t){return`ranges`in t?{...b(t),ranges:e.getSelectedZones().map(t=>e.getRangeDataFromZone(e.getActiveSheetId(),t))}:t}let Zq=new Gl;function Qq(e,t){let n=Zq.smallUuid();return{...Kq(e,t),figureId:n,chartId:n}}function $q(e,t){return{...Kq(e,t),figureId:Zq.smallUuid()}}function eJ(e,t){let n=Yq(e,Kq(e,t));return n.figureId=Zq.smallUuid(),n}function tJ(e,t){let n=b(t);n.sheetId=Zq.smallUuid();let r=t.name||e.getSheet(e.getActiveSheetId()).name,i=r.match(/(.+?)\d*$/)?.[1]||r;return n.name=e.getNextSheetName(i),n}function nJ(e,t){let n=e.getActivePosition();return{...Kq(e,t),base:t.dimension===`COL`?n.col:n.row}}function rJ(e,t){let n=e.getSelectedZone();return{...Kq(e,t),elements:t.dimension===`COL`?S(n.left,n.right+1):S(n.top,n.bottom+1)}}function iJ(e,t){let n=e.getSelectedZone();return{...b(t),zone:n}}function aJ(e,t){let n=b(t),{top:r,bottom:i,left:a,right:o}=e.getSelectedZone();return`cols`in n?n.cols=S(a,o+1):`rows`in n&&(n.rows=S(r,i+1)),n}function oJ(e,t){let n=e.getSelectedZone();return{...Kq(e,t),col:n.left,row:n.top,zone:n}}function sJ(e,t){return{type:`REPEAT_PASTE`,pasteOption:b(t.pasteOption),target:e.getSelectedZones()}}function cJ(e,t){let n=e.getSelectedZone();return{...Kq(e,t),start:t.dimension===`COL`?n.left:n.top,end:t.dimension===`COL`?n.right:n.bottom}}BK.add(`UPDATE_CELL`,lJ),BK.add(`CLEAR_CELL`,lJ),BK.add(`CLEAR_CELLS`,lJ),BK.add(`DELETE_CONTENT`,lJ),BK.add(`ADD_MERGE`,lJ),BK.add(`REMOVE_MERGE`,lJ),BK.add(`SET_FORMATTING`,lJ),BK.add(`CLEAR_FORMATTING`,lJ),BK.add(`SET_BORDER`,lJ),BK.add(`CREATE_TABLE`,lJ),BK.add(`REMOVE_TABLE`,lJ),BK.add(`HIDE_SHEET`,lJ),BK.add(`ADD_COLUMNS_ROWS`,nJ),BK.add(`REMOVE_COLUMNS_ROWS`,rJ),BK.add(`HIDE_COLUMNS_ROWS`,rJ),BK.add(`RESIZE_COLUMNS_ROWS`,rJ),BK.add(`CREATE_SHEET`,tJ),BK.add(`CREATE_FIGURE`,eJ),BK.add(`CREATE_CHART`,Qq),BK.add(`CREATE_IMAGE`,$q),BK.add(`GROUP_HEADERS`,cJ),BK.add(`UNGROUP_HEADERS`,cJ),BK.add(`UNFOLD_HEADER_GROUPS_IN_ZONE`,Jq),BK.add(`FOLD_HEADER_GROUPS_IN_ZONE`,Jq),VK.add(`PASTE`,sJ),VK.add(`INSERT_CELL`,iJ),VK.add(`DELETE_CELL`,iJ),VK.add(`AUTORESIZE_COLUMNS`,aJ),VK.add(`AUTORESIZE_ROWS`,aJ),VK.add(`SORT_CELLS`,oJ),VK.add(`SUM_SELECTION`,lJ),VK.add(`SET_DECIMAL`,lJ),VK.add(`DELETE_UNFILTERED_CONTENT`,lJ);function lJ(e,t){let n=b(t);for(let t of Gq)n=t(e,n);return n}let uJ=new class extends B{mapping={};uuidGenerator=new Gl;replace(e,t){let n={...t,id:this.uuidGenerator.uuidv4()};return super.replace(e,n)}getAllOrdered(){return this.getAll().sort((e,t)=>e.sequence-t.sequence)}};var dJ=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)}},fJ=class{fileStore;constructor(e){this.fileStore=e}async requestImage(){let e=await this.userImageUpload(),t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}async uploadFile(e){let t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}userImageUpload(){return new Promise((e,t)=>{let n=document.createElement(`input`);n.setAttribute(`type`,`file`),n.setAttribute(`accept`,`image/*`),n.addEventListener(`change`,async()=>{n.files===null||n.files.length!==1?t():e(n.files[0])}),n.click()})}getImageOriginalSize(e){return new Promise((t,n)=>{let r=new Image;r.addEventListener(`load`,()=>{t({width:r.width,height:r.height})}),r.addEventListener(`error`,n),r.src=e})}};let pJ=[{transform:`scale(0)`},{transform:`scale(0.8)`,offset:.33},{opacity:`0`,transform:`scale(1)`,offset:1}];var mJ=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(pJ,{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}`})}},hJ=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:mJ};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{...tp(e),marginLeft:0,marginTop:0};let t=e.firstElementChild,n=fv(t);return{...tp(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 gJ(e,t,n,r){let i=e.model.dispatch(`RENAME_SHEET`,{sheetId:t,newName:n,oldName:e.model.getters.getSheetName(t)});i.reasons.includes(`MissingSheetName`)?e.raiseError(k(`The sheet name cannot be empty.`),r):i.reasons.includes(`DuplicatedSheetName`)?e.raiseError(k(`A sheet with the name %s already exists. Please select another name.`,n),r):i.reasons.includes(`ForbiddenCharactersInSheetName`)&&e.raiseError(k(`Some used characters are not allowed in a sheet name (Forbidden characters are %s).`,je.join(` `)),r)}var _J=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:hJ,ColorPicker:yk};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=D(xO),(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()}onClick(){this.env.isMobile()&&this.activateSheet()}onMouseDown(e){this.env.isMobile()||(this.activateSheet(),this.props.onMouseDown(e))}activateSheet(){this.env.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:this.env.model.getters.getActiveSheetId(),sheetIdTo:this.props.sheetId}),this.scrollToSheet()}onDblClick(){this.env.model.getters.isReadonly()||this.startEdition()}onKeyDown(e){this.state.isEditing&&(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()||``;gJ(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 tp(e)}get contextMenuRegistry(){return Uq({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 vJ=[{name:k(`Sum`),types:[`number`],compute:(e,t)=>Vm([[e]],t)},{name:k(`Avg`),types:[`number`],compute:(e,t)=>vm([[e]],t)},{name:k(`Min`),types:[`number`],compute:(e,t)=>Sm([[e]],t).value},{name:k(`Max`),types:[`number`],compute:(e,t)=>xm([[e]],t).value},{name:k(`Count`),types:[`number`,`text`,`boolean`,`error`],compute:e=>bm([[e]])},{name:k(`Count Numbers`),types:[`number`,`text`,`boolean`,`error`],compute:(e,t)=>ym([[e]],t)}];var yJ=class extends hr{statisticFnResults=this._computeStatisticFnResults();isDirty=!1;constructor(e){super(e),this.model.selection.observe(this,{handleEvent:this.handleEvent.bind(this)}),this.onDispose(()=>{this.model.selection.unobserve(this)})}handle(e){switch((Ps.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=Qt(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=Dt(e=>{let t=e.split(`,`);return n.filter(e=>t.includes(e.type))});for(let e of vJ){let t,n=c(e.types.sort().join(`,`));n.length&&(t=mt(()=>e.compute(n,o))),s[e.name]=t}return s}},bJ=class extends t.Component{static template=`o-spreadsheet-BottomBarStatistic`;static props={openContextMenu:Function,closeContextMenu:Function};static components={Ripple:hJ};selectedStatisticFn=``;store;setup(){this.store=D(yJ),(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 Zk,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?`__`:z(n(),{locale:t}))}},xJ=class extends t.Component{static template=`o-spreadsheet-BottomBar`;static props={onClick:Function};static components={MenuPopover:Dv,Ripple:hJ,BottomBarSheet:_J,BottomBarStatistic:bJ};bottomBarRef=(0,t.useRef)(`bottomBar`);sheetListRef=(0,t.useRef)(`sheetList`);dragAndDrop=Sk();targetScroll=void 0;state=(0,t.useState)({isSheetListScrollableLeft:!1,isSheetListScrollableRight:!1});menuMaxHeight=250;menuState=(0,t.useState)({isOpen:!1,menuId:void 0,anchorRect:null,menuItems:[]});sheetList=this.getVisibleSheets();setup(){(0,t.onWillUpdateProps)(()=>{this.updateScrollState();let e=this.getVisibleSheets();w(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(k(`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 Zk,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.anchorRect={x:e,y:t,width:0,height:0}}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.anchorRect=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()||(this.closeMenu(),this.env.isMobile()))return;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}},SJ=class extends hr{_clickableCells=(0,t.markRaw)({});_registryItems=(0,t.markRaw)(bq.getAll().sort((e,t)=>e.sequence-t.sequence));handle(e){(Ps.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)(bq.getAll().sort((e,t)=>e.sequence-t.sequence)))}getClickableItem(e){let{sheetId:t,col:n,row:r}=e,i=this._clickableCells,a=T(n,r);if(i[t]||(i[t]={}),!(a in i[t])){let n=this.findClickableItem(e);i[t][a]=n}return i[t][a]}findClickableItem(e){let t=this.getters;for(let n of this._registryItems)if(n.condition(e,t))return n}get clickableCells(){let e=[],t=this.getters;for(let n of this.getters.getVisibleCellPositions()){let r=this.getClickableItem(n);if(!r)continue;let i=typeof r.title==`function`?r.title(n,t):r.title,a=this.getClickableCellRect(n);a&&e.push({coordinates:a,position:n,action:r.execute,title:i||``,component:r.component,componentProps:r.componentProps?.(n,t)??{}})}return e}getClickableCellRect(e){let t=this.getters.expandZone(e.sheetId,E(e)),n=this.getters.getVisibleRect(t),r=this.getters.getCellIcons(e),i={center:r.find(e=>e.horizontalAlign===`center`),left:r.find(e=>e.horizontalAlign===`left`),right:r.find(e=>e.horizontalAlign===`right`)};if(!i.center?.onClick){if(i.right?.onClick){let e=this.getters.getRect(t),r=this.getters.getCellIconRect(i.right,e);n.width-=r.width+i.right.margin}if(i.left?.onClick){let e=this.getters.getRect(t),r=this.getters.getCellIconRect(i.left,e);n.x+=r.width+i.left.margin,n.width-=r.width+i.left.margin}return n}}},CJ=class extends t.Component{static template=`o-spreadsheet-SpreadsheetDashboard`;static props={getGridSize:Function};static components={GridOverlay:KB,GridPopover:qB,Popover:Cv,VerticalScrollBar:fV,HorizontalScrollBar:dV};cellPopovers;onMouseWheel;canvasPosition;hoveredCell;clickableCellsStore;gridRef;setup(){this.gridRef=(0,t.useRef)(`grid`),this.hoveredCell=D(Pv),this.clickableCellsStore=D(SJ),(0,t.useChildSubEnv)({getPopoverContainerRect:()=>xp(this.env.model.getters.getViewportZoomLevel(),this.getGridRect())}),tV(`canvas`,this.env.model,()=>this.env.model.getters.getSheetViewDimension()),this.onMouseWheel=iV((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=D(Bk),rV(this.gridRef,this.moveCanvas.bind(this),()=>{let{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0},()=>{let{maxOffsetY:e}=this.env.model.getters.getMaximumSheetOffset(),{scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo();return t<e})}get gridContainer(){return U({"max-width":`${this.getMaxSheetWidth()}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,t){let{position:n,action:r}=t;r(n,this.env,dp(e))}onClosePopover(){this.cellPopovers.close()}onGridResized(){let{height:e,width:t}=this.props.getGridSize(),n=this.getMaxSheetWidth();this.env.model.dispatch(`RESIZE_SHEETVIEW`,{width:Math.min(n,t),height:e,gridOffsetX:0,gridOffsetY:0})}moveCanvas(e,t){let{scrollX:n,scrollY:r}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:n+e,offsetY:r+t})}getGridRect(){return{...ep(this.gridRef),...this.env.model.getters.getSheetViewDimensionWithHeaders()}}getMaxSheetWidth(){let e=this.env.model.getters.getActiveSheetId(),{right:t}=this.env.model.getters.getSheetZone(e);return this.env.model.getters.getColDimensions(e,t).end}},wJ=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;Hz(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=Wz(t,this.dimension,r.start,r.end);this.props.openContextMenu(n,i)}},TJ=class extends wJ{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`,"border-bottom":e.isEndHidden?``:`1px solid`})}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)}}},EJ=class extends wJ{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`,"border-right":e.isEndHidden?``:`1px solid`})}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)}}},DJ=class extends t.Component{static template=`o-spreadsheet-HeaderGroupContainer`;static props={dimension:String,layers:Array};static components={RowGroup:TJ,ColGroup:EJ,MenuPopover:Dv};menu=(0,t.useState)({isOpen:!1,anchorRect:null,menuItems:[]});getLayerOffset(e){return e*21}onContextMenu(e){let t=this.env.model.getters.getActiveSheetId(),n={x:e.clientX,y:e.clientY},r=Uz(t,this.props.dimension);this.openContextMenu(n,r)}openContextMenu(e,t){this.menu.isOpen=!0,this.menu.anchorRect={...e,width:0,height:0},this.menu.menuItems=t}closeMenu(){this.menu.isOpen=!1,this.menu.anchorRect=null,this.menu.menuItems=[]}get groupComponent(){return this.props.dimension===`ROW`?TJ:EJ}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}};function OJ(){let e=xv();return{get isSmall(){return e.width<768}}}var kJ=class extends t.Component{static template=`o-spreadsheet-SidePanel`;static props={panelContent:Object,panelProps:Object,onCloseSidePanel:Function,onStartHandleDrag:Function,onResetPanelSize:Function,isPinned:{type:Boolean,optional:!0},onTogglePinPanel:{type:Function,optional:!0},onToggleCollapsePanel:{type:Function,optional:!0},isCollapsed:{type:Boolean,optional:!0}};spreadsheetRect=xv();getTitle(){let e=this.props.panelContent;return typeof e.title==`function`?e.title(this.env,this.props.panelProps):e.title}get pinInfoMessage(){return k(`Pin this panel to allow to open another side panel beside it.`)}},AJ=class extends t.Component{static template=`o-spreadsheet-SidePanels`;static props={};static components={SidePanel:kJ};sidePanelStore;spreadsheetRect=xv();setup(){this.sidePanelStore=D(rW),(0,t.useEffect)(()=>{this.sidePanelStore.mainPanel&&!this.sidePanelStore.isMainPanelOpen&&this.sidePanelStore.closeMainPanel(),this.sidePanelStore.secondaryPanel&&!this.sidePanelStore.isSecondaryPanelOpen&&this.sidePanelStore.close()},()=>[this.sidePanelStore.isMainPanelOpen,this.sidePanelStore.isSecondaryPanelOpen])}startHandleDrag(e,t){let n=document.body.style.cursor,r=e===`mainPanel`?this.sidePanelStore.mainPanel:this.sidePanelStore.secondaryPanel;if(!r)return;let i=r.size,a=t.clientX;vk(t=>{document.body.style.cursor=`col-resize`;let n=i+a-t.clientX;this.sidePanelStore.changePanelSize(e,n)},()=>{document.body.style.cursor=n})}get mainPanelProps(){let e=this.sidePanelStore.mainPanelProps;if(!(!this.sidePanelStore.mainPanel||!e))return{panelContent:tW.get(this.sidePanelStore.mainPanel.componentTag),panelProps:e,onCloseSidePanel:()=>this.sidePanelStore.closeMainPanel(),onTogglePinPanel:()=>this.sidePanelStore.togglePinPanel(),onStartHandleDrag:e=>this.startHandleDrag(`mainPanel`,e),onResetPanelSize:()=>this.sidePanelStore.resetPanelSize(`mainPanel`),isPinned:this.sidePanelStore.mainPanel?.isPinned,onToggleCollapsePanel:()=>this.sidePanelStore.toggleCollapsePanel(`mainPanel`),isCollapsed:this.sidePanelStore.mainPanel?.isCollapsed}}get secondaryPanelProps(){let e=this.sidePanelStore.secondaryPanelProps;if(!(!this.sidePanelStore.secondaryPanel||!e))return{panelContent:tW.get(this.sidePanelStore.secondaryPanel.componentTag),panelProps:e,onCloseSidePanel:()=>this.sidePanelStore.close(),onStartHandleDrag:e=>this.startHandleDrag(`secondaryPanel`,e),onResetPanelSize:()=>this.sidePanelStore.resetPanelSize(`secondaryPanel`),onToggleCollapsePanel:()=>this.sidePanelStore.toggleCollapsePanel(`secondaryPanel`),isCollapsed:this.sidePanelStore.secondaryPanel?.isCollapsed}}get panelList(){return[{key:this.sidePanelStore.secondaryPanelKey,props:this.secondaryPanelProps,style:this.sidePanelStore.secondaryPanel?U({width:`${this.sidePanelStore.secondaryPanel.size}px`}):``},{key:this.sidePanelStore.mainPanelKey,props:this.mainPanelProps,style:this.sidePanelStore.mainPanel?U({width:`${this.sidePanelStore.mainPanel.size}px`}):``}].filter(e=>e.key&&e.props)}},jJ=class extends t.Component{static template=`o-spreadsheet-RibbonMenu`;static props={onClose:Function};static components={Menu:hv};rootItems=Wq.getMenuItems();menuRef=(0,t.useRef)(`menu`);containerRef=(0,t.useRef)(`container`);state=(0,t.useState)({menuItems:this.rootItems,title:k(`Menu Bar`),parentState:void 0});setup(){(0,t.useExternalListener)(window,`click`,this.onExternalClick,{capture:!0}),(0,t.onMounted)(this.updateShadows)}onExternalClick(e){this.menuRef.el?.contains(e.target)||this.props.onClose()}onClickMenu(e){let t=e.children(this.env);t.length?(this.state.parentState={...this.state},this.state.menuItems=t,this.state.title=e.name(this.env),this.containerRef.el?.scrollTo({top:0})):(this.state.menuItems=this.rootItems,this.state.title=void 0,this.state.parentState=void 0,e.execute?.(this.env),this.props.onClose())}get menuProps(){return{menuItems:g(this.env,this.state.menuItems),onClose:this.props.onClose,onClickMenu:this.onClickMenu.bind(this)}}get style(){return U({height:`${this.props.height}px`})}updateShadows(){if(!this.containerRef.el)return;this.containerRef.el.classList.remove(`scroll-top`,`scroll-bottom`);let e=this.containerRef.el.scrollHeight-this.containerRef.el.clientHeight||0;this.containerRef.el.scrollTop<e-1&&this.containerRef.el.classList.add(`scroll-bottom`),this.containerRef.el.scrollTop>0&&this.containerRef.el.classList.add(`scroll-top`)}onClickBack(){if(!this.state.parentState){this.props.onClose();return}this.state.menuItems=this.state.parentState.menuItems,this.state.title=this.state.parentState.title,this.state.parentState=this.state.parentState.parentState,this.containerRef.el?.scrollTo({top:0})}get backTitle(){return this.state.parentState?k(`Go to previous menu`):k(`Close menu bar`)}},MJ=class extends t.Component{static components={Composer:PO,BottomBar:xJ,Ripple:hJ,RibbonMenu:jJ};static template=`o-spreadsheet-SmallBottomBar`;static props={onClick:Function};composerFocusStore;composerStore;composerInterface;composerRef=(0,t.useRef)(`bottombarComposer`);menuState=(0,t.useState)({isOpen:!1});setup(){this.composerFocusStore=D(_r);let e=D(CB);this.composerStore=e,this.composerInterface={id:`bottombarComposer`,get editionMode(){return e.editionMode},startEdition:this.composerStore.startEdition,setCurrentContent:this.composerStore.setCurrentContent,stopEdition:this.composerStore.stopEdition},(0,t.useEffect)(()=>{this.env.isMobile()&&!this.menuState.isOpen&&this.composerStore.editionMode!==`inactive`&&this.composerFocusStore.activeComposer!==this.composerInterface&&this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`contentFocus`})})}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:`inactive`}get showFxIcon(){return this.focus===`inactive`&&!this.composerStore.currentContent&&!this.composerStore.placeholder}get rect(){return this.composerRef.el?tp(this.composerRef.el):{x:0,y:0,width:0,height:0}}get composerProps(){let{width:e,height:t}=this.env.model.getters.getSheetViewDimensionWithHeaders();return{rect:{...this.rect},delimitation:{width:e,height:t},focus:this.focus,composerStore:this.composerStore,onComposerContentFocused:e=>this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`contentFocus`,selection:e}),isDefaultFocus:!1,inputStyle:U({height:this.focus===`inactive`?`26px`:`fit-content`,"max-height":`130px`}),showAssistant:!1,placeholder:this.composerStore.placeholder}}get symbols(){return[`=`,`(`,`)`,`:`,`-`,`/`,`*`,`,`,`+`,`$`,`.`]}insertSymbol(e){this.composerStore.replaceComposerCursorSelection(e),this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`contentFocus`})}toggleRibbon(){this.composerStore.cancelEdition(),this.menuState.isOpen=!this.menuState.isOpen}},NJ=class extends t.Component{static template=`o-spreadsheet-TopBarComposer`;static props={};static components={Composer:PO};composerFocusStore;composerStore;composerInterface;setup(){this.composerFocusStore=D(_r);let e=D(CB);this.composerStore=e,this.composerInterface={id:`topbarComposer`,get editionMode(){return e.editionMode},startEdition:this.composerStore.startEdition,setCurrentContent:this.composerStore.setCurrentContent,stopEdition:this.composerStore.stopEdition}}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:`inactive`}get showFxIcon(){return this.focus===`inactive`&&!this.composerStore.currentContent&&!this.composerStore.placeholder}get composerStyle(){let e={padding:`5px 0px 5px 8px`,"max-height":`300px`,"line-height":`24px`};return e.height=this.focus===`inactive`?`34px`:`fit-content`,U(e)}onFocus(e){this.composerFocusStore.focusComposer(this.composerInterface,{selection:e})}},PJ=class{mutators=[`closeDropdowns`,`openDropdown`];_currentDropdown=null;closeDropdowns(){this._currentDropdown=null}openDropdown(e){this._currentDropdown=e}get currentDropdown(){return this._currentDropdown}},FJ=class{content={};add(e){if(e in this.content)throw Error(`${e} is already present in this registry!`);return this.content[e]=[],this}addChild(e,t){return this.content[e].push(t),this}getEntries(e){return this.content[e].sort((e,t)=>e.sequence-t.sequence)}getCategories(){return Object.keys(this.content)}};function IJ(){let e=(0,t.useComponent)(),n=D(PJ);return(0,t.onWillUnmount)(()=>{e===n.currentDropdown&&n.closeDropdowns()}),{closeDropdowns:()=>n.closeDropdowns(),openDropdown:()=>{n.openDropdown(e)},get isActive(){return n.currentDropdown===e}}}let LJ=[[[`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`]]];var RJ=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:vV,Popover:Cv};BORDER_POSITIONS=LJ;lineStyleButtonRef=(0,t.useRef)(`lineStyleButton`);borderStyles=ba;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:`bottom-left`,verticalOffset:0}}get popoverProps(){return{anchorRect:this.props.anchorRect,maxHeight:this.props.maxHeight,positioning:`bottom-left`,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}}},zJ=class extends t.Component{static template=`o-spreadsheet-BorderEditorWidget`;static props={disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};static components={BorderEditor:RJ};topBarToolStore;borderEditorButtonRef=(0,t.useRef)(`borderEditorButton`);state=(0,t.useState)({currentColor:Te.color,currentStyle:Te.style,currentPosition:void 0});setup(){this.topBarToolStore=IJ(),(0,t.onWillUpdateProps)(()=>{this.isActive||(this.state.currentPosition=void 0)})}get dropdownMaxHeight(){return this.env.model.getters.getSheetViewDimension().height}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()}get isActive(){return this.topBarToolStore.isActive}toggleBorderEditor(){this.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}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}})}},BJ=class extends t.Component{static template=`o-spreadsheet-PaintFormatButton`;static props={class:{type:String,optional:!0}};paintFormatStore;setup(){this.paintFormatStore=D(HB)}get isActive(){return this.paintFormatStore.isActive}onDblClick(){this.paintFormatStore.activate({persistent:!0})}togglePaintFormat(){this.isActive?this.paintFormatStore.cancel():this.paintFormatStore.activate({persistent:!1})}},VJ=class extends t.Component{static template=`o-spreadsheet-TableDropdownButton`;static components={TableStylesPopover:XU,ActionButton:_V};static props={class:{type:String,optional:!0}};topBarToolStore;state=(0,t.useState)({popoverProps:void 0});setup(){this.topBarToolStore=IJ()}onStylePicked(e){let t=this.env.model.getters.getActiveSheetId(),n={...this.tableConfig,styleId:e};kP(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.topBarToolStore.closeDropdowns(),this.env.toggleSidePanel(`TableSidePanel`,{});return}let{left:t,bottom:n}=e.currentTarget.getBoundingClientRect();this.topBarToolStore.openDropdown(),this.state.popoverProps={anchorRect:{x:t,y:n,width:0,height:0},positioning:`bottom-left`,verticalOffset:0}}closePopover(){this.state.popoverProps=void 0}get action(){return{name:e=>e.model.getters.getFirstTableInSelection()?k(`Edit table`):k(`Insert table`),icon:e=>e.model.getters.getFirstTableInSelection()?`o-spreadsheet-Icon.EDIT_TABLE`:`o-spreadsheet-Icon.PAINT_TABLE`}}get tableConfig(){return{...SA,numberOfHeaders:1,bandedRows:!0}}},HJ=class extends t.Component{static components={ColorPickerWidget:vV};static props={class:String,style:String,icon:String,title:String};static template=`o-spreadsheet-ColorEditor`;topBarToolStore;state=(0,t.useState)({isOpen:!1});setup(){this.topBarToolStore=IJ()}get currentColor(){return this.env.model.getters.getCurrentStyle()[this.props.style]||(this.props.style===`textColor`?`#000000`:`#ffffff`)}setColor(e){jP(this.env,{[this.props.style]:e}),this.state.isOpen=!1}get isMenuOpen(){return this.topBarToolStore.isActive}onClick(){this.isMenuOpen?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}},UJ=class extends t.Component{static template=`o-spreadsheet-DropdownAction`;static components={ActionButton:_V,Popover:Cv};static props={parentAction:Object,childActions:Array,class:String,childClass:String};topBarToolStore;actionRef=(0,t.useRef)(`actionRef`);setup(){this.topBarToolStore=IJ()}toggleDropdown(){this.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}get isActive(){return this.topBarToolStore.isActive}get popoverProps(){return{anchorRect:this.actionRef.el?this.actionRef.el.getBoundingClientRect():{x:0,y:0,width:0,height:0},positioning:`bottom-left`,verticalOffset:0,class:`rounded`}}},WJ=class extends t.Component{static components={FontSizeEditor:bV};static props={class:String};static template=`o-spreadsheet-TopBarFontSizeEditor`;topBarToolStore;setup(){this.topBarToolStore=IJ()}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||Ce}setFontSize(e){jP(this.env,{fontSize:e})}onToggle(){this.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}onFocusInput(){this.topBarToolStore.openDropdown()}get isActive(){return this.topBarToolStore.isActive}},GJ=class extends t.Component{static template=`o-spreadsheet-NumberFormatsTool`;static components={MenuPopover:Dv,ActionButton:_V};static props={class:String};formatNumberMenuItemSpec=Hq;topBarToolStore;buttonRef=(0,t.useRef)(`buttonRef`);state=(0,t.useState)({anchorRect:{x:0,y:0,width:0,height:0},menuItems:[]});setup(){this.topBarToolStore=IJ()}toggleMenu(){if(this.isActive)this.topBarToolStore.closeDropdowns();else{let e=h(this.formatNumberMenuItemSpec);this.state.menuItems=e.children(this.env).sort((e,t)=>e.sequence-t.sequence),this.state.anchorRect=tp(this.buttonRef.el),this.topBarToolStore.openDropdown()}}get isActive(){return this.topBarToolStore.isActive}},KJ=class extends t.Component{static template=`o-spreadsheet-TopBarZoom`;static components={NumberEditor:yV};static props={class:String};topBarToolStore;valueList=ve;setup(){this.topBarToolStore=IJ()}get currentFontSize(){return(this.env.model.getters.getViewportZoomLevel()||1)*100}setZoom(e){this.env.model.dispatch(`SET_ZOOM`,{zoom:e/100})}toggle(){this.topBarToolStore.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}onFocusInput(){this.topBarToolStore.openDropdown()}};let qJ=new FJ;qJ.add(`edit`).addChild(`edit`,{component:_V,props:{action:dI,class:`o-hoverable-button o-toolbar-button`},sequence:1}).addChild(`edit`,{component:_V,props:{action:fI,class:`o-hoverable-button o-toolbar-button`},sequence:2}).addChild(`edit`,{component:BJ,props:{class:`o-hoverable-button o-toolbar-button o-mobile-disabled`},sequence:3}).addChild(`edit`,{component:_V,props:{action:Oz,class:`o-hoverable-button o-toolbar-button`},sequence:4}).addChild(`edit`,{component:KJ,props:{class:`o-menu-item-button o-hoverable-button o-toolbar-button`},sequence:5}).add(`numberFormat`).addChild(`numberFormat`,{component:_V,props:{action:RR,class:`o-hoverable-button o-toolbar-button`},sequence:1}).addChild(`numberFormat`,{component:_V,props:{action:$R,class:`o-hoverable-button o-toolbar-button`},sequence:2}).addChild(`numberFormat`,{component:_V,props:{action:QR,class:`o-hoverable-button o-toolbar-button`},sequence:3}).addChild(`numberFormat`,{component:GJ,props:{class:`o-menu-item-button o-hoverable-button o-toolbar-button`},sequence:4}).add(`fontSize`).addChild(`fontSize`,{component:WJ,props:{class:`o-hoverable-button o-toolbar-button`},sequence:3}).add(`textStyle`).addChild(`textStyle`,{component:_V,props:{action:ez,class:`o-hoverable-button o-toolbar-button`},sequence:1}).addChild(`textStyle`,{component:_V,props:{action:tz,class:`o-hoverable-button o-toolbar-button`},sequence:2}).addChild(`textStyle`,{component:_V,props:{action:dz,class:`o-hoverable-button o-toolbar-button`},sequence:3}).addChild(`textStyle`,{component:HJ,props:{class:`o-hoverable-button o-menu-item-button o-toolbar-button`,style:`textColor`,icon:`o-spreadsheet-Icon.TEXT_COLOR`,title:k(`Text Color`)},sequence:4}).add(`cellStyle`).addChild(`cellStyle`,{component:HJ,props:{class:`o-hoverable-button o-menu-item-button o-toolbar-button`,style:`fillColor`,icon:`o-spreadsheet-Icon.FILL_COLOR`,title:k(`Fill Color`)},sequence:1}).addChild(`cellStyle`,{component:zJ,props:{class:`o-hoverable-button o-menu-item-button o-toolbar-button`},sequence:2}).addChild(`cellStyle`,{component:_V,props:{action:AI,class:`o-hoverable-button o-menu-item-button o-toolbar-button`},sequence:3}).add(`alignment`).addChild(`alignment`,{component:UJ,props:{parentAction:mz,childActions:[hz,gz,_z],class:`o-hoverable-button o-toolbar-button`,childClass:`o-hoverable-button`},sequence:1}).addChild(`alignment`,{component:UJ,props:{parentAction:vz,childActions:[yz,bz,xz],class:`o-hoverable-button o-menu-item-button o-toolbar-button`,childClass:`o-hoverable-button`},sequence:2}).addChild(`alignment`,{component:UJ,props:{parentAction:Cz,childActions:[wz,Tz,Ez],class:`o-hoverable-button o-menu-item-button o-toolbar-button`,childClass:`o-hoverable-button`},sequence:3}).addChild(`alignment`,{component:UJ,props:{parentAction:rz,childActions:[oz,sz,cz,lz,uz],class:`o-hoverable-button o-menu-item-button o-toolbar-button`,childClass:`o-hoverable-button`},sequence:4}).add(`misc`).addChild(`misc`,{component:VJ,props:{class:`o-toolbar-button o-hoverable-button o-menu-item-button o-mobile-disabled`},sequence:1}).addChild(`misc`,{component:_V,props:{action:AR,class:`o-hoverable-button o-menu-item-button o-toolbar-button`},sequence:2});var JJ=class extends t.Component{static template=`o-spreadsheet-TopBar`;static props={onClick:Function,dropdownMaxHeight:Number};static components={MenuPopover:Dv,TopBarComposer:NJ,Popover:Cv};toolsCategories=qJ.getCategories();state=(0,t.useState)({menuState:{isOpen:!1,anchorRect:null,menuItems:[]},invisibleToolsCategories:[],toolsPopoverState:{isOpen:!1}});isSelectingMenu=!1;openedEl=null;menus=[];toolbarMenuRegistry=qJ;formatNumberMenuItemSpec=Hq;isntToolbarMenu=!1;composerFocusStore;fingerprints;topBarToolStore;toolBarContainerRef=(0,t.useRef)(`toolBarContainer`);toolbarRef=(0,t.useRef)(`toolBar`);moreToolsContainerRef=(0,t.useRef)(`moreToolsContainer`);moreToolsButtonRef=(0,t.useRef)(`moreToolsButton`);spreadsheetRect=xv();setup(){this.composerFocusStore=D(_r),this.fingerprints=D(xF),this.topBarToolStore=D(PJ),(0,t.useExternalListener)(window,`click`,this.onExternalClick),(0,t.onWillStart)(()=>this.updateCellState()),(0,t.onWillUpdateProps)(()=>this.updateCellState()),(0,t.useEffect)(()=>{this.state.toolsPopoverState.isOpen=!1,this.setVisibilityToolsGroups()},()=>[this.spreadsheetRect.width])}setVisibilityToolsGroups(){if(this.env.model.getters.isReadonly())return;let e=[],{x:t}=this.toolbarRef.el.getBoundingClientRect(),{x:n}=this.toolBarContainerRef.el.getBoundingClientRect();this.moreToolsContainerRef.el?.classList.remove(`d-none`);let r=this.moreToolsButtonRef.el?.getBoundingClientRect().width||0,i=Math.round(this.spreadsheetRect.width)-r-(t-n)-16,a=document.querySelectorAll(`.tool-container`),o=0;for(let t=0;t<a.length;t++){let n=a[t];n.classList.remove(`d-none`);let{width:r}=n.getBoundingClientRect();o+=r,o>i&&(n.classList.add(`d-none`),e.push(this.toolsCategories[t]))}this.state.invisibleToolsCategories=e,e.length||this.moreToolsContainerRef.el?.classList.add(`d-none`)}get topbarComponents(){return uJ.getAllOrdered().filter(e=>!e.isVisible||e.isVisible(this.env))}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||Ce}onExternalClick(e){this.openedEl!==e.target&&this.closeMenus()}onClick(){this.props.onClick(),this.closeMenus()}onMenuMouseOver(e,t){this.isSelectingMenu&&this.isntToolbarMenu&&this.openMenu(e,t)}toggleContextMenu(e,t){this.state.menuState.isOpen&&this.isntToolbarMenu?this.closeMenus():(this.openMenu(e,t),this.isntToolbarMenu=!0)}openMenu(e,t){this.topBarToolStore.currentDropdown&&this.topBarToolStore.closeDropdowns(),this.state.toolsPopoverState.isOpen=!1,this.state.menuState.isOpen=!0,this.state.menuState.anchorRect=tp(t.currentTarget),this.state.menuState.menuItems=e.children(this.env).sort((e,t)=>e.sequence-t.sequence),this.state.menuState.parentMenu=e,this.isSelectingMenu=!0,this.openedEl=t.target,this.composerFocusStore.activeComposer.stopEdition()}closeMenus(){this.topBarToolStore.currentDropdown&&this.topBarToolStore.closeDropdowns(),this.state.toolsPopoverState.isOpen=!1,this.state.menuState.isOpen=!1,this.state.menuState.parentMenu=void 0,this.isSelectingMenu=!1,this.openedEl=null}updateCellState(){this.menus=Wq.getMenuItems()}getMenuName(e){return e.name(this.env)}setColor(e,t){jP(this.env,{[e]:t}),this.onClick()}setFontSize(e){jP(this.env,{fontSize:e})}toggleMoreTools(){this.topBarToolStore.currentDropdown&&this.topBarToolStore.closeDropdowns(),this.state.toolsPopoverState.isOpen=!this.state.toolsPopoverState.isOpen}get toolsPopoverProps(){return{anchorRect:this.moreToolsButtonRef.el?tp(this.moreToolsButtonRef.el):{x:0,y:0,width:0,height:0},positioning:`bottom-left`,verticalOffset:0,class:`rounded`,maxWidth:300}}showDivider(e){return e<this.toolsCategories.length-1||this.state.invisibleToolsCategories.length>0}};function YJ(){return new XJ(navigator.clipboard)}var XJ=class{clipboard;constructor(e){this.clipboard=e}async write(e){if(this.clipboard?.write)try{await this.clipboard?.write(this.getClipboardItems(e))}catch(t){console.log(`Failed to write on the clipboard, falling back to plain/html text. Error %s`,t);try{await this.clipboard?.write([new ClipboardItem({"text/plain":this.getBlob(e,`text/plain`),"text/html":this.getBlob(e,`text/html`)})])}catch{}}else await this.writeText(e[`text/plain`]??``)}async writeText(e){try{this.clipboard?.writeText(e)}catch{}}async read(){let e;try{e=await navigator.permissions.query({name:`clipboard-read`})}catch{}if(this.clipboard?.read)try{let e=await this.clipboard.read(),t={};for(let n of e)for(let e of n.types){let r=await n.getType(e);eA.includes(e)?t[e]=r:t[e]=await r.text()}return{status:`ok`,content:t}}catch{return{status:e?.state===`denied`?`permissionDenied`:`notImplemented`}}else return{status:`ok`,content:{"text/plain":await this.clipboard?.readText()}}}getClipboardItems(e){let t={};for(let n of Object.keys(e))t[n]=this.getBlob(e,n);return[new ClipboardItem(t)]}getBlob(e,t){let n=e[t];return n instanceof Blob||n instanceof File?n:new Blob([e[t]||``],{type:t})}},ZJ=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},colorScheme:{type:String,optional:!0}};static components={TopBar:JJ,Grid:oW,BottomBar:xJ,SmallBottomBar:MJ,SidePanels:AJ,SpreadsheetDashboard:CJ,HeaderGroupContainer:DJ,FullScreenFigure:lW};sidePanel;spreadsheetRef=(0,t.useRef)(`spreadsheet`);spreadsheetRect=xv();_focusGrid;isViewportTooSmall=!1;notificationStore;composerFocusStore;get model(){return this.props.model}getStyle(){let e={},t=this.env.model.getters.getScrollBarWidth();return this.env.isDashboard()?e[`grid-template-rows`]=`auto`:e[`grid-template-rows`]=`min-content auto min-content`,e[`grid-template-columns`]=`auto ${this.sidePanel.mainPanel?`${this.sidePanel.totalPanelSize||350}px`:`auto`}`,e[`--os-scrollbar-width`]=`${t}px`,e[`color-scheme`]=this.props.colorScheme,U(e)}setup(){if(!(`isSmall`in this.env)){let e=OJ();(0,t.useSubEnv)({get isSmall(){return e.isSmall}})}let e=ar();e.inject(ur,this.model);let n=this.env;e.get(nW).setSmallThreshhold(()=>n.isSmall),this.notificationStore=D(ck),this.composerFocusStore=D(_r),this.sidePanel=D(rW);let r=this.model.config.external.fileStore;(0,t.useSubEnv)({model:this.model,imageProvider:r?new fJ(r):void 0,loadCurrencies:this.model.config.external.loadCurrencies,loadLocales:this.model.config.external.loadLocales,isDashboard:()=>this.model.getters.isDashboard(),openSidePanel:this.sidePanel.open.bind(this.sidePanel),replaceSidePanel:this.sidePanel.replace.bind(this.sidePanel),toggleSidePanel:this.sidePanel.toggle.bind(this.sidePanel),clipboard:this.env.clipboard||YJ(),startCellEdition:e=>this.composerFocusStore.focusActiveComposer({content:e}),notifyUser:e=>this.notificationStore.notifyUser(e),askConfirmation:(e,t,n)=>this.notificationStore.askConfirmation(e,t,n),raiseError:(e,t)=>this.notificationStore.raiseError(e,t),isMobile:vp}),this.notificationStore.updateNotificationCallbacks({...this.props}),(0,t.useEffect)(()=>{!this.spreadsheetRef.el.contains(document.activeElement)&&document.activeElement?.contains(this.spreadsheetRef.el)&&this.focusGrid()}),(0,t.useExternalListener)(window,`resize`,()=>this.render(!0)),(0,t.useExternalListener)(document.body,`wheel`,()=>{}),this.bindModelEvents(),(0,t.onWillUpdateProps)(e=>{if(e.model!==this.props.model)throw Error(`Changing the props model is not supported at the moment.`);(e.notifyUser!==this.props.notifyUser||e.askConfirmation!==this.props.askConfirmation||e.raiseError!==this.props.raiseError)&&this.notificationStore.updateNotificationCallbacks({...e})});let i=ft(this.render.bind(this,!0));(0,t.onMounted)(()=>{this.checkViewportSize(),e.on(`store-updated`,this,i),a.observe(this.spreadsheetRef.el)}),(0,t.onWillUnmount)(()=>{this.unbindModelEvents(),e.off(`store-updated`,this),a.disconnect(),Xl()}),(0,t.onPatched)(()=>{this.checkViewportSize()});let a=new ResizeObserver(()=>{this.sidePanel.changeSpreadsheetWidth(this.spreadsheetRect.width)})}bindModelEvents(){this.model.on(`update`,this,()=>this.render(!0)),this.model.on(`notify-ui`,this,e=>this.notificationStore.notifyUser(e)),this.model.on(`raise-error-ui`,this,({text:e})=>this.notificationStore.raiseError(e))}unbindModelEvents(){this.model.off(`update`,this),this.model.off(`notify-ui`,this),this.model.off(`raise-error-ui`,this)}checkViewportSize(){let{xRatio:e,yRatio:t}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());if(!(!isFinite(e)||!isFinite(t)))if(t>.85||e>.85){if(this.isViewportTooSmall)return;this.notificationStore.notifyUser({text:k(`The current window is too small to display this sheet properly. Consider resizing your browser window or adjusting frozen rows and columns.`),type:`warning`,sticky:!1}),this.isViewportTooSmall=!0}else this.isViewportTooSmall=!1}focusGrid(){this._focusGrid&&this._focusGrid()}get gridHeight(){return this.env.model.getters.getSheetViewDimension().height}get gridContainerStyle(){let e=21*this.rowLayers.length,t=21*this.colLayers.length,n=this.env.model.getters.getViewportZoomLevel();return U({"grid-template-columns":`${e?e+2:0}px auto`,"grid-template-rows":`${t?t+2:0}px auto`,zoom:`${n}`})}get rowLayers(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,`ROW`)}get colLayers(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,`COL`)}getGridSize(){let e=this.spreadsheetRef.el;if(!e)return{width:0,height:0};let t=this.env.model.getters.getViewportZoomLevel(),n=this.env.model.getters.getScrollBarWidth(),r=n=>e.querySelector(n)&&$f(e.querySelector(n),t).height||0,i=n=>e.querySelector(n)&&$f(e.querySelector(n),t).width||0,a=e.getBoundingClientRect(),o=r(`.o-spreadsheet-topbar-wrapper`),s=r(`.o-spreadsheet-bottombar-wrapper`),c=r(`.o-column-groups`),l=i(`.o-grid`),u=a.height-c-o-s;return{width:Math.max(l/t-n,0),height:Math.max(u/t-n,0)}}getSpreadSheetClasses(){return[this.env.isSmall?`o-spreadsheet-mobile`:``,this.props.colorScheme===`dark`?`dark`:``].join(` `)}},QJ=class{transportService;constructor(e){this.transportService=e}async sendMessage(e){(e.type===`CLIENT_JOINED`||e.type===`CLIENT_LEFT`||e.type===`CLIENT_MOVED`)&&await this.transportService.sendMessage(e)}onNewMessage(e,t){this.transportService.onNewMessage(e,t)}leave(e){this.transportService.leave(e)}};function $J(e){return Cq.get(e.type)(e)}var eY=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)}}},tY=class{id;data;constructor(e,t){this.id=e,this.data=t}transformed(e){return new nY(this.id,mt(()=>e(this.data)))}},nY=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))}},rY=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))}},iY=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 rY(Qe(this._execution(e),this._execution(e)))}revertedExecution(e){return new rY(Qe(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):[]}}},aY=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 eY(this.buildTransformation),this.tree=new iY(this.buildTransformation,this.HEAD_BRANCH);let t=e.initialOperationId,n=new tY(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 tY(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 tY(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 oY(e){return new aY({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=>sY([e]),buildEmpty:e=>new AK(e,`empty`,[]),buildTransformation:{with:e=>t=>new AK(t.id,t.clientId,bK(t.commands,e.commands),t.rootCommand,void 0,t.timestamp),without:e=>t=>new AK(t.id,t.clientId,bK(t.commands,e.commands.map($J).flat()),t.rootCommand,void 0,t.timestamp)}})}function sY(e){for(let t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){let n=t.changes[e];cY(n)}}function cY(e){let t=e.target,n=e.key,r=e.before;r===void 0?delete t[n]:t[n]=r}var lY=class{getters;providers=[];isAdaptingRanges=!1;constructor(e){this.getters=e}static getters=[`copyFormulaStringForSheet`,`extendRange`,`getRangeString`,`getRangeFromSheetXC`,`createAdaptedRanges`,`getRangeData`,`getRangeDataFromXc`,`getRangeDataFromZone`,`getRangeFromRangeData`,`getRangeFromZone`,`getRangesUnion`,`recomputeRanges`,`isRangeValid`,`removeRangesSheetPrefix`];allowDispatch(e){return e.type===`MOVE_RANGES`?e.target.length===1?`Success`:`InvalidZones`:`Success`}beforeHandle(e){}handle(e){if(this.isAdaptingRanges)throw Error(`Plugins cannot dispatch commands during adaptRanges phase`);let t=nl(e);t&&this.executeOnAllRanges(t)}finalize(){}verifyRangeRemoved(e){return t=>{let n=e(t);return n.changeType!==`NONE`&&!pn(n.range.zone)?{range:n.range,changeType:`REMOVE`}:n}}executeOnAllRanges(e){this.isAdaptingRanges=!0;let t={applyChange:this.verifyRangeRemoved(e.applyChange),adaptRangeString:(t,n)=>Gu(t,n,e),adaptFormulaString:(t,n)=>Wu(t,n,e)};for(let n of this.providers)n(t,e.sheetId,e.sheetName);this.isAdaptingRanges=!1}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,n,r){return e.map(e=>{if(!pn(e.zone))return e;let i=e.prefixSheet?e.sheetId:r,a=Jc(e),o=qc(e),s={...e.unboundedZone,left:a&&!e.unboundedZone.hasHeader?e.unboundedZone.left:e.unboundedZone.left+(e.parts[0].colFixed?0:t),right:a?e.unboundedZone.right:e.unboundedZone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:o&&!e.unboundedZone.hasHeader?e.unboundedZone.top:e.unboundedZone.top+(e.parts[0].rowFixed?0:n),bottom:o?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:n)};return tl(Wc({...e,sheetId:i,zone:s},this.getters.getSheetSize))})}removeRangesSheetPrefix(e,t){return t.map(t=>t.prefixSheet&&t.sheetId===e?{...t,prefixSheet:!1}:t)}extendRange(e,t,n){let r=t===`COL`?e.zone.right+n:e.zone.right,i=t===`ROW`?e.zone.bottom+n:e.zone.bottom,a={left:e.zone.left,top:e.zone.top,right:Jc(e)?void 0:r,bottom:qc(e)?void 0:i};return Wc({...e,zone:a},this.getters.getSheetSize)}getRangeFromSheetXC(e,t){if(!Oc.test(t)||!this.getters.tryGetSheet(e))return Kc(t);let{sheetName:n}=Pc(t);return Gc({xc:t,sheetId:this.getters.getSheetIdByName(n)||e,invalidSheetName:n&&!this.getters.getSheetIdByName(n)?n:void 0},this.getters.getSheetSize)}getRangeString(e,t,n={useBoundedReference:!1,useFixedReference:!1}){return e?e.invalidXc?e.invalidXc:this.getters.tryGetSheet(e.sheetId)?Yc(e,t,this.getters.getSheetName,n):A.InvalidReference:A.InvalidReference}getRangeDataFromXc(e,t){let n=this.getters.getRangeFromSheetXC(e,t);return this.getRangeDataFromZone(n.sheetId,n.unboundedZone)}getRangeDataFromZone(e,t){return t=this.getters.getUnboundedZone(e,t),{_sheetId:e,_zone:t}}getRangeData(e){return this.getRangeDataFromZone(e.sheetId,e.unboundedZone)}getRangeFromZone(e,t){return Wc({sheetId:e,zone:t,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}],prefixSheet:!1},this.getters.getSheetSize)}recomputeRanges(e,t){return Qt(e.map(e=>e.unboundedZone),t.map(e=>e.unboundedZone)).map(t=>this.getRangeFromZone(e[0].sheetId,t))}getRangeFromRangeData(e){return this.getters.tryGetSheet(e._sheetId)?Wc({prefixSheet:!1,zone:e._zone,sheetId:e._sheetId,invalidSheetName:void 0,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}]},this.getters.getSheetSize):Kc(A.InvalidReference)}isRangeValid(e){if(!e)return!1;let{xc:t,sheetName:n}=Pc(e);return t.match(Oc)!==null&&(!n||this.getters.getSheetIdByName(n)!==void 0)}getRangesUnion(e){let t=xn(...e.map(e=>e.unboundedZone));return this.getRangeFromZone(e[0].sheetId,t)}copyFormulaStringForSheet(e,t,n,r){if(!n.startsWith(`=`))return n;let i=lU(n),a=i.dependencies.map(n=>{let i=this.getters.getRangeFromSheetXC(e,n);return r===`keepSameReference`?i:Xc(e,t,i)});return this.getters.getFormulaString(t,i.tokens,a)}},uY=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})}unobserve(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))}},dY=class{getters;stream;anchor;defaultAnchor;constructor(e){this.getters=e,this.stream=new uY,this.anchor={cell:{col:0,row:0},zone:E({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)}unobserve(e){this.stream.unobserve(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=E({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 Ws(`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=this.getters.expandZone(n,a);if(Cn(this.anchor.zone,o))return new Ws(`NoChanges`);let s={zone:o,cell:{col:r,row:i}};return this.processEvent({mode:`updateAnchor`,anchor:s,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,E({col:e,row:t}));return this.processEvent({options:{scrollIntoView:!0},anchor:{zone:r,cell:{col:e,row:t}},mode:`newAnchor`})}commitSelection(){return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:this.anchor,mode:`commitSelection`})}resizeAnchorZone(e,t=1){if(t!==`end`&&t<=0)return new Ws(`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 Ws.Success;let p=r.zone,m=e=>{e=Nn(e);let{left:t,right:r,top:i,bottom:a}=this.getters.expandZone(n,e);return{left:Math.max(0,t),right:Math.min(this.getters.getNumberCols(n)-1,r),top:Math.max(0,i),bottom:Math.min(this.getters.getNumberRows(n)-1,a)}},{cell:h,zone:g}=this.getReferenceAnchor(),{col:_,row:v}=h,y=0;for(;p!==null;){if(y++,d<0){let e=this.getNextAvailableCol(d,s-(y-1),v);p=g.right<=s-y?m({top:c,left:o,bottom:l,right:e}):null}if(d>0){let e=this.getNextAvailableCol(d,o+(y-1),v);p=o+y<=g.left?m({top:c,left:e,bottom:l,right:s}):null}if(f<0){let e=this.getNextAvailableRow(f,_,l-(y-1));p=g.bottom<=l-y?m({top:c,left:o,bottom:e,right:s}):null}if(f>0){let e=this.getNextAvailableRow(f,_,c+(y-1));p=c+y<=g.top?m({top:e,left:o,bottom:l,right:s}):null}if(p&&=Nn(p),p&&!Cn(p,r.zone))return this.processEvent({options:{scrollIntoView:!0},mode:`updateAnchor`,anchor:{zone:p,cell:{col:i,row:a}}})}p=m(bn({top:a,bottom:a,left:i,right:i},Nn({top:this.getNextAvailableRow(f,_,c),left:this.getNextAvailableCol(d,o,v),bottom:this.getNextAvailableRow(f,_,l),right:this.getNextAvailableCol(d,s,v)})));let ee={zone:p,cell:{col:i,row:a}};return this.processEvent({anchor:ee,mode:`updateAnchor`,options:{scrollIntoView:!0}})}selectColumn(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.getNumberRows(n)-1,i={left:e,right:e,top:0,bottom:r},a=this.getters.findFirstVisibleColRowIndex(n,`ROW`),o,s;switch(t){case`overrideSelection`:case`newAnchor`:o=e,s=a;break;case`updateAnchor`:({col:o,row:s}=this.anchor.cell),i=bn(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=bn(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(Cn(this.anchor.zone,this.getters.getSheetZone(e)))return this.modifyAnchor({...t,zone:E(t.cell)},`updateAnchor`,{scrollIntoView:!1});let n=this.getters.getContiguousZone(e,t.zone);return w(n,t.zone)?this.selectAll():this.modifyAnchor({...t,zone:n},`updateAnchor`,{scrollIntoView:!1})}selectTableAroundSelection(){let e=this.getters.getActiveSheetId(),t=this.getters.getContiguousZone(e,this.anchor.zone);return this.modifyAnchor({...this.anchor,zone:t},`updateAnchor`,{scrollIntoView:!1})}selectAll(){let e=this.getters.getActiveSheetId(),t={left:0,top:0,bottom:this.getters.getNumberRows(e)-1,right:this.getters.getNumberCols(e)-1};return this.processEvent({mode:`overrideSelection`,anchor:{zone:t,cell:this.anchor.cell},options:{scrollIntoView:!1}})}isListening(e){return this.stream.isListening(e)}processEvent(e){let t={...e,previousAnchor:b(this.anchor)},n=this.checkEventAnchorZone(t);return n===`Success`?(this.anchor=t.anchor,this.stream.send(t),Ws.Success):new Ws(n)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){let{cell:t,zone:n}=e;if(!En(t.col,t.row,n))return`InvalidAnchorZone`;let{left:r,right:i,top:a,bottom:o}=n,s=this.getters.getActiveSheetId(),c=this.getters.findVisibleHeader(s,`COL`,r,i);return this.getters.findVisibleHeader(s,`ROW`,a,o)===void 0||c===void 0?`SelectionOutOfBound`:`Success`}checkAnchorZoneOrThrow(e){if(this.checkAnchorZone(e)===`InvalidAnchorZone`)throw Error(`The provided anchor is invalid. The cell must be part of the zone.`)}getNextAvailablePosition(e,t=1){let{col:n,row:r}=this.anchor.cell,i=this.deltaToTarget({col:n,row:r},e,t);return{col:this.getNextAvailableCol(i[0],n,r),row:this.getNextAvailableRow(i[1],n,r)}}getNextAvailableCol(e,t,n){let r=this.getters.getActiveSheetId(),i={col:t,row:n};return this.getNextAvailableHeader(e,`COL`,t,i,e=>this.getters.isInSameMerge(r,t,n,e,n))}getNextAvailableRow(e,t,n){let r=this.getters.getActiveSheetId(),i={col:t,row:n};return this.getNextAvailableHeader(e,`ROW`,n,i,e=>this.getters.isInSameMerge(r,t,n,t,e))}getNextAvailableHeader(e,t,n,r,i){let a=this.getters.getActiveSheetId();if(e===0)return n;let o=Math.sign(e),s=n+e;for(;i(s);)s+=o;for(;this.getters.isHeaderHidden(a,t,s);)s+=o;return s<0||s>this.getters.getNumberHeaders(a,t)-1?this.getters.isHeaderHidden(a,t,n)?this.getNextAvailableHeader(-o,t,n,r,i):n:s}getReferenceAnchor(){let e=this.getters.getActiveSheetId(),t=this.anchor,{left:n,right:r,top:i,bottom:a}=t.zone,{col:o,row:s}=t.cell,c=this.getters.isColHidden(e,o)&&this.getters.findVisibleHeader(e,`COL`,n,r)||o,l=this.getters.isRowHidden(e,s)&&this.getters.findVisibleHeader(e,`ROW`,i,a)||s,u=this.getters.expandZone(e,{left:c,right:c,top:l,bottom:l});return{cell:{col:c,row:l},zone:u}}deltaToTarget(e,t,n){switch(t){case`up`:return n===`end`?[0,this.getEndOfCluster(e,`rows`,-1)-e.row]:[0,-n];case`down`:return n===`end`?[0,this.getEndOfCluster(e,`rows`,1)-e.row]:[0,n];case`left`:return n===`end`?[this.getEndOfCluster(e,`cols`,-1)-e.col,0]:[-n,0];case`right`:return n===`end`?[this.getEndOfCluster(e,`cols`,1)-e.col,0]:[n,0]}}getStartingPosition(e){let{col:t,row:n}=this.getPosition(),r=this.anchor.zone;switch(e){case`down`:case`up`:n=n===r.top?r.bottom:r.top;break;case`left`:case`right`:t=t===r.right?r.left:r.right;break}return{col:t,row:n}}getEndOfCluster(e,t,n){let r=this.getters.getActiveSheetId(),i=e,a=this.getNextCellPosition(e,t,n),o=!this.isCellSkippableInCluster({...i,sheetId:r})&&!this.isCellSkippableInCluster({...a,sheetId:r})?`endOfCluster`:`nextCluster`;for(;;){let e=this.getNextCellPosition(i,t,n);if(i.col===e.col&&i.row===e.row)break;let a=this.isCellSkippableInCluster({...e,sheetId:r});if(o===`endOfCluster`&&a)break;if(o===`nextCluster`&&!a){i=e;break}i=e}return t===`cols`?i.col:i.row}getNextCellPosition(e,t,n){let r=t===`cols`?`col`:`row`,i={...e};return i[r]=t===`cols`?this.getNextAvailableCol(n,i.col,i.row):this.getNextAvailableRow(n,i.col,i.row),{col:i.col,row:i.row}}getPosition(){return{...this.anchor.cell}}isCellSkippableInCluster(e){let t=this.getters.getMainCellPosition(e),n=this.getters.getEvaluatedCell(t);return n.type===`empty`||n.type===`text`&&n.value===``}},fY=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]=bl(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 pY=17781237,mY=17781238,hY=88853993,gY=88853994;function _Y(e,t,n){let r=[[`xmlns:r`,du],[`xmlns:a`,su],[`xmlns:c`,cu]],i=vY({backgroundColor:e.data.backgroundColor,line:{color:`000000`}}),a=$``;if(e.data.title?.text){let t=V(sd(e.data.backgroundColor)),n=e.data.title.fontSize??16;a=$`
|
|
123
|
+
You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=await rq(t)}}if(r)return r instanceof File?r:new File([r],`image.png`,{type:`image/png`})}isCutOperation(){return this._isCutOperation??!1}getDeleteCellsTargets(e,t){let n=this.getters.getActiveSheetId(),r;return r=t===`COL`?{...e,left:e.right+1,right:this.getters.getNumberCols(n)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(n)-1},{cut:[r],paste:[e]}}getInsertCellsTargets(e,t){let n=this.getters.getActiveSheetId(),r,i;return t===`COL`?(r={...e,right:this.getters.getNumberCols(n)-1},i={...e,left:e.right+1,right:e.right+1}):(r={...e,bottom:this.getters.getNumberRows(n)-1},i={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(n)-1}),{cut:[r],paste:[i]}}getClipboardData(e){let t=this.getters.getActiveSheetId(),n=this.getters.getSelectedFigureId();if(n)return{figureId:n,sheetId:t};let r=tA(t,e);return this._isCutOperation||(r.rowsIndexes=r.rowsIndexes.filter(e=>!this.getters.isRowFiltered(t,e))),r}drawLayer(e){if(this.status!==`visible`||!this.copiedData)return;let{sheetId:t,zones:n}=this.copiedData;if(t!==this.getters.getActiveSheetId()||!n||!n.length)return;let{ctx:r,thinLineWidth:i}=e;r.setLineDash([8,5]),r.strokeStyle=ae,r.lineWidth=3.3*i;for(let e of n){let{x:t,y:n,width:i,height:a}=this.getters.getVisibleRect(e);i>0&&a>0&&r.strokeRect(t,n,i,a)}}};let aq={filterType:`criterion`,type:`none`,values:[]};var oq=class extends cb{static getters=[`getFilterValue`,`getFilterHiddenValues`,`getFilterCriterionValue`,`getFirstTableInSelection`,`isRowFiltered`,`isFilterActive`];filterValues={};hiddenRows={};isEvaluationDirty=!1;allowDispatch(e){switch(e.type){case`UPDATE_FILTER`:if(!this.getters.getFilterId(e))return`FilterNotFound`;break}return`Success`}handle(e){switch(e.type){case`UNDO`:case`REDO`:case`UPDATE_CELL`:case`EVALUATE_CELLS`:case`ACTIVATE_SHEET`:case`REMOVE_TABLE`:case`ADD_COLUMNS_ROWS`:case`REMOVE_COLUMNS_ROWS`:case`UPDATE_TABLE`:this.isEvaluationDirty=!0;break;case`START`:for(let e of this.getters.getSheetIds())this.filterValues[e]={};break;case`CREATE_SHEET`:this.filterValues[e.sheetId]={};break;case`HIDE_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`GROUP_HEADERS`:case`UNGROUP_HEADERS`:case`FOLD_HEADER_GROUP`:case`UNFOLD_HEADER_GROUP`:case`FOLD_ALL_HEADER_GROUPS`:case`UNFOLD_ALL_HEADER_GROUPS`:case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:this.updateHiddenRows(e.sheetId);break;case`UPDATE_FILTER`:this.updateFilter(e),this.updateHiddenRows(e.sheetId);break;case`DUPLICATE_SHEET`:this.filterValues[e.sheetIdTo]=b(this.filterValues[e.sheetId]);break}}finalize(){if(this.isEvaluationDirty){for(let e of this.getters.getSheetIds())this.updateHiddenRows(e);this.isEvaluationDirty=!1}}isRowFiltered(e,t){return!!this.hiddenRows[e]?.has(t)}getFilterValue(e){let t=this.getters.getFilterId(e),n=e.sheetId;return t?this.filterValues[n]?.[t]:void 0}getFilterHiddenValues(e){let t=this.getters.getFilterId(e),n=e.sheetId;if(!t||!this.filterValues[n])return[];let r=this.filterValues[n][t]||[];return r.filterType===`values`?r.hiddenValues:[]}getFilterCriterionValue(e){let t=this.getters.getFilterId(e),n=e.sheetId;if(!t||!this.filterValues[n])return aq;let r=this.filterValues[n][t];return r&&r.filterType===`criterion`?r:aq}isFilterActive(e){let t=this.getters.getFilterId(e);if(!t)return!1;let n=e.sheetId,r=this.filterValues[n]?.[t];return r?r.filterType===`values`?r.hiddenValues.length>0:r.type!==`none`:!1}getFirstTableInSelection(){let e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZones();return this.getters.getTablesOverlappingZones(e,t)[0]}updateFilter({col:e,row:t,value:n,sheetId:r}){let i=this.getters.getFilterId({sheetId:r,col:e,row:t});i&&(this.filterValues[r]||(this.filterValues[r]={}),this.filterValues[r][i]=n)}updateHiddenRows(e){let t=this.getters.getFilters(e).sort((e,t)=>e.rangeWithHeaders.zone.top-t.rangeWithHeaders.zone.top),n=new Set;for(let r of t){let t=this.filterValues[e]?.[r.id],i=r.filteredRange?.zone;if(!(!t||!i||n.has(r.rangeWithHeaders.zone.top)||this.getters.isRowHiddenByUser(e,r.rangeWithHeaders.zone.top)))if(t.filterType===`values`){let a=t.hiddenValues?.map(Rl);if(!a)continue;let o=new Set(a);for(let t=i.top;t<=i.bottom;t++){let i=this.getCellValueAsString(e,r.col,t);o.has(i)&&n.add(t)}}else{if(t.type===`none`)continue;let a=W.get(t.type),o=t.values.map(t=>t.startsWith(`=`)?this.getters.evaluateFormula(e,t)??``:nc(t,R));if(o.some(gm))continue;let s={type:t.type,values:o.map(mm),dateValue:t.dateValue};for(let t=i.top;t<=i.bottom;t++){let i={sheetId:e,col:r.col,row:t},o=this.getters.getEvaluatedCell(i).value??``;a.isValueValid(o,s,this.getters,e)||n.add(t)}}}this.hiddenRows[e]=n}getCellValueAsString(e,t,n){return this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).formattedValue.toLowerCase()}exportForExcel(e){for(let t of e.sheets){let e=t.id;for(let n of t.tables){let r=un(n.range),i=[],a=[];for(let n of S(0,On(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?jn(c.filteredRange.zone).map(t=>this.getters.getEvaluatedCell({sheetId:e,...t}).formattedValue):[];if(s.length){let e=l.filter(e=>e).filter(e=>!s.includes(e));i.push({colId:n,displayedValues:[...new Set(e)],displayBlanks:!s.includes(``)&&l.some(e=>!e)})}let u=this.getters.getEvaluatedCell(o).formattedValue,d=this.getUniqueColNameForExcel(n,u,a);a.push(d);let f=T(o.col,o.row);t.cells[f]=d,t.cellValues[f]=d}n.filters=i}}}getUniqueColNameForExcel(e,t,n){return t||=`Column${e}`,zt(t,n,{compute:(e,n)=>t+String(n),start:2})}},sq=class extends cb{static getters=[`getColDimensions`,`getRowDimensions`,`getColRowOffset`];headerPositions={};isDirty=!0;handle(e){switch(Ps.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`:case`SET_FORMATTING`:case`CLEAR_FORMATTING`:this.headerPositions={},this.isDirty=!0;break;case`UPDATE_FILTER`:case`UPDATE_TABLE`:case`REMOVE_TABLE`:this.headerPositions={},this.isDirty=!0;break;case`REMOVE_COLUMNS_ROWS`:case`RESIZE_COLUMNS_ROWS`:case`HIDE_COLUMNS_ROWS`:case`ADD_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`FOLD_HEADER_GROUP`:case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_ALL_HEADER_GROUPS`:case`FOLD_ALL_HEADER_GROUPS`:case`UNGROUP_HEADERS`:case`GROUP_HEADERS`:case`CREATE_SHEET`:this.getters.tryGetSheet(e.sheetId)&&(this.headerPositions[e.sheetId]=this.computeHeaderPositionsOfSheet(e.sheetId));break;case`DUPLICATE_SHEET`:this.headerPositions[e.sheetIdTo]=b(this.headerPositions[e.sheetId]);break}}finalize(){for(let e of this.getters.getSheetIds())(this.isDirty||!this.headerPositions[e])&&(this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e));this.isDirty=!1}getColDimensions(e,t){let n=this.headerPositions[e].COL[t],r=this.getters.getColSize(e,t);return{start:n,size:r,end:n+(this.getters.isColHidden(e,t)?0:r)}}getRowDimensions(e,t){let n=this.headerPositions[e].ROW[t],r=this.getters.getRowSize(e,t);return{start:n,size:r,end:n+(this.getters.isRowHidden(e,t)?0:r)}}getColRowOffset(e,t,n,r=this.getters.getActiveSheetId()){let i=this.headerPositions[r][e][t];return this.headerPositions[r][e][n]-i}computeHeaderPositionsOfSheet(e){return{COL:this.computePositions(e,`COL`),ROW:this.computePositions(e,`ROW`)}}computePositions(e,t){let n={},r=0;for(let i=0;i<this.getters.getNumberHeaders(e,t)+1;i++)n[i]=r,!this.getters.isHeaderHidden(e,t,i)&&(r+=this.getters.getHeaderSize(e,t,i));return n}},cq=class extends cb{static layers=[`Selection`];static getters=[`getActiveSheet`,`getActiveSheetId`,`getActiveSheetName`,`getActiveCell`,`getActiveCols`,`getActiveRows`,`getCurrentStyle`,`getSelectedZones`,`getSelectedZone`,`getSelectedCells`,`getSelectedFigureId`,`getSelection`,`getActivePosition`,`getSheetPosition`,`isSingleColSelected`,`getElementsFromSelection`,`tryGetActiveSheetId`,`isGridSelectionActive`,`getSelectecUnboundedZone`];gridSelection={anchor:{cell:{col:0,row:0},zone:{top:0,left:0,bottom:0,right:0}},zones:[{top:0,left:0,bottom:0,right:0}]};selectedFigureId=null;sheetsData={};moveClient;isUnbounded;activeSheet=null;constructor(e){super(e),this.moveClient=e.moveClient,this.isUnbounded=!1}allowDispatch(e){switch(e.type){case`ACTIVATE_SHEET`:try{if(!this.getters.getSheet(e.sheetIdTo).isVisible)return`SheetIsHidden`;break}catch{return`InvalidSheetId`}case`MOVE_COLUMNS_ROWS`:return this.isMoveElementAllowed(e)}return`Success`}handleEvent(e){let t=e.anchor,n=[...this.gridSelection.zones];switch(this.isUnbounded=e.options?.unbounded||!1,e.mode){case`overrideSelection`:n=[t.zone];break;case`updateAnchor`:let r=n.findIndex(t=>Cn(t,e.previousAnchor.zone));r>=0&&(n[r]=t.zone);break;case`newAnchor`:n.push(t.zone);break;case`commitSelection`:let i=n.find(e=>Dn(t.zone,e)&&!Cn(t.zone,e));if(n.filter(e=>Cn(t.zone,e)).length>1&&n.length>2)n=n.filter(e=>!Cn(e,t.zone));else if(i){let e=Zn(t.zone,i);n=n.filter(e=>!Cn(e,t.zone)&&!Cn(e,i)).concat(e)}n=Fn(n);let a=n[n.length-1];t={cell:En(t.cell.col,t.cell.row,a)?t.cell:{col:a.left,row:a.top},zone:a};break}this.setSelectionMixin(t,n),this.selection.resetDefaultAnchor(this,b(this.gridSelection.anchor));let{col:r,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:r,row:i}),this.selectedFigureId=null}handle(e){switch(e.type){case`ACTIVATE_SHEET`:this.selectedFigureId=null;break;case`DELETE_FIGURE`:this.selectedFigureId===e.figureId&&(this.selectedFigureId=null);break;case`DELETE_SHEET`:this.selectedFigureId&&this.getters.getFigure(e.sheetId,this.selectedFigureId)&&(this.selectedFigureId=null);break}switch(e.type){case`START`:let t=this.getters.getVisibleSheetIds()[0];this.activateSheet(t,t);let{col:n,row:r}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(n,r),this.selection.registerAsDefault(this,this.gridSelection.anchor,{handleEvent:this.handleEvent.bind(this)}),this.moveClient({sheetId:t,col:0,row:0});break;case`ACTIVATE_SHEET`:this.activateSheet(e.sheetIdFrom,e.sheetIdTo);break;case`REMOVE_COLUMNS_ROWS`:{let t=this.getters.getActiveSheetId();if(e.sheetId===t){e.dimension===`COL`?this.onColumnsRemoved(e):this.onRowsRemoved(e);let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:n,row:r})}break}case`ADD_COLUMNS_ROWS`:{let t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:n,row:r})}break}case`MOVE_COLUMNS_ROWS`:e.sheetId===this.getActiveSheetId()&&this.onMoveElements(e);break;case`SELECT_FIGURE`:this.selectedFigureId=e.figureId;break;case`ACTIVATE_NEXT_SHEET`:this.activateNextSheet(`right`);break;case`ACTIVATE_PREVIOUS_SHEET`:this.activateNextSheet(`left`);break;case`HIDE_SHEET`:e.sheetId===this.getActiveSheetId()&&this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:e.sheetId,sheetIdTo:this.getters.getVisibleSheetIds()[0]});break;case`UNDO`:case`REDO`:case`DELETE_SHEET`:let i=Object.keys(this.sheetsData).filter(e=>!this.getters.tryGetSheet(e));for(let e of i)delete this.sheetsData[e];for(let e in this.sheetsData){let t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:b(t)}}this.fallbackToVisibleSheet();let a=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map(e=>this.getters.expandZone(a,e)),this.gridSelection.anchor.zone=this.getters.expandZone(a,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones),this.selectedFigureId=null;break}}finalize(){this.fallbackToVisibleSheet(),this.selection.resetDefaultAnchor(this,b(this.gridSelection.anchor))}isGridSelectionActive(){return this.selection.isListening(this)}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}getActiveSheetName(){return this.activeSheet.name}tryGetActiveSheetId(){return this.activeSheet?.id}getActiveCell(){return this.getters.getEvaluatedCell(this.getActivePosition())}getActiveCols(){let e=new Set;for(let t of this.gridSelection.zones)if(t.top===0&&t.bottom===this.getters.getNumberRows(this.getters.getActiveSheetId())-1)for(let n=t.left;n<=t.right;n++)e.add(n);return e}getActiveRows(){let e=new Set,t=this.getters.getActiveSheetId();for(let n of this.gridSelection.zones)if(n.left===0&&n.right===this.getters.getNumberCols(t)-1)for(let t=n.top;t<=n.bottom;t++)e.add(t);return e}getCurrentStyle(){let e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();return this.getters.getCellStyle({sheetId:t,col:e.left,row:e.top})??{}}getSelectedZones(){return b(this.gridSelection.zones)}getSelectedZone(){return b(this.gridSelection.anchor.zone)}getSelectecUnboundedZone(){return b(this.isUnbounded?this.getters.getUnboundedZone(this.activeSheet.id,this.gridSelection.anchor.zone):this.gridSelection.anchor.zone)}getSelection(){return b(this.gridSelection)}getSelectedCells(){let e=this.getters.getActiveSheetId(),t=[];for(let n of this.gridSelection.zones)t.push(...this.getters.getEvaluatedCellsInZone(e,n));return t}getSelectedFigureId(){return this.selectedFigureId}getActivePosition(){return this.getters.getMainCellPosition({sheetId:this.getActiveSheetId(),col:this.gridSelection.anchor.cell.col,row:this.gridSelection.anchor.cell.row})}getSheetPosition(e){if(e===this.getters.getActiveSheetId())return this.getActivePosition();{let t=this.sheetsData[e];return t?{sheetId:e,col:t.gridSelection.anchor.cell.col,row:t.gridSelection.anchor.cell.row}:this.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0})}}isSingleColSelected(){let e=this.getters.getSelectedZones();return!(e.length!==1||e[0].left!==e[0].right)}getElementsFromSelection(e){if(e===`COL`&&this.getters.getActiveCols().size===0||e===`ROW`&&this.getters.getActiveRows().size===0)return[];let t=this.getters.getSelectedZones(),n=[],r=e===`COL`?`left`:`top`,i=e===`COL`?`right`:`bottom`;for(let e of t){let t=Array.from({length:e[i]-e[r]+1},(t,n)=>e[r]+n);n=n.concat(t)}return[...new Set(n)].sort()}activateSheet(e,t){if(this.setActiveSheet(t),this.sheetsData[e]={gridSelection:b(this.gridSelection)},t in this.sheetsData)Object.assign(this,this.sheetsData[t]),this.selection.resetDefaultAnchor(this,b(this.gridSelection.anchor));else{let{col:e,row:n}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(e,n)}let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.activeSheet.id,col:n,row:r})}setSelectionMixin(e,t){let{anchor:n,zones:r}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=n,this.gridSelection.zones=r}selectCell(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.expandZone(n,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:r,cell:{col:e,row:t}},[r])}setActiveSheet(e){this.activeSheet=this.getters.getSheet(e)}activateNextSheet(e){let t=this.getters.getSheetIds(),n=(t.findIndex(e=>e===this.activeSheet.id)+(e===`left`?t.length-1:1))%t.length;this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[n]})}onColumnsRemoved(e){let{cell:t,zone:n}=this.gridSelection.anchor,r=vn(n,`left`,[...e.elements]),i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=vn(i,`left`,[...e.elements]);let a={cell:{col:i.left,row:i.top},zone:r},o=this.gridSelection.zones.map(t=>vn(t,`left`,[...e.elements]));this.setSelectionMixin(a,o)}onRowsRemoved(e){let{cell:t,zone:n}=this.gridSelection.anchor,r=vn(n,`top`,[...e.elements]),i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=vn(i,`top`,[...e.elements]);let a={cell:{col:i.left,row:i.top},zone:r},o=this.gridSelection.zones.map(t=>vn(t,`top`,[...e.elements]));this.setSelectionMixin(a,o)}onAddElements(e){let t=e.dimension===`COL`?`left`:`top`,n=_n(this.gridSelection.anchor.zone,t,e.base,e.position,e.quantity),r=this.gridSelection.zones.map(n=>_n(n,t,e.base,e.position,e.quantity)),i={cell:{col:n.left,row:n.top},zone:n};this.setSelectionMixin(i,r)}onMoveElements(e){let t=e.elements.length,n=this.getFiguresUpdates(e);this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,sheetName:e.sheetName,base:e.base,quantity:t,position:e.position});let r=e.dimension===`COL`,i=e.elements[0],a=e.elements[t-1],o=e.base<i,s=o&&r?t:0,c=o&&!r?t:0,l=o?e.elements.map(e=>e+t):e.elements,u={};for(let t of l)u[t]=this.getters.getHeaderSize(e.sheetId,e.dimension,t);let d=[{left:r?i+s:0,right:r?a+s:this.getters.getNumberCols(e.sheetId)-1,top:r?0:i+c,bottom:r?this.getters.getNumberRows(e.sheetId)-1:a+c}],f=this.getActiveSheetId(),p=o?e.base:e.base+1,m=[{left:r?p:0,right:r?p+t-1:this.getters.getNumberCols(e.sheetId)-1,top:r?0:p,bottom:r?this.getters.getNumberRows(e.sheetId)-1:p+t-1}],h=BB.cellHandlers.getKeys().map(e=>[e,new(BB.cellHandlers.get(e))(this.getters,this.dispatch)]),g={};for(let[e,t]of h)g[e]=t.copy(tA(f,d),!1,`shiftCells`);for(let[e,t]of h)g[e]&&t.paste({zones:m,sheetId:f},g[e],{isCutOperation:!0});let _=m[0],v=_.left,y=_.top;this.setSelectionMixin({zone:_,cell:{col:v,row:y}},[_]);let ee=o?e.base:e.base+1,te={};for(let t of l){let n=u[t];n!==this.getters.getHeaderSize(e.sheetId,e.dimension,ee)&&(te[n]??=[],te[n].push(ee)),ee+=1}for(let t in te)this.dispatch(`RESIZE_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,size:parseInt(t,10),elements:te[t]});this.dispatch(`REMOVE_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,sheetName:e.sheetName,elements:l}),this.applyFigureUpdates(n)}getFiguresUpdates(e){let t=[],n={},r=e.elements[0]<e.base?e.base-e.elements.length+1:e.base;for(let t=0;t<e.elements.length;t++)n[e.elements[t]]=r+t;for(let r of this.getters.getFigures(e.sheetId))e.dimension===`COL`&&r.col in n&&t.push({type:`UPDATE_FIGURE`,sheetId:e.sheetId,figureId:r.id,col:n[r.col],row:r.row}),e.dimension===`ROW`&&r.row in n&&t.push({type:`UPDATE_FIGURE`,sheetId:e.sheetId,figureId:r.id,row:n[r.row],col:r.col});return t}applyFigureUpdates(e){for(let t of e)this.dispatch(t.type,{...t})}isMoveElementAllowed(e){let t=e.dimension===`COL`,n=e.elements[0],r=e.elements[e.elements.length-1],i=e.sheetId,a=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;if(a(i,n-1,n)||a(i,r,r+1)||a(i,e.base-1,e.base))return`WillRemoveExistingMerge`;let o=[e.base,...e.elements],s=t?this.getters.getNumberCols(i):this.getters.getNumberRows(i);return o.some(e=>e<0||e>=s)?`InvalidHeaderIndex`:!t&&!this.isTableRowMoveAllowed(i,e.elements)?`CannotMoveTableHeader`:`Success`}isTableRowMoveAllowed(e,t){let n=this.getters.getCoreTables(e);if(n.length===0)return!0;let r=new Set(t);return n.every(({range:{zone:e},config:n})=>{let{top:i,bottom:a}=e;if(n.numberOfHeaders===0)return!0;let o=i+n.numberOfHeaders-1;return t.some(e=>e>=i&&e<=o)?S(i,a+1).every(e=>r.has(e)):!0})}fallbackToVisibleSheet(){if(!this.getters.tryGetSheet(this.getters.getActiveSheetId())){let e=this.getters.getVisibleSheetIds();if(this.activeSheet=this.getters.getSheet(e[0]),this.activeSheet.id in this.sheetsData){let{anchor:e}=this.clipSelection(this.activeSheet.id,this.sheetsData[this.activeSheet.id].gridSelection);this.selectCell(e.cell.col,e.cell.row)}else this.selectCell(0,0);let{col:t,row:n}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:n})}}clipSelection(e,t){let n=this.getters.getNumberCols(e)-1,r=this.getters.getNumberRows(e)-1,i=t.zones.map(e=>({left:x(e.left,0,n),right:x(e.right,0,n),top:x(e.top,0,r),bottom:x(e.bottom,0,r)})),a=x(t.anchor.cell.col,0,n),o=x(t.anchor.cell.row,0,r),s={left:x(t.anchor.zone.left,0,n),right:x(t.anchor.zone.right,0,n),top:x(t.anchor.zone.top,0,r),bottom:x(t.anchor.zone.bottom,0,r)};return{zones:i,anchor:{cell:{col:a,row:o},zone:s}}}drawLayer(e){if(this.getters.isDashboard())return;let{ctx:t,thinLineWidth:n}=e,r=this.getSelectedZones();t.fillStyle=`#f3f7fe`,t.fillStyle=r.length===1&&r[0].left===r[0].right&&r[0].top===r[0].bottom?`#f3f7fe`:`#e9f0ff`,t.strokeStyle=ae,t.lineWidth=1.5*n;for(let e of r){let{x:n,y:r,width:i,height:a}=this.getters.getVisibleRect(e);t.globalCompositeOperation=`multiply`,t.fillRect(n,r,i,a),t.globalCompositeOperation=`source-over`,t.strokeRect(n,r,i,a)}t.globalCompositeOperation=`source-over`;let i=this.getActivePosition();t.strokeStyle=ae,t.lineWidth=3*n;let a;a=this.getters.isInMerge(i)?this.getters.getMerge(i):E(i);let{x:o,y:s,width:c,height:l}=this.getters.getVisibleRect(a);c>0&&l>0&&t.strokeRect(o,s,c,l)}},lq=class{getters;sheetId;boundaries;top;bottom;left;right;offsetX;offsetY;canScrollVertically;canScrollHorizontally;viewportWidth;viewportHeight;offsetCorrectionX;offsetCorrectionY;constructor(e,t,n,r,i,a){if(this.getters=e,this.sheetId=t,this.boundaries=n,r.width<0||r.height<0)throw Error(`Viewport size cannot be negative`);this.viewportWidth=r.height&&r.width,this.viewportHeight=r.width&&r.height,this.top=n.top,this.bottom=n.bottom,this.left=n.left,this.right=n.right,this.offsetX=a.x,this.offsetY=a.y,this.canScrollVertically=i.canScrollVertically,this.canScrollHorizontally=i.canScrollHorizontally,this.offsetCorrectionX=this.getters.getColDimensions(this.sheetId,this.boundaries.left).start,this.offsetCorrectionY=this.getters.getRowDimensions(this.sheetId,this.boundaries.top).start,this.adjustViewportOffsetX(),this.adjustViewportOffsetY()}getMaxSize(){let e=this.getters.findLastVisibleColRowIndex(this.sheetId,`COL`,{first:this.boundaries.left,last:this.boundaries.right}),t=this.getters.findLastVisibleColRowIndex(this.sheetId,`ROW`,{first:this.boundaries.top,last:this.boundaries.bottom}),{end:n}=this.getters.getColDimensions(this.sheetId,e),{end:r}=this.getters.getRowDimensions(this.sheetId,t),i=n-this.offsetCorrectionX;this.canScrollHorizontally&&(i=Math.max(i,this.viewportWidth));let a=r-this.offsetCorrectionY;return this.canScrollVertically&&(a=Math.max(a,this.viewportHeight),r+46>a&&!this.getters.isReadonly()&&(a+=46)),{width:i,height:a}}getColIndex(e){return e<this.offsetCorrectionX||e>this.offsetCorrectionX+this.viewportWidth?-1:this.searchHeaderIndex(`COL`,e-this.offsetCorrectionX+this.snapCorrection.x,this.left)}getRowIndex(e){return e<this.offsetCorrectionY||e>this.offsetCorrectionY+this.viewportHeight?-1:this.searchHeaderIndex(`ROW`,e-this.offsetCorrectionY+this.snapCorrection.y,this.top)}adjustPosition(e){let t=this.sheetId,n=this.getters.getMainCellPosition({sheetId:t,...e}),{col:r,row:i}=this.getters.getNextVisibleCellPosition(n);En(r,this.boundaries.top,this.boundaries)&&this.adjustPositionX(r),En(this.boundaries.left,i,this.boundaries)&&this.adjustPositionY(i)}adjustPositionX(e){let t=this.sheetId,{start:n,end:r}=this.getters.getColDimensions(t,e);this.offsetX+this.viewportWidth+this.offsetCorrectionX<r?this.offsetX=r-this.viewportWidth:this.offsetX+this.offsetCorrectionX>n&&(this.offsetX=n-this.offsetCorrectionX),this.adjustViewportZoneX()}adjustPositionY(e){let t=this.sheetId,{start:n,end:r}=this.getters.getRowDimensions(t,e);this.offsetY+this.viewportHeight+this.offsetCorrectionY<r?this.offsetY=r-this.viewportHeight:this.offsetY+this.offsetCorrectionY>n&&(this.offsetY=n-this.offsetCorrectionY),this.adjustViewportZoneY()}willNewOffsetScrollViewport(e,t){return this.canScrollHorizontally&&this.offsetX!==e||this.canScrollVertically&&this.offsetY!==t}setViewportOffset(e,t){this.setViewportOffsetX(e),this.setViewportOffsetY(t)}adjustViewportZone(){this.adjustViewportZoneX(),this.adjustViewportZoneY()}getVisibleRect(e){let t=Sn(e,this),n=this.snapCorrection.x,r=this.snapCorrection.y;if(t)return{x:this.getters.getColRowOffset(`COL`,this.left,t.left)+this.offsetCorrectionX-(this.left===t.left?0:n),y:this.getters.getColRowOffset(`ROW`,this.top,t.top)+this.offsetCorrectionY-(this.top===t.top?0:r),width:Math.min(this.getters.getColRowOffset(`COL`,t.left,t.right+1)-(this.left===t.left?n:0),this.viewportWidth),height:Math.min(this.getters.getColRowOffset(`ROW`,t.top,t.bottom+1)-(this.top===t.top?r:0),this.viewportHeight)}}getFullRect(e){let t=Sn(e,this.boundaries),n=this.snapCorrection.x,r=this.snapCorrection.y;if(t){let t=this.getters.getColRowOffset(`COL`,this.left,e.left)+this.offsetCorrectionX,i=this.getters.getColRowOffset(`ROW`,this.top,e.top)+this.offsetCorrectionY,a=this.getters.getColRowOffset(`COL`,e.left,e.right+1),o=this.getters.getColRowOffset(`ROW`,e.top,e.bottom+1);return{x:t-n,y:i-r,width:a,height:o}}}isVisible(e,t){return t<=this.bottom&&t>=this.top&&e>=this.left&&e<=this.right&&!this.getters.isColHidden(this.sheetId,e)&&!this.getters.isRowHidden(this.sheetId,t)}searchHeaderIndex(e,t,n=0){if(this.viewportWidth<=0||this.viewportHeight<=0)return-1;let r=this.sheetId,i=this.getters.getNumberHeaders(r,e),a=n,o=i;for(;a<=o&&a!==i&&o!==-1;){let i=Math.floor((a+o)/2),s=this.getters.getColRowOffset(e,n,i),c=this.getters.getHeaderSize(r,e,i);if(t>=s&&t<s+c)return i;t>=s+c?a=i+1:o=i-1}return-1}setViewportOffsetX(e){this.canScrollHorizontally&&(this.offsetX=e,this.adjustViewportZoneX())}setViewportOffsetY(e){this.canScrollVertically&&(this.offsetY=e,this.adjustViewportZoneY())}adjustViewportOffsetX(){if(this.canScrollHorizontally){let{width:e}=this.getMaxSize();this.viewportWidth+this.offsetX>e&&(this.offsetX=Math.max(0,e-this.viewportWidth))}this.adjustViewportZoneX()}adjustViewportOffsetY(){if(this.canScrollVertically){let{height:e}=this.getMaxSize();this.viewportHeight+this.offsetY>e&&(this.offsetY=Math.max(0,e-this.viewportHeight))}this.adjustViewportZoneY()}adjustViewportZoneX(){this.left=this.searchHeaderIndex(`COL`,this.offsetX,this.boundaries.left),this.right=Math.min(this.boundaries.right,this.searchHeaderIndex(`COL`,Math.max(this.viewportWidth+this.snapCorrection.x-.1),this.left)),this.viewportWidth&&(this.left===-1&&(this.left=this.boundaries.left),this.right===-1&&(this.right=this.boundaries.right))}adjustViewportZoneY(){this.top=this.searchHeaderIndex(`ROW`,this.offsetY,this.boundaries.top),this.bottom=Math.min(this.boundaries.bottom,this.searchHeaderIndex(`ROW`,Math.max(this.viewportHeight+this.snapCorrection.y-.1,0),this.top)),this.viewportHeight&&(this.top===-1&&(this.top=this.boundaries.top),this.bottom===-1&&(this.bottom=this.boundaries.bottom))}get snapCorrection(){return{x:Math.abs(this.offsetX-this.getters.getColRowOffset(`COL`,this.boundaries.left,Math.max(0,this.left))),y:Math.abs(this.offsetY-this.getters.getColRowOffset(`ROW`,this.boundaries.top,Math.max(0,this.top)))}}},uq=class extends cb{static getters=`getColIndex.getRowIndex.getActiveMainViewport.getSheetViewDimension.getSheetViewDimensionWithHeaders.getMainViewportRect.isVisibleInViewport.getEdgeScrollCol.getEdgeScrollRow.getVisibleFigures.getVisibleRect.getVisibleRectWithoutHeaders.getVisibleRectWithZoom.getVisibleCellPositions.getColRowOffsetInViewport.getMainViewportCoordinates.getActiveSheetScrollInfo.getSheetViewVisibleCols.getSheetViewVisibleRows.getFrozenSheetViewRatio.isPixelPositionVisible.getColDimensionsInViewport.getRowDimensionsInViewport.getAllActiveViewportsZonesAndRect.getRect.getFigureUI.getPositionAnchorOffset.getGridOffset.getViewportZoomLevel.getScrollBarWidth.getMaximumSheetOffset`.split(`.`);viewports={};sheetViewWidth=Pe();sheetViewHeight=Pe();gridOffsetX=0;gridOffsetY=0;zoomLevel=1;sheetsWithDirtyViewports=new Set;shouldAdjustViewports=!1;allowDispatch(e){switch(e.type){case`SET_VIEWPORT_OFFSET`:return this.chainValidations(this.checkScrollingDirection,this.checkIfViewportsWillChange)(e);case`RESIZE_SHEETVIEW`:return this.chainValidations(this.checkValuesAreDifferent,this.checkPositiveDimension)(e);default:return`Success`}}handleEvent(e){let t=this.getters.getActiveSheetId();if(e.options.scrollIntoView){let{col:n,row:r}=Ln(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(Ps.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`SET_ZOOM`:this.zoomLevel=e.zoom||1;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`:case`SET_FORMATTING`:for(let e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);break;case`DELETE_SHEET`:this.cleanViewports(),this.sheetsWithDirtyViewports.delete(e.sheetId);break;case`ACTIVATE_SHEET`:this.sheetsWithDirtyViewports.add(e.sheetIdTo);break;case`SCROLL_TO_CELL`:this.refreshViewport(this.getters.getActiveSheetId(),{col:e.col,row:e.row});break}}finalize(){for(let e of this.sheetsWithDirtyViewports)if(this.resetViewports(e),this.shouldAdjustViewports){let t=this.getters.getSheetPosition(e);this.getSubViewports(e).forEach(e=>{e.adjustPosition(t)})}this.sheetsWithDirtyViewports=new Set,this.shouldAdjustViewports=!1,this.setViewports()}setViewports(){let e=this.getters.getSheetIds();for(let t of e)this.viewports[t]?.bottomRight||this.resetViewports(t)}getColIndex(e){let t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map(t=>t.getColIndex(e)))}getRowIndex(e){let t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map(t=>t.getRowIndex(e)))}getSheetViewDimensionWithHeaders(){return{width:this.sheetViewWidth+this.gridOffsetX,height:this.sheetViewHeight+this.gridOffsetY}}getSheetViewDimension(){return{width:this.sheetViewWidth,height:this.sheetViewHeight}}getGridOffset(){return{x:this.gridOffsetX,y:this.gridOffsetY}}getActiveMainViewport(){let e=this.getters.getActiveSheetId();return this.getMainViewport(e)}getActiveSheetScrollInfo(){let e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetX,scrollY:t.offsetY}}getSheetViewVisibleCols(){let e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map(e=>S(e.left,e.right+1)).flat())].filter(t=>t>=0&&!this.getters.isHeaderHidden(e,`COL`,t))}getSheetViewVisibleRows(){let e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map(e=>S(e.top,e.bottom+1)).flat())].filter(t=>t>=0&&!this.getters.isHeaderHidden(e,`ROW`,t))}getVisibleCellPositions(){let e=this.getSheetViewVisibleCols(),t=this.getSheetViewVisibleRows(),n=this.getters.getActiveSheetId(),r=[];for(let i of e)for(let e of t){let t={sheetId:n,col:i,row:e},a=this.getters.getMainCellPosition(t);a.row!==e||a.col!==i||r.push(t)}return r}getMainViewportRect(){let e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e),{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(e),{width:i,height:a}=t.getMaxSize();return{x:this.getters.getColDimensions(e,n).start,y:this.getters.getRowDimensions(e,r).start,width:i,height:a}}getMaximumSheetOffset(){let e=this.getters.getActiveSheetId(),{width:t,height:n}=this.getMainViewportRect(),r=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-r.viewportWidth),maxOffsetY:Math.max(0,n-r.viewportHeight)}}getColRowOffsetInViewport(e,t,n){if(n<t)return-this.getColRowOffsetInViewport(e,n,t);let r=this.getters.getActiveSheetId(),i=e===`COL`?this.getters.getSheetViewVisibleCols():this.getters.getSheetViewVisibleRows(),a=i.findIndex(e=>t>=e),o=i.findIndex(e=>n<=e);o=o===-1?i.length:o;let s=i.slice(a,o),c=0;for(let t of s)c+=this.getters.getHeaderSize(r,e,t);return c*this.zoomLevel}isVisibleInViewport({sheetId:e,col:t,row:n}){return this.getSubViewports(e).some(e=>e.isVisible(t,n))}getScrollBarWidth(){return 15/this.zoomLevel}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=xc(e-s),i=1):e<c&&n>=c&&l>0?(r=!0,a=xc(c-e),i=-1):o&&t<c&&e>c&&(r=!0,a=xc(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=xc(e-s),i=1):e<c&&n>=c&&l>0?(r=!0,a=xc(c-e),i=-1):o&&t<c&&e>c&&(r=!0,a=xc(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}}getVisibleRectWithZoom(e){let t=this.getViewportZoomLevel(),n=this.getVisibleRectWithoutHeaders(e);return n.width*=t,n.height*=t,n.x=n.x*t+this.gridOffsetX*t,n.y=n.y*t+this.gridOffsetY*t,n}getVisibleRectWithoutHeaders(e){let t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,t=>t.getVisibleRect(e))}getRect(e){let t=this.getters.getActiveSheetId(),n=this.mapViewportsToRect(t,t=>t.getFullRect(e));return{...n,x:n.x+this.gridOffsetX,y:n.y+this.gridOffsetY}}getRectWithoutHeaders(e){let t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,t=>t.getFullRect(e))}getMainViewportCoordinates(){let e=this.getters.getActiveSheetId(),{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,n).start}}getColDimensionsInViewport(e,t){let{top:n}=this.getMainInternalViewport(e),r={left:t,right:t,top:n,bottom:n},{x:i,width:a}=this.getVisibleRect(r),o=i-this.gridOffsetX;return{start:o,size:a,end:o+a}}getRowDimensionsInViewport(e,t){let{left:n}=this.getMainInternalViewport(e),r={left:0,right:n,top:t,bottom:t},{y:i,height:a}=this.getVisibleRect(r),o=i-this.gridOffsetY;return{start:o,size:a,end:o+a}}getAllActiveViewportsZonesAndRect(){let e=this.getters.getActiveSheetId();return this.getSubViewports(e).map(e=>({zone:e,rect:{x:e.offsetCorrectionX+this.gridOffsetX,y:e.offsetCorrectionY+this.gridOffsetY,...e.getMaxSize()}}))}getViewportZoomLevel(){return this.zoomLevel}ensureMainViewportExist(e){this.viewports[e]||this.resetViewports(e)}getSubViewports(e){return this.ensureMainViewportExist(e),Object.values(this.viewports[e]).filter(C)}checkPositiveDimension(e){return e.width<0||e.height<0?`InvalidViewportSize`:`Success`}checkValuesAreDifferent(e){let{height:t,width:n}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===n&&e.height===t?`ValuesNotChanged`:`Success`}checkScrollingDirection({offsetX:e,offsetY:t}){let n=this.getMainInternalViewport(this.getters.getActiveSheetId());return!n.canScrollHorizontally&&e>0||!n.canScrollVertically&&t>0?`InvalidScrollingDirection`:`Success`}checkIfViewportsWillChange({offsetX:e,offsetY:t}){let n=this.getters.getActiveSheetId(),{maxOffsetX:r,maxOffsetY:i}=this.getMaximumSheetOffset();return this.getSubViewports(n).some(n=>n.willNewOffsetScrollViewport(x(e,0,r),x(t,0,i)))?`Success`:`ViewportScrollLimitsReached`}getMainViewport(e){let t=this.getMainInternalViewport(e);return{top:t.top,left:t.left,bottom:t.bottom,right:t.right}}getMainInternalViewport(e){return this.ensureMainViewportExist(e),this.viewports[e].bottomRight}cleanViewports(){let e={};for(let t of this.getters.getSheetIds())e[t]=this.viewports[t];this.viewports=e}resizeSheetView(e,t,n=0,r=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=n,this.gridOffsetY=r,this.recomputeViewports()}recomputeViewports(){for(let e of this.getters.getSheetIds())this.resetViewports(e)}setSheetViewOffset(e,t){let n=this.getters.getActiveSheetId(),{maxOffsetX:r,maxOffsetY:i}=this.getMaximumSheetOffset();this.getSubViewports(n).forEach(n=>n.setViewportOffset(x(e,0,r),x(t,0,i)))}getViewportOffset(e){return{x:this.viewports[e]?.bottomRight.offsetX||0,y:this.viewports[e]?.bottomRight.offsetY||0}}resetViewports(e){if(!this.getters.tryGetSheet(e))return;let{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e),r=this.getters.getNumberCols(e),i=this.getters.getNumberRows(e),a=Math.min(this.getters.getColRowOffset(`COL`,0,t,e),this.sheetViewWidth),o=Math.min(this.getters.getColRowOffset(`ROW`,0,n,e),this.sheetViewHeight),s=Math.max(this.sheetViewWidth-a,0),c=Math.max(this.sheetViewHeight-o,0),{xRatio:l,yRatio:u}=this.getFrozenSheetViewRatio(e),d=l<1,f=u<1,p=this.getViewportOffset(e),m={topLeft:n&&t&&new lq(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 lq(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 lq(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 lq(this.getters,e,{left:t,right:r-1,top:n,bottom:i-1},{width:s,height:c},{canScrollHorizontally:d,canScrollVertically:f},{x:d?p.x:0,y:f?p.y:0})};this.viewports[e]=m}refreshViewport(e,t){this.getSubViewports(e).forEach(e=>{e.adjustViewportZone(),e.adjustPosition(t)})}shiftVertically(e){let t=this.getters.getActiveSheetId(),{top:n}=this.getMainInternalViewport(t),{scrollX:r}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(r,e);let{anchor:i}=this.getters.getSelection();if(i.cell.row>=this.getters.getPaneDivisions(t).ySplit){let e=this.getMainInternalViewport(t).top-n;this.selection.selectCell(i.cell.col,i.cell.row+e)}}getColIndexLeftOfMainViewport(e){if(e>=0)return-1;let t=this.getters.getActiveSheetId(),n=this.getActiveMainViewport().left,r=-this.getActiveSheetScrollInfo().scrollX-this.getters.getColRowOffset(`COL`,n,0);for(;e<r;n--)r-=this.getters.getColSize(t,n-1);return Math.max(n,0)}getRowIndexTopOfMainViewport(e){if(e>=0)return-1;let t=this.getters.getActiveSheetId(),n=this.getActiveMainViewport().top,r=-this.getActiveSheetScrollInfo().scrollY-this.getters.getColRowOffset(`ROW`,n,0);for(;e<r;n--)r-=this.getters.getRowSize(t,n-1);return Math.max(n,0)}getVisibleFigures(){let e=this.getters.getActiveSheetId(),t=[],n=this.getters.getFigures(e),{scrollX:r,scrollY:i}=this.getters.getActiveSheetScrollInfo(),{x:a,y:o}=this.getMainViewportCoordinates(),{width:s,height:c}=this.getters.getSheetViewDimensionWithHeaders();for(let l of n){let n=this.getFigureUI(e,l),{x:u,y:d}=n;u>=a&&(u+l.width<r+a||u>s+r+a)||d>=o&&(d+l.height<i+o||d>c+i+o)||t.push(n)}return t}getFigureUI(e,t){let n=t.offset.x+this.getters.getColDimensions(e,t.col).start,r=t.offset.y+this.getters.getRowDimensions(e,t.row).start;return{...t,x:n,y:r}}getPositionAnchorOffset(e){let{scrollX:t,scrollY:n}=this.getters.getActiveSheetScrollInfo(),r=e.x-t,i=e.y-n,a=r>=0?this.getColIndex(r):this.getColIndexLeftOfMainViewport(r),o=i>=0?this.getRowIndex(i):this.getRowIndexTopOfMainViewport(i),{x:s,y:c}=this.getRect(E({col:a,row:o}));return{col:a,row:o,offset:{x:Math.max(r-s+this.gridOffsetX,0),y:Math.max(i-c+this.gridOffsetY,0)}}}isPixelPositionVisible(e){let{scrollX:t,scrollY:n}=this.getters.getActiveSheetScrollInfo(),{x:r,y:i}=this.getters.getMainViewportCoordinates(),{width:a,height:o}=this.getters.getSheetViewDimension();return!(e.x>=r&&(e.x<r+t||e.x>a+t+r)||e.y>=i&&(e.y<i+n||e.y>o+n+i))}getFrozenSheetViewRatio(e){let{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e),r=this.getters.getColDimensions(e,t).start,i=this.getters.getRowDimensions(e,n).start,a=this.sheetViewWidth+this.gridOffsetX,o=this.sheetViewHeight+this.gridOffsetY;return{xRatio:r/a,yRatio:i/o}}mapViewportsToRect(e,t){let n=1/0,r=1/0,i=0,a=0,o=!1;for(let s of this.getSubViewports(e)){let e=t(s);e&&(o=!0,n=Math.min(n,e.x),r=Math.min(r,e.y),i=Math.max(i,e.x+e.width),a=Math.max(a,e.y+e.height))}return o?{x:n,y:r,width:i-n,height:a-r}:{x:0,y:0,width:0,height:0}}};let dq=new Kl().add(`settings`,jW).add(`sheet`,MW).add(`header grouping`,CW).add(`header visibility`,TW).add(`tables`,LW).add(`dataValidation`,xW).add(`cell`,hW).add(`merge`,DW).add(`style`,FW).add(`headerSize`,wW).add(`borders`,pW).add(`conditional formatting`,bW).add(`figures`,SW).add(`chart`,vW).add(`carousel`,mW).add(`image`,EW).add(`pivot_core`,AW).add(`spreadsheet_pivot_core`,NW).add(`tableStyle`,IW),fq=new Kl().add(`ui_sheet`,tq).add(`ui_options`,eq).add(`autofill`,WG).add(`sort`,XK).add(`automatic_sum`,GG).add(`format`,LK).add(`insert_pivot`,BK).add(`pivot_presence`,YK).add(`split_to_columns`,ZK).add(`subtotal_evaluation`,lb).add(`collaborative`,PK).add(`history`,qK).add(`table_autofill`,QK).add(`table_ui_resize`,$K).add(`datavalidation_insert`,FK).add(`checkbox_toggle`,XG).add(`dynamic_translate`,IK).add(`geo_features`,RK).add(`data_cleanup`,AG),pq=new Kl().add(`selection`,cq).add(`evaluation_filter`,oq).add(`header_visibility_ui`,zK).add(`cell_computed_style`,YG).add(`table_computed_style`,KG).add(`header_positions`,sq).add(`viewport`,uq).add(`clipboard`,iq).add(`carousel_ui`,nq),mq=new Kl().add(`evaluation`,lG).add(`evaluation_chart`,_G).add(`evaluation_cf`,vG).add(`row_size`,xG).add(`data_validation_ui`,bG).add(`dynamic_tables`,gG).add(`custom_colors`,hG).add(`pivot_ui`,EG).add(`cell_icon`,dG);ak.add(`dataValidation`,{displayAllOnInitialContent:!0,canBeToggled:!1,getProposals(e,t){if(Bt(t)||!this.composer.currentEditedCell)return[];let n=this.composer.currentEditedCell,r=this.getters.getValidationRuleForCell(n);if(!r||r.criterion.type!==`isValueInList`&&r.criterion.type!==`isValueInRange`)return[];let i=this.composer.currentEditedCell.sheetId,a=r.criterion.type===`isValueInRange`?this.getters.getDataValidationRangeValues(i,r.criterion):r.criterion.values.map(e=>({label:e,value:e}));if(r.criterion.displayStyle!==`chip`)return a.map(e=>({text:e.value,fuzzySearchKey:e.label,htmlContent:[{value:e.label}]}));let o=r.criterion.colors;return a.map(e=>{let t=o?.[e.value];return{text:e.value,htmlContent:[{value:e.label,color:Ur(t||`#E7E9ED`),backgroundColor:t||`#E7E9ED`,classes:[`badge rounded-pill fs-6 fw-normal w-100 mt-1 text-start`]}],fuzzySearchKey:e.label}})},selectProposal(e,t){this.composer.setCurrentContent(t),this.composer.stopEdition()}}),ak.add(`functions`,{sequence:100,autoSelectFirstProposal:!0,maxDisplayedProposals:10,getProposals(e){if(e.type!==`SYMBOL`)return[];let t=e.value;return Bt(this.composer.currentContent)?Object.entries(yO.content).filter(([e,{hidden:t}])=>!t).map(([e,{description:n}])=>({text:e,description:n,htmlContent:YH(t,e,le,`o-semi-bold`)})).sort((e,t)=>e.text.length-t.text.length||e.text.localeCompare(t.text)):[]},selectProposal(e,t){let n=e.end,r=e.end;[`SYMBOL`,`FUNCTION`].includes(e.type)&&(n=e.start);let i=this.composer.currentTokens;t+=`(`;let a=i.map(e=>e.start).indexOf(e.start);a+1<i.length&&i[a+1]?.type===`LEFT_PAREN`&&r++,this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t)}});function hq(e,t){for(let n=0;n<t.length;n++){let r=t[n].proposalValues;r===void 0||r.length===0||ak.add(`${e}_function_${t[n].name}_argument_proposals`,{sequence:50,autoSelectFirstProposal:!0,selectProposal:gq,getProposals:t=>{let i=t.functionContext;if(!i||i.parent.toUpperCase()!==e.toUpperCase()||i.argPosition!==n)return;let a=[],o=``;for(let{value:e,label:t}of r){switch(typeof e){case`string`:o=`"${e}"`;break;case`number`:o=e.toString();break;case`boolean`:o=e?`TRUE`:`FALSE`;break;default:}a.push({text:o,description:t,htmlContent:[{value:o,color:typeof e==`string`?He.STRING:He.NUMBER}],fuzzySearchKey:o,alwaysExpanded:!0})}return a}})}}function gq(e,t){let n=e.end,r=e.end;[`LEFT_PAREN`,`ARG_SEPARATOR`].includes(e.type)||(n=e.start),this.composer.stopComposerRangeSelection(),this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t)}yO.getAll().forEach(e=>hq(e.name,e.args)),ak.add(`pivot_ids`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||![`PIVOT.VALUE`,`PIVOT.HEADER`,`PIVOT`].includes(t.parent.toUpperCase())||t.argPosition!==0)return;let n=this.getters.getPivotIds();if(!n.includes(e.value))return n.map(e=>{let t=this.getters.getPivotCoreDefinition(e),n=`${this.getters.getPivotFormulaId(e)}`;return{text:n,description:t.name,htmlContent:[{value:n,color:He.NUMBER}],fuzzySearchKey:n+t.name,alwaysExpanded:!0}}).filter(C)},selectProposal:gq}),ak.add(`pivot_measures`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(t?.parent.toUpperCase()!==`PIVOT.VALUE`||t.argPosition!==1)return[];let n=NU(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return[];let i=this.getters.getPivot(r);return i.init(),i.isValid()?i.definition.measures.map(e=>{if(e.fieldName===`__count`){let e=`"__count"`;return{text:e,description:k(`Count`),htmlContent:[{value:e,color:He.STRING}],fuzzySearchKey:k(`Count`)+e}}return AU(e)}).filter(C):[]},selectProposal:gq}),ak.add(`pivot_group_fields`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||!_q(e)&&!vq(e))return;let n=NU(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return;let i=this.getters.getPivot(r);i.init();let a=i.getFields(),{columns:o,rows:s}=i.definition,c=t.args;t?.parent.toUpperCase()===`PIVOT.VALUE`?(c=c.filter((e,t)=>t%2==0),c=c.slice(1,t.argPosition)):c=c.filter((e,t)=>t%2==1);let l=c.map(e=>e?.value).filter(C),u=o.map(e=>e.nameWithGranularity),d=s.map(e=>e.nameWithGranularity),f=[],p=[`ARG_SEPARATOR`,`SPACE`].includes(e.type)?l.at(-1):l.at(-2),m=cW.get(i.type);if(m&&p?.startsWith(`#`)&&(p=p.slice(1)),p===void 0&&(f.push(u[0]),f.push(d[0])),d.includes(p)){let e=d[d.indexOf(p)+1];f.push(e),f.push(u[0])}if(u.includes(p)){let e=u[u.indexOf(p)+1];f.push(e)}let h=f.filter(C);return h.map(e=>{let[t,n]=e.split(`:`),r=a[t];return r?kU(r,n):void 0}).concat(h.map(e=>{if(!m)return;let t=a[e.split(`:`)[0]];if(!t)return;let n=`"#${e}"`;return{text:n,description:k(`%s (positional)`,t.string)+(t.help?` (${t.help})`:``),htmlContent:[{value:n,color:He.STRING}],fuzzySearchKey:t.string+n}})).filter(C)},selectProposal:gq});function _q(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.VALUE`&&t.argPosition>=2&&t.argPosition%2==0}function vq(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.HEADER`&&t.argPosition>=1&&t.argPosition%2==1}ak.add(`pivot_group_values`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||!e||!yq(e)&&!bq(e))return;let n=NU(e),r=this.getters.getPivotId(n);if(!r||!this.getters.isExistingPivot(r))return;let i=this.getters.getPivot(r);if(!i.isValid())return;let a=t.argPosition,o=e.functionContext?.args[a-1]?.value;if(!o)return;let s;try{s=i.definition.getDimension(o)}catch{return}return s.granularity===`month_number`?Object.values(Bo).map((e,t)=>({text:`${t+1}`,fuzzySearchKey:e.toString(),description:e.toString(),htmlContent:[{value:`${t+1}`,color:He.NUMBER}]})):s.granularity===`quarter_number`?[1,2,3,4].map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:k(`Quarter %s`,e),htmlContent:[{value:`${e}`,color:He.NUMBER}]})):s.granularity===`day_of_month`?S(1,32).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:He.NUMBER}]})):s.granularity===`iso_week_number`?S(0,54).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:He.NUMBER}]})):s.granularity===`day_of_week`?S(1,8).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:He.NUMBER}]})):s.granularity===`hour_number`?S(0,24).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:He.NUMBER}]})):s.granularity===`minute_number`?S(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:He.NUMBER}]})):s.granularity===`second_number`?S(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:He.NUMBER}]})):i.getPossibleFieldValues(s).map(({value:e,label:t})=>{let n=typeof e==`string`,r=n?`"${e}"`:e.toString(),i=n?He.STRING:He.NUMBER,a=t===e?``:t;return{text:r,description:a,htmlContent:[{value:r,color:i}],fuzzySearchKey:r+a}})},selectProposal:gq});function yq(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.VALUE`&&t.argPosition>=2&&t.argPosition%2==1}function bq(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.HEADER`&&t.argPosition>=1&&t.argPosition%2==0}ak.add(`sheet_names`,{sequence:150,autoSelectFirstProposal:!0,getProposals(e){return e.type===`SYMBOL`||e.type===`UNKNOWN`&&e.value.startsWith(`'`)?this.getters.getSheetIds().map(e=>{let t=Ye(this.getters.getSheetName(e));return{text:t,fuzzySearchKey:t.startsWith(`'`)?t:`'`+t}}):[]},selectProposal(e,t){let n=e.start,r=e.end;this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t+`!`)}});let xq=new B;xq.add(`link`,{condition:(e,t)=>!!t.getEvaluatedCell(e).link,execute:(e,t,n)=>$s(t.model.getters.getEvaluatedCell(e).link,t,n),title:(e,t)=>{let n=t.getEvaluatedCell(e).link;return n?n.isExternal?k(`Go to url: %(url)s`,{url:n.url}):k(`Go to %(label)s`,{label:n.label}):``},sequence:5}),xq.add(`dashboard_pivot_sorting`,{condition:(e,t)=>{if(!t.isDashboard())return!1;let n=t.getPivotCellFromPosition(e);return pR(t,e)&&n.type===`MEASURE_HEADER`},execute:(e,t)=>{mR(t,e,Cq(t.model.getters,e))},component:lW,componentProps:(e,t)=>({position:e,sortDirection:t.getPivotCellSortDirection(e)}),sequence:2});let Sq={none:`asc`,asc:`desc`,desc:`none`};function Cq(e,t){return Sq[e.getPivotCellSortDirection(t)??`none`]}uG.add(`filter_icon`,(e,t)=>{if(e.isFilterHeader(t)){let n=e.isFilterActive(t),r=kr(e.getCellComputedStyle(t).fillColor||`#fff`)<.45;return{type:`filter_icon`,svg:sj(n,r,!1),hoverSvg:sj(n,r,!0),priority:3,horizontalAlign:`right`,size:17,margin:2,position:t,onClick:(e,t)=>{let n=t.getStore(Bk),r=n.persistentCellPopover;if(r.isOpen&&r.col===e.col&&r.row===e.row&&r.type===`FilterMenu`){n.close();return}n.open(e,`FilterMenu`)}}}});let wq=new B().add(`ADD_COLUMNS_ROWS`,Dq).add(`REMOVE_COLUMNS_ROWS`,Mq).add(`ADD_MERGE`,Oq).add(`REMOVE_MERGE`,kq).add(`CREATE_SHEET`,Aq).add(`DELETE_SHEET`,Nq).add(`DUPLICATE_SHEET`,jq).add(`CREATE_FIGURE`,Pq).add(`CREATE_CHART`,Fq).add(`HIDE_COLUMNS_ROWS`,Iq).add(`UNHIDE_COLUMNS_ROWS`,Lq).add(`CREATE_TABLE_STYLE`,Rq).add(`ADD_PIVOT`,Eq).add(`RENAME_SHEET`,zq);for(let e of Vs.values())wq.contains(e)||wq.add(e,Tq);function Tq(e){return[e]}function Eq(e){return[{type:`REMOVE_PIVOT`,pivotId:e.pivotId}]}function Dq(e){let t=[],n=e.base;e.position===`after`&&n++;for(let r=0;r<e.quantity;r++)t.push(r+n);return[{type:`REMOVE_COLUMNS_ROWS`,dimension:e.dimension,elements:t,sheetId:e.sheetId,sheetName:e.sheetName}]}function Oq(e){return[{type:`REMOVE_MERGE`,sheetId:e.sheetId,target:e.target}]}function kq(e){return[{type:`ADD_MERGE`,sheetId:e.sheetId,target:e.target}]}function Aq(e){return[{type:`DELETE_SHEET`,sheetId:e.sheetId,sheetName:e.name}]}function jq(e){return[{type:`DELETE_SHEET`,sheetId:e.sheetIdTo,sheetName:``}]}function Mq(e){let t=[],n=[...e.elements].sort((e,t)=>e-t);for(let r of Ze(n)){let n=r[0]===0?0:r[0]-1,i=r[0]===0?`before`:`after`;t.push({type:`ADD_COLUMNS_ROWS`,dimension:e.dimension,quantity:r.length,base:n,sheetId:e.sheetId,sheetName:e.sheetName,position:i})}return t}function Nq(e){return[{type:`CREATE_SHEET`,sheetId:e.sheetId,position:1,name:e.sheetName}]}function Pq(e){return[{type:`DELETE_FIGURE`,figureId:e.figureId,sheetId:e.sheetId}]}function Fq(e){return[{type:`DELETE_FIGURE`,figureId:e.figureId,sheetId:e.sheetId}]}function Iq(e){return[{type:`UNHIDE_COLUMNS_ROWS`,sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}function Lq(e){return[{type:`HIDE_COLUMNS_ROWS`,sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]}function Rq(e){return[{type:`REMOVE_TABLE_STYLE`,tableStyleId:e.tableStyleId}]}function zq(e){return[{type:`RENAME_SHEET`,sheetId:e.sheetId,oldName:e.newName,newName:e.oldName}]}let Bq=new B;Bq.add(`format_number_automatic`,{...FR,id:`format_number_automatic`,sequence:10}).add(`format_number_plain_text`,{...IR,id:`format_number_plain_text`,sequence:15,separator:!0}).add(`format_number_number`,{...LR,id:`format_number_number`,sequence:20}).add(`format_number_percent`,{...zR,id:`format_number_percent`,sequence:30,separator:!1}).add(`format_number_scientific`,{...BR,id:`format_number_scientific`,sequence:33,separator:!0}).add(`format_number_currency`,{...VR,id:`format_number_currency`,sequence:40}).add(`format_number_accounting`,{...UR,id:`format_number_accounting`,sequence:45}).add(`format_number_currency_rounded`,{...HR,id:`format_number_currency_rounded`,sequence:50,separator:!0}).add(`format_number_date`,{...KR,id:`format_number_date`,sequence:70}).add(`format_number_time`,{...qR,id:`format_number_time`,sequence:80}).add(`format_number_date_time`,{...JR,id:`format_number_date_time`,sequence:90}).add(`format_number_duration`,{...YR,id:`format_number_duration`,sequence:100,separator:!0}).add(`format_custom_currency`,{...GR,id:`format_custom_currency`,sequence:120}).add(`format_custom_date`,{...XR,id:`format_custom_date`,sequence:130}).add(`format_custom_number`,{...ZR,id:`format_custom_number`,sequence:140});function Vq(e){let t=new Set(Bq.getAll().map(t=>typeof t.format==`function`?t.format(e):t.format)),n=new Map;for(let r of e.model.getters.getSheetIds()){let i=e.model.getters.getEvaluatedCells(r);for(let e in i){let r=i[e];if(r.format&&!n.has(r.format)&&!t.has(r.format)){let e=Hq(r.format);(e===`date`||e===`currency`)&&n.set(r.format,PR({descriptionValue:e===`currency`?1e3:WR,format:r.format,name:r.format}))}}}return[...n.values()]}let Hq=Dt(e=>ns(e)?`date`:e.includes(`[$`)?`currency`:`number`),Uq={name:k(`More formats`),icon:`o-spreadsheet-Icon.NUMBER_FORMATS`,children:[e=>{let t=Vq(e).map(e=>({...e,sequence:110}));return t.length>0&&(t[t.length-1].separator=!0),[...Bq.getAll(),...t]}]};function Wq(e){let t=new Zk;return t.add(`delete`,{...Wk,sequence:10}).add(`hide_sheet`,{...Xk,sequence:20}).add(`duplicate`,{...Gk,sequence:30,separator:!0}).add(`rename`,{...Kk(e),sequence:40}).add(`change_color`,{...qk(e),sequence:50,separator:!0}).add(`move_right`,{...Jk,sequence:60}).add(`move_left`,{...Yk,sequence:70}),t}let Gq=new Zk;Gq.add(`file`,{name:k(`File`),sequence:10}).addChild(`settings`,[`file`],{name:k(`Settings`),sequence:200,execute:e=>e.openSidePanel(`Settings`),isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.COG`}).add(`edit`,{name:k(`Edit`),sequence:20}).addChild(`undo`,[`edit`],{...dI,sequence:10}).addChild(`redo`,[`edit`],{...fI,sequence:20,separator:!0}).addChild(`copy`,[`edit`],{...pI,sequence:30}).addChild(`cut`,[`edit`],{...mI,sequence:40}).addChild(`paste`,[`edit`],{...hI,sequence:50}).addChild(`paste_special`,[`edit`],{...gI,sequence:60,separator:!0}).addChild(`paste_special_value`,[`edit`,`paste_special`],{..._I,sequence:10}).addChild(`paste_special_format`,[`edit`,`paste_special`],{...vI,sequence:20}).addChild(`edit_table`,[`edit`],{...jI,isVisible:uF,sequence:60}).addChild(`find_and_replace`,[`edit`],{...yI,sequence:65,separator:!0}).addChild(`delete`,[`edit`],{name:k(`Delete`),icon:`o-spreadsheet-Icon.TRASH`,sequence:70}).addChild(`edit_delete_cell_values`,[`edit`,`delete`],{...bI,sequence:10}).addChild(`edit_delete_row`,[`edit`,`delete`],{...xI,sequence:20}).addChild(`edit_delete_column`,[`edit`,`delete`],{...wI,sequence:30}).addChild(`edit_delete_cell_shift_up`,[`edit`,`delete`],{...OI,sequence:40}).addChild(`edit_delete_cell_shift_left`,[`edit`,`delete`],{...kI,sequence:50}).addChild(`edit_unhide_columns`,[`edit`],{...EF,sequence:80}).addChild(`edit_unhide_rows`,[`edit`],{...kF,sequence:80}).add(`view`,{name:k(`View`),sequence:30}).addChild(`unfreeze_panes`,[`view`],{...AF,sequence:4}).addChild(`freeze_panes`,[`view`],{...jF,sequence:5}).addChild(`unfreeze_rows`,[`view`,`freeze_panes`],{...MF,sequence:5}).addChild(`freeze_first_row`,[`view`,`freeze_panes`],{...NF,sequence:10}).addChild(`freeze_second_row`,[`view`,`freeze_panes`],{...PF,sequence:15}).addChild(`freeze_current_row`,[`view`,`freeze_panes`],{...FF,sequence:20,separator:!0}).addChild(`unfreeze_columns`,[`view`,`freeze_panes`],{...IF,sequence:25}).addChild(`freeze_first_col`,[`view`,`freeze_panes`],{...LF,sequence:30}).addChild(`freeze_second_col`,[`view`,`freeze_panes`],{...RF,sequence:35}).addChild(`freeze_current_col`,[`view`,`freeze_panes`],{...zF,sequence:40}).addChild(`group_headers`,[`view`],{name:k(`Group`),sequence:15,separator:!0,icon:`o-spreadsheet-Icon.PLUS_IN_BOX`,isVisible:gF}).addChild(`group_columns`,[`view`,`group_headers`],{...WF,sequence:5}).addChild(`ungroup_columns`,[`view`,`group_headers`],{...KF,isVisible:e=>XF(e,`COL`),sequence:10}).addChild(`group_rows`,[`view`,`group_headers`],{...GF,sequence:15}).addChild(`ungroup_rows`,[`view`,`group_headers`],{...qF,isVisible:e=>XF(e,`ROW`),sequence:20}).addChild(`show`,[`view`],{name:k(`Show`),sequence:1,icon:`o-spreadsheet-Icon.SHOW`}).addChild(`view_gridlines`,[`view`,`show`],{...BF,sequence:5}).addChild(`view_formulas`,[`view`,`show`],{...UF,sequence:10}).addChild(`zoom`,[`view`],{name:k(`Zoom`),sequence:1,icon:`o-spreadsheet-Icon.ZOOM`}).addChild(`view_irregularity_map`,[`view`],{...VF,sequence:40,separator:!0}).add(`insert`,{name:k(`Insert`),sequence:40}).addChild(`insert_row`,[`insert`],{...II,sequence:10}).addChild(`insert_row_before`,[`insert`,`insert_row`],{...RI,sequence:10}).addChild(`insert_row_after`,[`insert`,`insert_row`],{...VI,sequence:20}).addChild(`insert_column`,[`insert`],{...HI,sequence:20}).addChild(`insert_column_before`,[`insert`,`insert_column`],{...WI,sequence:10}).addChild(`insert_column_after`,[`insert`,`insert_column`],{...qI,sequence:20}).addChild(`insert_cell`,[`insert`],{...JI,sequence:30}).addChild(`insert_cell_down`,[`insert`,`insert_cell`],{...YI,name:k(`Shift down`),sequence:10}).addChild(`insert_cell_right`,[`insert`,`insert_cell`],{...XI,name:k(`Shift right`),sequence:20}).addChild(`insert_sheet`,[`insert`],{...mL,sequence:40,separator:!0}).addChild(`insert_chart`,[`insert`],{...ZI,sequence:50}).addChild(`insert_carousel`,[`insert`],{...QI,sequence:51}).addChild(`insert_pivot`,[`insert`],{...$I,sequence:52}).addChild(`insert_image`,[`insert`],{...eL,sequence:55}).addChild(`insert_table`,[`insert`],{...tL,sequence:57}).addChild(`insert_function`,[`insert`],{...nL,sequence:60}).addChild(`insert_function_sum`,[`insert`,`insert_function`],{...rL,sequence:0}).addChild(`insert_function_average`,[`insert`,`insert_function`],{...iL,sequence:10}).addChild(`insert_function_count`,[`insert`,`insert_function`],{...aL,sequence:20}).addChild(`insert_function_max`,[`insert`,`insert_function`],{...oL,sequence:30}).addChild(`insert_function_min`,[`insert`,`insert_function`],{...sL,sequence:40,separator:!0}).addChild(`categorie_function_all`,[`insert`,`insert_function`],{...cL,sequence:50}).addChild(`categories_function_list`,[`insert`,`insert_function`],uL).addChild(`insert_link`,[`insert`],{...dL,separator:!0,sequence:70}).addChild(`insert_checkbox`,[`insert`],{...fL,sequence:80}).addChild(`insert_dropdown`,[`insert`],{...pL,separator:!0,sequence:90}).add(`format`,{name:k(`Format`),sequence:50}).addChild(`format_number`,[`format`],{...Uq,name:k(`Number`),sequence:10,separator:!0}).addChild(`format_bold`,[`format`],{...ez,sequence:20}).addChild(`format_italic`,[`format`],{...tz,sequence:30}).addChild(`format_underline`,[`format`],{...nz,sequence:40}).addChild(`format_strikethrough`,[`format`],{...dz,sequence:50,separator:!0}).addChild(`format_font_size`,[`format`],{...fz,sequence:60,separator:!0}).addChild(`format_alignment`,[`format`],{...pz,sequence:70}).addChild(`format_alignment_left`,[`format`,`format_alignment`],{...hz,sequence:10}).addChild(`format_alignment_center`,[`format`,`format_alignment`],{...gz,sequence:20}).addChild(`format_alignment_right`,[`format`,`format_alignment`],{..._z,sequence:30,separator:!0}).addChild(`format_alignment_top`,[`format`,`format_alignment`],{...yz,sequence:40}).addChild(`format_alignment_middle`,[`format`,`format_alignment`],{...bz,sequence:50}).addChild(`format_alignment_bottom`,[`format`,`format_alignment`],{...xz,sequence:60,separator:!0}).addChild(`format_wrapping`,[`format`],{...Sz,sequence:80,separator:!0}).addChild(`format_wrapping_overflow`,[`format`,`format_wrapping`],{...wz,sequence:10}).addChild(`format_wrapping_wrap`,[`format`,`format_wrapping`],{...Tz,sequence:20}).addChild(`format_wrapping_clip`,[`format`,`format_wrapping`],{...Ez,sequence:30}).addChild(`format_cf`,[`format`],{...Dz,sequence:90,separator:!0}).addChild(`format_clearFormat`,[`format`],{...Oz,sequence:100,separator:!0}).add(`data`,{name:k(`Data`),sequence:60}).addChild(`sort_range`,[`data`],{...CR,sequence:10,separator:!0}).addChild(`sort_ascending`,[`data`,`sort_range`],{...wR,sequence:10}).addChild(`sort_descending`,[`data`,`sort_range`],{...OR,sequence:20}).addChild(`data_cleanup`,[`data`],{...TR,sequence:15}).addChild(`remove_duplicates`,[`data`,`data_cleanup`],{...ER,sequence:10}).addChild(`trim_whitespace`,[`data`,`data_cleanup`],{...DR,sequence:20}).addChild(`split_to_columns`,[`data`],{...jR,sequence:20}).addChild(`data_validation`,[`data`],{name:k(`Data Validation`),execute:e=>{e.openSidePanel(`DataValidation`)},isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.DATA_VALIDATION`,sequence:30,separator:!0}).addChild(`add_remove_data_filter`,[`data`],{...kR,sequence:40,separator:!0}).addChild(`pivot_data_sources`,[`data`],e=>{let t=e.model.getters.getPivotIds().length;return e.model.getters.getPivotIds().map((n,r)=>{let i={get highlights(){return GH(e.model.getters,n)}};return{id:`item_pivot_${e.model.getters.getPivotFormulaId(n)}`,name:e.model.getters.getPivotDisplayName(n),sequence:50+r/t,isReadonlyAllowed:!0,execute:e=>e.openSidePanel(`PivotSidePanel`,{pivotId:n}),isEnabled:e=>!e.isSmall,onStartHover:e=>e.getStore(sk).register(i),onStopHover:e=>e.getStore(sk).unRegister(i),icon:`o-spreadsheet-Icon.PIVOT`,separator:r===e.model.getters.getPivotIds().length-1,secondaryIcon:e=>e.model.getters.isPivotUnused(n)?`o-spreadsheet-Icon.UNUSED_PIVOT_WARNING`:void 0}})}).addChild(`reinsert_dynamic_pivot`,[`data`],MR).addChild(`reinsert_static_pivot`,[`data`],NR),ve.forEach(e=>{Gq.addChild(`zoom${e}`,[`view`,`zoom`],HF(e))});let Kq=[qq,Jq,Xq,Zq];function qq(e,t){return`sheetId`in t?{...b(t),sheetId:e.getActiveSheetId()}:t}function Jq(e,t){return!(`target`in t)||!Array.isArray(t.target)?t:{...b(t),target:e.getSelectedZones()}}function Yq(e,t){return`zone`in t?{...b(t),zone:e.getSelectedZone()}:t}function Xq(e,t){if(!(`row`in t)||!(`col`in t))return t;let{col:n,row:r}=e.getActivePosition();return{...b(t),col:n,row:r}}function Zq(e,t){return`ranges`in t?{...b(t),ranges:e.getSelectedZones().map(t=>e.getRangeDataFromZone(e.getActiveSheetId(),t))}:t}let Qq=new Gl;function $q(e,t){let n=Qq.smallUuid();return{...qq(e,t),figureId:n,chartId:n}}function eJ(e,t){return{...qq(e,t),figureId:Qq.smallUuid()}}function tJ(e,t){let n=Xq(e,qq(e,t));return n.figureId=Qq.smallUuid(),n}function nJ(e,t){let n=b(t);n.sheetId=Qq.smallUuid();let r=t.name||e.getSheet(e.getActiveSheetId()).name,i=r.match(/(.+?)\d*$/)?.[1]||r;return n.name=e.getNextSheetName(i),n}function rJ(e,t){let n=e.getActivePosition();return{...qq(e,t),base:t.dimension===`COL`?n.col:n.row}}function iJ(e,t){let n=e.getSelectedZone();return{...qq(e,t),elements:t.dimension===`COL`?S(n.left,n.right+1):S(n.top,n.bottom+1)}}function aJ(e,t){let n=e.getSelectedZone();return{...b(t),zone:n}}function oJ(e,t){let n=b(t),{top:r,bottom:i,left:a,right:o}=e.getSelectedZone();return`cols`in n?n.cols=S(a,o+1):`rows`in n&&(n.rows=S(r,i+1)),n}function sJ(e,t){let n=e.getSelectedZone();return{...qq(e,t),col:n.left,row:n.top,zone:n}}function cJ(e,t){return{type:`REPEAT_PASTE`,pasteOption:b(t.pasteOption),target:e.getSelectedZones()}}function lJ(e,t){let n=e.getSelectedZone();return{...qq(e,t),start:t.dimension===`COL`?n.left:n.top,end:t.dimension===`COL`?n.right:n.bottom}}VK.add(`UPDATE_CELL`,uJ),VK.add(`CLEAR_CELL`,uJ),VK.add(`CLEAR_CELLS`,uJ),VK.add(`DELETE_CONTENT`,uJ),VK.add(`ADD_MERGE`,uJ),VK.add(`REMOVE_MERGE`,uJ),VK.add(`SET_FORMATTING`,uJ),VK.add(`CLEAR_FORMATTING`,uJ),VK.add(`SET_BORDER`,uJ),VK.add(`CREATE_TABLE`,uJ),VK.add(`REMOVE_TABLE`,uJ),VK.add(`HIDE_SHEET`,uJ),VK.add(`ADD_COLUMNS_ROWS`,rJ),VK.add(`REMOVE_COLUMNS_ROWS`,iJ),VK.add(`HIDE_COLUMNS_ROWS`,iJ),VK.add(`RESIZE_COLUMNS_ROWS`,iJ),VK.add(`CREATE_SHEET`,nJ),VK.add(`CREATE_FIGURE`,tJ),VK.add(`CREATE_CHART`,$q),VK.add(`CREATE_IMAGE`,eJ),VK.add(`GROUP_HEADERS`,lJ),VK.add(`UNGROUP_HEADERS`,lJ),VK.add(`UNFOLD_HEADER_GROUPS_IN_ZONE`,Yq),VK.add(`FOLD_HEADER_GROUPS_IN_ZONE`,Yq),HK.add(`PASTE`,cJ),HK.add(`INSERT_CELL`,aJ),HK.add(`DELETE_CELL`,aJ),HK.add(`AUTORESIZE_COLUMNS`,oJ),HK.add(`AUTORESIZE_ROWS`,oJ),HK.add(`SORT_CELLS`,sJ),HK.add(`SUM_SELECTION`,uJ),HK.add(`SET_DECIMAL`,uJ),HK.add(`DELETE_UNFILTERED_CONTENT`,uJ);function uJ(e,t){let n=b(t);for(let t of Kq)n=t(e,n);return n}let dJ=new class extends B{mapping={};uuidGenerator=new Gl;replace(e,t){let n={...t,id:this.uuidGenerator.uuidv4()};return super.replace(e,n)}getAllOrdered(){return this.getAll().sort((e,t)=>e.sequence-t.sequence)}};var fJ=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)}},pJ=class{fileStore;constructor(e){this.fileStore=e}async requestImage(){let e=await this.userImageUpload(),t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}async uploadFile(e){let t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}userImageUpload(){return new Promise((e,t)=>{let n=document.createElement(`input`);n.setAttribute(`type`,`file`),n.setAttribute(`accept`,`image/*`),n.addEventListener(`change`,async()=>{n.files===null||n.files.length!==1?t():e(n.files[0])}),n.click()})}getImageOriginalSize(e){return new Promise((t,n)=>{let r=new Image;r.addEventListener(`load`,()=>{t({width:r.width,height:r.height})}),r.addEventListener(`error`,n),r.src=e})}};let mJ=[{transform:`scale(0)`},{transform:`scale(0.8)`,offset:.33},{opacity:`0`,transform:`scale(1)`,offset:1}];var hJ=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(mJ,{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}`})}},gJ=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:hJ};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{...tp(e),marginLeft:0,marginTop:0};let t=e.firstElementChild,n=fv(t);return{...tp(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 _J(e,t,n,r){let i=e.model.dispatch(`RENAME_SHEET`,{sheetId:t,newName:n,oldName:e.model.getters.getSheetName(t)});i.reasons.includes(`MissingSheetName`)?e.raiseError(k(`The sheet name cannot be empty.`),r):i.reasons.includes(`DuplicatedSheetName`)?e.raiseError(k(`A sheet with the name %s already exists. Please select another name.`,n),r):i.reasons.includes(`ForbiddenCharactersInSheetName`)&&e.raiseError(k(`Some used characters are not allowed in a sheet name (Forbidden characters are %s).`,je.join(` `)),r)}var vJ=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:gJ,ColorPicker:yk};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=D(xO),(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()}onClick(){this.env.isMobile()&&this.activateSheet()}onMouseDown(e){this.env.isMobile()||(this.activateSheet(),this.props.onMouseDown(e))}activateSheet(){this.env.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:this.env.model.getters.getActiveSheetId(),sheetIdTo:this.props.sheetId}),this.scrollToSheet()}onDblClick(){this.env.model.getters.isReadonly()||this.startEdition()}onKeyDown(e){this.state.isEditing&&(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()||``;_J(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 tp(e)}get contextMenuRegistry(){return Wq({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 yJ=[{name:k(`Sum`),types:[`number`],compute:(e,t)=>Vm([[e]],t)},{name:k(`Avg`),types:[`number`],compute:(e,t)=>vm([[e]],t)},{name:k(`Min`),types:[`number`],compute:(e,t)=>Sm([[e]],t).value},{name:k(`Max`),types:[`number`],compute:(e,t)=>xm([[e]],t).value},{name:k(`Count`),types:[`number`,`text`,`boolean`,`error`],compute:e=>bm([[e]])},{name:k(`Count Numbers`),types:[`number`,`text`,`boolean`,`error`],compute:(e,t)=>ym([[e]],t)}];var bJ=class extends hr{statisticFnResults=this._computeStatisticFnResults();isDirty=!1;constructor(e){super(e),this.model.selection.observe(this,{handleEvent:this.handleEvent.bind(this)}),this.onDispose(()=>{this.model.selection.unobserve(this)})}handle(e){switch((Ps.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=Qt(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=Dt(e=>{let t=e.split(`,`);return n.filter(e=>t.includes(e.type))});for(let e of yJ){let t,n=c(e.types.sort().join(`,`));n.length&&(t=mt(()=>e.compute(n,o))),s[e.name]=t}return s}},xJ=class extends t.Component{static template=`o-spreadsheet-BottomBarStatistic`;static props={openContextMenu:Function,closeContextMenu:Function};static components={Ripple:gJ};selectedStatisticFn=``;store;setup(){this.store=D(bJ),(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 Zk,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?`__`:z(n(),{locale:t}))}},SJ=class extends t.Component{static template=`o-spreadsheet-BottomBar`;static props={onClick:Function};static components={MenuPopover:Dv,Ripple:gJ,BottomBarSheet:vJ,BottomBarStatistic:xJ};bottomBarRef=(0,t.useRef)(`bottomBar`);sheetListRef=(0,t.useRef)(`sheetList`);dragAndDrop=Sk();targetScroll=void 0;state=(0,t.useState)({isSheetListScrollableLeft:!1,isSheetListScrollableRight:!1});menuMaxHeight=250;menuState=(0,t.useState)({isOpen:!1,menuId:void 0,anchorRect:null,menuItems:[]});sheetList=this.getVisibleSheets();setup(){(0,t.onWillUpdateProps)(()=>{this.updateScrollState();let e=this.getVisibleSheets();w(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(k(`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 Zk,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.anchorRect={x:e,y:t,width:0,height:0}}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.anchorRect=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()||(this.closeMenu(),this.env.isMobile()))return;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}},CJ=class extends hr{_clickableCells=(0,t.markRaw)({});_registryItems=(0,t.markRaw)(xq.getAll().sort((e,t)=>e.sequence-t.sequence));handle(e){(Ps.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)(xq.getAll().sort((e,t)=>e.sequence-t.sequence)))}getClickableItem(e){let{sheetId:t,col:n,row:r}=e,i=this._clickableCells,a=T(n,r);if(i[t]||(i[t]={}),!(a in i[t])){let n=this.findClickableItem(e);i[t][a]=n}return i[t][a]}findClickableItem(e){let t=this.getters;for(let n of this._registryItems)if(n.condition(e,t))return n}get clickableCells(){let e=[],t=this.getters;for(let n of this.getters.getVisibleCellPositions()){let r=this.getClickableItem(n);if(!r)continue;let i=typeof r.title==`function`?r.title(n,t):r.title,a=this.getClickableCellRect(n);a&&e.push({coordinates:a,position:n,action:r.execute,title:i||``,component:r.component,componentProps:r.componentProps?.(n,t)??{}})}return e}getClickableCellRect(e){let t=this.getters.expandZone(e.sheetId,E(e)),n=this.getters.getVisibleRect(t),r=this.getters.getCellIcons(e),i={center:r.find(e=>e.horizontalAlign===`center`),left:r.find(e=>e.horizontalAlign===`left`),right:r.find(e=>e.horizontalAlign===`right`)};if(!i.center?.onClick){if(i.right?.onClick){let e=this.getters.getRect(t),r=this.getters.getCellIconRect(i.right,e);n.width-=r.width+i.right.margin}if(i.left?.onClick){let e=this.getters.getRect(t),r=this.getters.getCellIconRect(i.left,e);n.x+=r.width+i.left.margin,n.width-=r.width+i.left.margin}return n}}},wJ=class extends t.Component{static template=`o-spreadsheet-SpreadsheetDashboard`;static props={getGridSize:Function};static components={GridOverlay:KB,GridPopover:qB,Popover:Cv,VerticalScrollBar:fV,HorizontalScrollBar:dV};cellPopovers;onMouseWheel;canvasPosition;hoveredCell;clickableCellsStore;gridRef;setup(){this.gridRef=(0,t.useRef)(`grid`),this.hoveredCell=D(Pv),this.clickableCellsStore=D(CJ),(0,t.useChildSubEnv)({getPopoverContainerRect:()=>xp(this.env.model.getters.getViewportZoomLevel(),this.getGridRect())}),tV(`canvas`,this.env.model,()=>this.env.model.getters.getSheetViewDimension()),this.onMouseWheel=iV((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=D(Bk),rV(this.gridRef,this.moveCanvas.bind(this),()=>{let{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0},()=>{let{maxOffsetY:e}=this.env.model.getters.getMaximumSheetOffset(),{scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo();return t<e})}get gridContainer(){return U({"max-width":`${this.getMaxSheetWidth()}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,t){let{position:n,action:r}=t;r(n,this.env,dp(e))}onClosePopover(){this.cellPopovers.close()}onGridResized(){let{height:e,width:t}=this.props.getGridSize(),n=this.getMaxSheetWidth();this.env.model.dispatch(`RESIZE_SHEETVIEW`,{width:Math.min(n,t),height:e,gridOffsetX:0,gridOffsetY:0})}moveCanvas(e,t){let{scrollX:n,scrollY:r}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:n+e,offsetY:r+t})}getGridRect(){return{...ep(this.gridRef),...this.env.model.getters.getSheetViewDimensionWithHeaders()}}getMaxSheetWidth(){let e=this.env.model.getters.getActiveSheetId(),{right:t}=this.env.model.getters.getSheetZone(e);return this.env.model.getters.getColDimensions(e,t).end}},TJ=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;Hz(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=Wz(t,this.dimension,r.start,r.end);this.props.openContextMenu(n,i)}},EJ=class extends TJ{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`,"border-bottom":e.isEndHidden?``:`1px solid`})}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)}}},DJ=class extends TJ{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`,"border-right":e.isEndHidden?``:`1px solid`})}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)}}},OJ=class extends t.Component{static template=`o-spreadsheet-HeaderGroupContainer`;static props={dimension:String,layers:Array};static components={RowGroup:EJ,ColGroup:DJ,MenuPopover:Dv};menu=(0,t.useState)({isOpen:!1,anchorRect:null,menuItems:[]});getLayerOffset(e){return e*21}onContextMenu(e){let t=this.env.model.getters.getActiveSheetId(),n={x:e.clientX,y:e.clientY},r=Uz(t,this.props.dimension);this.openContextMenu(n,r)}openContextMenu(e,t){this.menu.isOpen=!0,this.menu.anchorRect={...e,width:0,height:0},this.menu.menuItems=t}closeMenu(){this.menu.isOpen=!1,this.menu.anchorRect=null,this.menu.menuItems=[]}get groupComponent(){return this.props.dimension===`ROW`?EJ:DJ}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}};function kJ(){let e=xv();return{get isSmall(){return e.width<768}}}var AJ=class extends t.Component{static template=`o-spreadsheet-SidePanel`;static props={panelContent:Object,panelProps:Object,onCloseSidePanel:Function,onStartHandleDrag:Function,onResetPanelSize:Function,isPinned:{type:Boolean,optional:!0},onTogglePinPanel:{type:Function,optional:!0},onToggleCollapsePanel:{type:Function,optional:!0},isCollapsed:{type:Boolean,optional:!0}};spreadsheetRect=xv();getTitle(){let e=this.props.panelContent;return typeof e.title==`function`?e.title(this.env,this.props.panelProps):e.title}get pinInfoMessage(){return k(`Pin this panel to allow to open another side panel beside it.`)}},jJ=class extends t.Component{static template=`o-spreadsheet-SidePanels`;static props={};static components={SidePanel:AJ};sidePanelStore;spreadsheetRect=xv();setup(){this.sidePanelStore=D(iW),(0,t.useEffect)(()=>{this.sidePanelStore.mainPanel&&!this.sidePanelStore.isMainPanelOpen&&this.sidePanelStore.closeMainPanel(),this.sidePanelStore.secondaryPanel&&!this.sidePanelStore.isSecondaryPanelOpen&&this.sidePanelStore.close()},()=>[this.sidePanelStore.isMainPanelOpen,this.sidePanelStore.isSecondaryPanelOpen])}startHandleDrag(e,t){let n=document.body.style.cursor,r=e===`mainPanel`?this.sidePanelStore.mainPanel:this.sidePanelStore.secondaryPanel;if(!r)return;let i=r.size,a=t.clientX;vk(t=>{document.body.style.cursor=`col-resize`;let n=i+a-t.clientX;this.sidePanelStore.changePanelSize(e,n)},()=>{document.body.style.cursor=n})}get mainPanelProps(){let e=this.sidePanelStore.mainPanelProps;if(!(!this.sidePanelStore.mainPanel||!e))return{panelContent:nW.get(this.sidePanelStore.mainPanel.componentTag),panelProps:e,onCloseSidePanel:()=>this.sidePanelStore.closeMainPanel(),onTogglePinPanel:()=>this.sidePanelStore.togglePinPanel(),onStartHandleDrag:e=>this.startHandleDrag(`mainPanel`,e),onResetPanelSize:()=>this.sidePanelStore.resetPanelSize(`mainPanel`),isPinned:this.sidePanelStore.mainPanel?.isPinned,onToggleCollapsePanel:()=>this.sidePanelStore.toggleCollapsePanel(`mainPanel`),isCollapsed:this.sidePanelStore.mainPanel?.isCollapsed}}get secondaryPanelProps(){let e=this.sidePanelStore.secondaryPanelProps;if(!(!this.sidePanelStore.secondaryPanel||!e))return{panelContent:nW.get(this.sidePanelStore.secondaryPanel.componentTag),panelProps:e,onCloseSidePanel:()=>this.sidePanelStore.close(),onStartHandleDrag:e=>this.startHandleDrag(`secondaryPanel`,e),onResetPanelSize:()=>this.sidePanelStore.resetPanelSize(`secondaryPanel`),onToggleCollapsePanel:()=>this.sidePanelStore.toggleCollapsePanel(`secondaryPanel`),isCollapsed:this.sidePanelStore.secondaryPanel?.isCollapsed}}get panelList(){return[{key:this.sidePanelStore.secondaryPanelKey,props:this.secondaryPanelProps,style:this.sidePanelStore.secondaryPanel?U({width:`${this.sidePanelStore.secondaryPanel.size}px`}):``},{key:this.sidePanelStore.mainPanelKey,props:this.mainPanelProps,style:this.sidePanelStore.mainPanel?U({width:`${this.sidePanelStore.mainPanel.size}px`}):``}].filter(e=>e.key&&e.props)}},MJ=class extends t.Component{static template=`o-spreadsheet-RibbonMenu`;static props={onClose:Function};static components={Menu:hv};rootItems=Gq.getMenuItems();menuRef=(0,t.useRef)(`menu`);containerRef=(0,t.useRef)(`container`);state=(0,t.useState)({menuItems:this.rootItems,title:k(`Menu Bar`),parentState:void 0});setup(){(0,t.useExternalListener)(window,`click`,this.onExternalClick,{capture:!0}),(0,t.onMounted)(this.updateShadows)}onExternalClick(e){this.menuRef.el?.contains(e.target)||this.props.onClose()}onClickMenu(e){let t=e.children(this.env);t.length?(this.state.parentState={...this.state},this.state.menuItems=t,this.state.title=e.name(this.env),this.containerRef.el?.scrollTo({top:0})):(this.state.menuItems=this.rootItems,this.state.title=void 0,this.state.parentState=void 0,e.execute?.(this.env),this.props.onClose())}get menuProps(){return{menuItems:g(this.env,this.state.menuItems),onClose:this.props.onClose,onClickMenu:this.onClickMenu.bind(this)}}get style(){return U({height:`${this.props.height}px`})}updateShadows(){if(!this.containerRef.el)return;this.containerRef.el.classList.remove(`scroll-top`,`scroll-bottom`);let e=this.containerRef.el.scrollHeight-this.containerRef.el.clientHeight||0;this.containerRef.el.scrollTop<e-1&&this.containerRef.el.classList.add(`scroll-bottom`),this.containerRef.el.scrollTop>0&&this.containerRef.el.classList.add(`scroll-top`)}onClickBack(){if(!this.state.parentState){this.props.onClose();return}this.state.menuItems=this.state.parentState.menuItems,this.state.title=this.state.parentState.title,this.state.parentState=this.state.parentState.parentState,this.containerRef.el?.scrollTo({top:0})}get backTitle(){return this.state.parentState?k(`Go to previous menu`):k(`Close menu bar`)}},NJ=class extends t.Component{static components={Composer:PO,BottomBar:SJ,Ripple:gJ,RibbonMenu:MJ};static template=`o-spreadsheet-SmallBottomBar`;static props={onClick:Function};composerFocusStore;composerStore;composerInterface;composerRef=(0,t.useRef)(`bottombarComposer`);menuState=(0,t.useState)({isOpen:!1});setup(){this.composerFocusStore=D(_r);let e=D(CB);this.composerStore=e,this.composerInterface={id:`bottombarComposer`,get editionMode(){return e.editionMode},startEdition:this.composerStore.startEdition,setCurrentContent:this.composerStore.setCurrentContent,stopEdition:this.composerStore.stopEdition},(0,t.useEffect)(()=>{this.env.isMobile()&&!this.menuState.isOpen&&this.composerStore.editionMode!==`inactive`&&this.composerFocusStore.activeComposer!==this.composerInterface&&this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`contentFocus`})})}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:`inactive`}get showFxIcon(){return this.focus===`inactive`&&!this.composerStore.currentContent&&!this.composerStore.placeholder}get rect(){return this.composerRef.el?tp(this.composerRef.el):{x:0,y:0,width:0,height:0}}get composerProps(){let{width:e,height:t}=this.env.model.getters.getSheetViewDimensionWithHeaders();return{rect:{...this.rect},delimitation:{width:e,height:t},focus:this.focus,composerStore:this.composerStore,onComposerContentFocused:e=>this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`contentFocus`,selection:e}),isDefaultFocus:!1,inputStyle:U({height:this.focus===`inactive`?`26px`:`fit-content`,"max-height":`130px`}),showAssistant:!1,placeholder:this.composerStore.placeholder}}get symbols(){return[`=`,`(`,`)`,`:`,`-`,`/`,`*`,`,`,`+`,`$`,`.`]}insertSymbol(e){this.composerStore.replaceComposerCursorSelection(e),this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`contentFocus`})}toggleRibbon(){this.composerStore.cancelEdition(),this.menuState.isOpen=!this.menuState.isOpen}},PJ=class extends t.Component{static template=`o-spreadsheet-TopBarComposer`;static props={};static components={Composer:PO};composerFocusStore;composerStore;composerInterface;setup(){this.composerFocusStore=D(_r);let e=D(CB);this.composerStore=e,this.composerInterface={id:`topbarComposer`,get editionMode(){return e.editionMode},startEdition:this.composerStore.startEdition,setCurrentContent:this.composerStore.setCurrentContent,stopEdition:this.composerStore.stopEdition}}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:`inactive`}get showFxIcon(){return this.focus===`inactive`&&!this.composerStore.currentContent&&!this.composerStore.placeholder}get composerStyle(){let e={padding:`5px 0px 5px 8px`,"max-height":`300px`,"line-height":`24px`};return e.height=this.focus===`inactive`?`34px`:`fit-content`,U(e)}onFocus(e){this.composerFocusStore.focusComposer(this.composerInterface,{selection:e})}},FJ=class{mutators=[`closeDropdowns`,`openDropdown`];_currentDropdown=null;closeDropdowns(){this._currentDropdown=null}openDropdown(e){this._currentDropdown=e}get currentDropdown(){return this._currentDropdown}},IJ=class{content={};add(e){if(e in this.content)throw Error(`${e} is already present in this registry!`);return this.content[e]=[],this}addChild(e,t){return this.content[e].push(t),this}getEntries(e){return this.content[e].sort((e,t)=>e.sequence-t.sequence)}getCategories(){return Object.keys(this.content)}};function LJ(){let e=(0,t.useComponent)(),n=D(FJ);return(0,t.onWillUnmount)(()=>{e===n.currentDropdown&&n.closeDropdowns()}),{closeDropdowns:()=>n.closeDropdowns(),openDropdown:()=>{n.openDropdown(e)},get isActive(){return n.currentDropdown===e}}}let RJ=[[[`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`]]];var zJ=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:vV,Popover:Cv};BORDER_POSITIONS=RJ;lineStyleButtonRef=(0,t.useRef)(`lineStyleButton`);borderStyles=ba;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:`bottom-left`,verticalOffset:0}}get popoverProps(){return{anchorRect:this.props.anchorRect,maxHeight:this.props.maxHeight,positioning:`bottom-left`,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}}},BJ=class extends t.Component{static template=`o-spreadsheet-BorderEditorWidget`;static props={disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};static components={BorderEditor:zJ};topBarToolStore;borderEditorButtonRef=(0,t.useRef)(`borderEditorButton`);state=(0,t.useState)({currentColor:Te.color,currentStyle:Te.style,currentPosition:void 0});setup(){this.topBarToolStore=LJ(),(0,t.onWillUpdateProps)(()=>{this.isActive||(this.state.currentPosition=void 0)})}get dropdownMaxHeight(){return this.env.model.getters.getSheetViewDimension().height}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()}get isActive(){return this.topBarToolStore.isActive}toggleBorderEditor(){this.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}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}})}},VJ=class extends t.Component{static template=`o-spreadsheet-PaintFormatButton`;static props={class:{type:String,optional:!0}};paintFormatStore;setup(){this.paintFormatStore=D(HB)}get isActive(){return this.paintFormatStore.isActive}onDblClick(){this.paintFormatStore.activate({persistent:!0})}togglePaintFormat(){this.isActive?this.paintFormatStore.cancel():this.paintFormatStore.activate({persistent:!1})}},HJ=class extends t.Component{static template=`o-spreadsheet-TableDropdownButton`;static components={TableStylesPopover:ZU,ActionButton:_V};static props={class:{type:String,optional:!0}};topBarToolStore;state=(0,t.useState)({popoverProps:void 0});setup(){this.topBarToolStore=LJ()}onStylePicked(e){let t=this.env.model.getters.getActiveSheetId(),n={...this.tableConfig,styleId:e};kP(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.topBarToolStore.closeDropdowns(),this.env.toggleSidePanel(`TableSidePanel`,{});return}let{left:t,bottom:n}=e.currentTarget.getBoundingClientRect();this.topBarToolStore.openDropdown(),this.state.popoverProps={anchorRect:{x:t,y:n,width:0,height:0},positioning:`bottom-left`,verticalOffset:0}}closePopover(){this.state.popoverProps=void 0}get action(){return{name:e=>e.model.getters.getFirstTableInSelection()?k(`Edit table`):k(`Insert table`),icon:e=>e.model.getters.getFirstTableInSelection()?`o-spreadsheet-Icon.EDIT_TABLE`:`o-spreadsheet-Icon.PAINT_TABLE`}}get tableConfig(){return{...SA,numberOfHeaders:1,bandedRows:!0}}},UJ=class extends t.Component{static components={ColorPickerWidget:vV};static props={class:String,style:String,icon:String,title:String};static template=`o-spreadsheet-ColorEditor`;topBarToolStore;state=(0,t.useState)({isOpen:!1});setup(){this.topBarToolStore=LJ()}get currentColor(){return this.env.model.getters.getCurrentStyle()[this.props.style]||(this.props.style===`textColor`?`#000000`:`#ffffff`)}setColor(e){jP(this.env,{[this.props.style]:e}),this.state.isOpen=!1}get isMenuOpen(){return this.topBarToolStore.isActive}onClick(){this.isMenuOpen?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}},WJ=class extends t.Component{static template=`o-spreadsheet-DropdownAction`;static components={ActionButton:_V,Popover:Cv};static props={parentAction:Object,childActions:Array,class:String,childClass:String};topBarToolStore;actionRef=(0,t.useRef)(`actionRef`);setup(){this.topBarToolStore=LJ()}toggleDropdown(){this.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}get isActive(){return this.topBarToolStore.isActive}get popoverProps(){return{anchorRect:this.actionRef.el?this.actionRef.el.getBoundingClientRect():{x:0,y:0,width:0,height:0},positioning:`bottom-left`,verticalOffset:0,class:`rounded`}}},GJ=class extends t.Component{static components={FontSizeEditor:bV};static props={class:String};static template=`o-spreadsheet-TopBarFontSizeEditor`;topBarToolStore;setup(){this.topBarToolStore=LJ()}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||Ce}setFontSize(e){jP(this.env,{fontSize:e})}onToggle(){this.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}onFocusInput(){this.topBarToolStore.openDropdown()}get isActive(){return this.topBarToolStore.isActive}},KJ=class extends t.Component{static template=`o-spreadsheet-NumberFormatsTool`;static components={MenuPopover:Dv,ActionButton:_V};static props={class:String};formatNumberMenuItemSpec=Uq;topBarToolStore;buttonRef=(0,t.useRef)(`buttonRef`);state=(0,t.useState)({anchorRect:{x:0,y:0,width:0,height:0},menuItems:[]});setup(){this.topBarToolStore=LJ()}toggleMenu(){if(this.isActive)this.topBarToolStore.closeDropdowns();else{let e=h(this.formatNumberMenuItemSpec);this.state.menuItems=e.children(this.env).sort((e,t)=>e.sequence-t.sequence),this.state.anchorRect=tp(this.buttonRef.el),this.topBarToolStore.openDropdown()}}get isActive(){return this.topBarToolStore.isActive}},qJ=class extends t.Component{static template=`o-spreadsheet-TopBarZoom`;static components={NumberEditor:yV};static props={class:String};topBarToolStore;valueList=ve;setup(){this.topBarToolStore=LJ()}get currentFontSize(){return(this.env.model.getters.getViewportZoomLevel()||1)*100}setZoom(e){this.env.model.dispatch(`SET_ZOOM`,{zoom:e/100})}toggle(){this.topBarToolStore.isActive?this.topBarToolStore.closeDropdowns():this.topBarToolStore.openDropdown()}onFocusInput(){this.topBarToolStore.openDropdown()}};let JJ=new IJ;JJ.add(`edit`).addChild(`edit`,{component:_V,props:{action:dI,class:`o-hoverable-button o-toolbar-button`},sequence:1}).addChild(`edit`,{component:_V,props:{action:fI,class:`o-hoverable-button o-toolbar-button`},sequence:2}).addChild(`edit`,{component:VJ,props:{class:`o-hoverable-button o-toolbar-button o-mobile-disabled`},sequence:3}).addChild(`edit`,{component:_V,props:{action:Oz,class:`o-hoverable-button o-toolbar-button`},sequence:4}).addChild(`edit`,{component:qJ,props:{class:`o-menu-item-button o-hoverable-button o-toolbar-button`},sequence:5}).add(`numberFormat`).addChild(`numberFormat`,{component:_V,props:{action:RR,class:`o-hoverable-button o-toolbar-button`},sequence:1}).addChild(`numberFormat`,{component:_V,props:{action:$R,class:`o-hoverable-button o-toolbar-button`},sequence:2}).addChild(`numberFormat`,{component:_V,props:{action:QR,class:`o-hoverable-button o-toolbar-button`},sequence:3}).addChild(`numberFormat`,{component:KJ,props:{class:`o-menu-item-button o-hoverable-button o-toolbar-button`},sequence:4}).add(`fontSize`).addChild(`fontSize`,{component:GJ,props:{class:`o-hoverable-button o-toolbar-button`},sequence:3}).add(`textStyle`).addChild(`textStyle`,{component:_V,props:{action:ez,class:`o-hoverable-button o-toolbar-button`},sequence:1}).addChild(`textStyle`,{component:_V,props:{action:tz,class:`o-hoverable-button o-toolbar-button`},sequence:2}).addChild(`textStyle`,{component:_V,props:{action:dz,class:`o-hoverable-button o-toolbar-button`},sequence:3}).addChild(`textStyle`,{component:UJ,props:{class:`o-hoverable-button o-menu-item-button o-toolbar-button`,style:`textColor`,icon:`o-spreadsheet-Icon.TEXT_COLOR`,title:k(`Text Color`)},sequence:4}).add(`cellStyle`).addChild(`cellStyle`,{component:UJ,props:{class:`o-hoverable-button o-menu-item-button o-toolbar-button`,style:`fillColor`,icon:`o-spreadsheet-Icon.FILL_COLOR`,title:k(`Fill Color`)},sequence:1}).addChild(`cellStyle`,{component:BJ,props:{class:`o-hoverable-button o-menu-item-button o-toolbar-button`},sequence:2}).addChild(`cellStyle`,{component:_V,props:{action:AI,class:`o-hoverable-button o-menu-item-button o-toolbar-button`},sequence:3}).add(`alignment`).addChild(`alignment`,{component:WJ,props:{parentAction:mz,childActions:[hz,gz,_z],class:`o-hoverable-button o-toolbar-button`,childClass:`o-hoverable-button`},sequence:1}).addChild(`alignment`,{component:WJ,props:{parentAction:vz,childActions:[yz,bz,xz],class:`o-hoverable-button o-menu-item-button o-toolbar-button`,childClass:`o-hoverable-button`},sequence:2}).addChild(`alignment`,{component:WJ,props:{parentAction:Cz,childActions:[wz,Tz,Ez],class:`o-hoverable-button o-menu-item-button o-toolbar-button`,childClass:`o-hoverable-button`},sequence:3}).addChild(`alignment`,{component:WJ,props:{parentAction:rz,childActions:[oz,sz,cz,lz,uz],class:`o-hoverable-button o-menu-item-button o-toolbar-button`,childClass:`o-hoverable-button`},sequence:4}).add(`misc`).addChild(`misc`,{component:HJ,props:{class:`o-toolbar-button o-hoverable-button o-menu-item-button o-mobile-disabled`},sequence:1}).addChild(`misc`,{component:_V,props:{action:AR,class:`o-hoverable-button o-menu-item-button o-toolbar-button`},sequence:2});var YJ=class extends t.Component{static template=`o-spreadsheet-TopBar`;static props={onClick:Function,dropdownMaxHeight:Number};static components={MenuPopover:Dv,TopBarComposer:PJ,Popover:Cv};toolsCategories=JJ.getCategories();state=(0,t.useState)({menuState:{isOpen:!1,anchorRect:null,menuItems:[]},invisibleToolsCategories:[],toolsPopoverState:{isOpen:!1}});isSelectingMenu=!1;openedEl=null;menus=[];toolbarMenuRegistry=JJ;formatNumberMenuItemSpec=Uq;isntToolbarMenu=!1;composerFocusStore;fingerprints;topBarToolStore;toolBarContainerRef=(0,t.useRef)(`toolBarContainer`);toolbarRef=(0,t.useRef)(`toolBar`);moreToolsContainerRef=(0,t.useRef)(`moreToolsContainer`);moreToolsButtonRef=(0,t.useRef)(`moreToolsButton`);spreadsheetRect=xv();setup(){this.composerFocusStore=D(_r),this.fingerprints=D(xF),this.topBarToolStore=D(FJ),(0,t.useExternalListener)(window,`click`,this.onExternalClick),(0,t.onWillStart)(()=>this.updateCellState()),(0,t.onWillUpdateProps)(()=>this.updateCellState()),(0,t.useEffect)(()=>{this.state.toolsPopoverState.isOpen=!1,this.setVisibilityToolsGroups()},()=>[this.spreadsheetRect.width])}setVisibilityToolsGroups(){if(this.env.model.getters.isReadonly())return;let e=[],{x:t}=this.toolbarRef.el.getBoundingClientRect(),{x:n}=this.toolBarContainerRef.el.getBoundingClientRect();this.moreToolsContainerRef.el?.classList.remove(`d-none`);let r=this.moreToolsButtonRef.el?.getBoundingClientRect().width||0,i=Math.round(this.spreadsheetRect.width)-r-(t-n)-16,a=document.querySelectorAll(`.tool-container`),o=0;for(let t=0;t<a.length;t++){let n=a[t];n.classList.remove(`d-none`);let{width:r}=n.getBoundingClientRect();o+=r,o>i&&(n.classList.add(`d-none`),e.push(this.toolsCategories[t]))}this.state.invisibleToolsCategories=e,e.length||this.moreToolsContainerRef.el?.classList.add(`d-none`)}get topbarComponents(){return dJ.getAllOrdered().filter(e=>!e.isVisible||e.isVisible(this.env))}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||Ce}onExternalClick(e){this.openedEl!==e.target&&this.closeMenus()}onClick(){this.props.onClick(),this.closeMenus()}onMenuMouseOver(e,t){this.isSelectingMenu&&this.isntToolbarMenu&&this.openMenu(e,t)}toggleContextMenu(e,t){this.state.menuState.isOpen&&this.isntToolbarMenu?this.closeMenus():(this.openMenu(e,t),this.isntToolbarMenu=!0)}openMenu(e,t){this.topBarToolStore.currentDropdown&&this.topBarToolStore.closeDropdowns(),this.state.toolsPopoverState.isOpen=!1,this.state.menuState.isOpen=!0,this.state.menuState.anchorRect=tp(t.currentTarget),this.state.menuState.menuItems=e.children(this.env).sort((e,t)=>e.sequence-t.sequence),this.state.menuState.parentMenu=e,this.isSelectingMenu=!0,this.openedEl=t.target,this.composerFocusStore.activeComposer.stopEdition()}closeMenus(){this.topBarToolStore.currentDropdown&&this.topBarToolStore.closeDropdowns(),this.state.toolsPopoverState.isOpen=!1,this.state.menuState.isOpen=!1,this.state.menuState.parentMenu=void 0,this.isSelectingMenu=!1,this.openedEl=null}updateCellState(){this.menus=Gq.getMenuItems()}getMenuName(e){return e.name(this.env)}setColor(e,t){jP(this.env,{[e]:t}),this.onClick()}setFontSize(e){jP(this.env,{fontSize:e})}toggleMoreTools(){this.topBarToolStore.currentDropdown&&this.topBarToolStore.closeDropdowns(),this.state.toolsPopoverState.isOpen=!this.state.toolsPopoverState.isOpen}get toolsPopoverProps(){return{anchorRect:this.moreToolsButtonRef.el?tp(this.moreToolsButtonRef.el):{x:0,y:0,width:0,height:0},positioning:`bottom-left`,verticalOffset:0,class:`rounded`,maxWidth:300}}showDivider(e){return e<this.toolsCategories.length-1||this.state.invisibleToolsCategories.length>0}};function XJ(){return new ZJ(navigator.clipboard)}var ZJ=class{clipboard;constructor(e){this.clipboard=e}async write(e){if(this.clipboard?.write)try{await this.clipboard?.write(this.getClipboardItems(e))}catch(t){console.log(`Failed to write on the clipboard, falling back to plain/html text. Error %s`,t);try{await this.clipboard?.write([new ClipboardItem({"text/plain":this.getBlob(e,`text/plain`),"text/html":this.getBlob(e,`text/html`)})])}catch{}}else await this.writeText(e[`text/plain`]??``)}async writeText(e){try{this.clipboard?.writeText(e)}catch{}}async read(){let e;try{e=await navigator.permissions.query({name:`clipboard-read`})}catch{}if(this.clipboard?.read)try{let e=await this.clipboard.read(),t={};for(let n of e)for(let e of n.types){let r=await n.getType(e);eA.includes(e)?t[e]=r:t[e]=await r.text()}return{status:`ok`,content:t}}catch{return{status:e?.state===`denied`?`permissionDenied`:`notImplemented`}}else return{status:`ok`,content:{"text/plain":await this.clipboard?.readText()}}}getClipboardItems(e){let t={};for(let n of Object.keys(e))t[n]=this.getBlob(e,n);return[new ClipboardItem(t)]}getBlob(e,t){let n=e[t];return n instanceof Blob||n instanceof File?n:new Blob([e[t]||``],{type:t})}},QJ=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},colorScheme:{type:String,optional:!0}};static components={TopBar:YJ,Grid:sW,BottomBar:SJ,SmallBottomBar:NJ,SidePanels:jJ,SpreadsheetDashboard:wJ,HeaderGroupContainer:OJ,FullScreenFigure:uW};sidePanel;spreadsheetRef=(0,t.useRef)(`spreadsheet`);spreadsheetRect=xv();_focusGrid;isViewportTooSmall=!1;notificationStore;composerFocusStore;get model(){return this.props.model}getStyle(){let e={},t=this.env.model.getters.getScrollBarWidth();return this.env.isDashboard()?e[`grid-template-rows`]=`auto`:e[`grid-template-rows`]=`min-content auto min-content`,e[`grid-template-columns`]=`auto ${this.sidePanel.mainPanel?`${this.sidePanel.totalPanelSize||350}px`:`auto`}`,e[`--os-scrollbar-width`]=`${t}px`,e[`color-scheme`]=this.props.colorScheme,U(e)}setup(){if(!(`isSmall`in this.env)){let e=kJ();(0,t.useSubEnv)({get isSmall(){return e.isSmall}})}let e=ar();e.inject(ur,this.model);let n=this.env;e.get(rW).setSmallThreshhold(()=>n.isSmall),this.notificationStore=D(ck),this.composerFocusStore=D(_r),this.sidePanel=D(iW);let r=this.model.config.external.fileStore;(0,t.useSubEnv)({model:this.model,imageProvider:r?new pJ(r):void 0,loadCurrencies:this.model.config.external.loadCurrencies,loadLocales:this.model.config.external.loadLocales,isDashboard:()=>this.model.getters.isDashboard(),openSidePanel:this.sidePanel.open.bind(this.sidePanel),replaceSidePanel:this.sidePanel.replace.bind(this.sidePanel),toggleSidePanel:this.sidePanel.toggle.bind(this.sidePanel),clipboard:this.env.clipboard||XJ(),startCellEdition:e=>this.composerFocusStore.focusActiveComposer({content:e}),notifyUser:e=>this.notificationStore.notifyUser(e),askConfirmation:(e,t,n)=>this.notificationStore.askConfirmation(e,t,n),raiseError:(e,t)=>this.notificationStore.raiseError(e,t),isMobile:vp}),this.notificationStore.updateNotificationCallbacks({...this.props}),(0,t.useEffect)(()=>{!this.spreadsheetRef.el.contains(document.activeElement)&&document.activeElement?.contains(this.spreadsheetRef.el)&&this.focusGrid()}),(0,t.useExternalListener)(window,`resize`,()=>this.render(!0)),(0,t.useExternalListener)(document.body,`wheel`,()=>{}),this.bindModelEvents(),(0,t.onWillUpdateProps)(e=>{if(e.model!==this.props.model)throw Error(`Changing the props model is not supported at the moment.`);(e.notifyUser!==this.props.notifyUser||e.askConfirmation!==this.props.askConfirmation||e.raiseError!==this.props.raiseError)&&this.notificationStore.updateNotificationCallbacks({...e})});let i=ft(this.render.bind(this,!0));(0,t.onMounted)(()=>{this.checkViewportSize(),e.on(`store-updated`,this,i),a.observe(this.spreadsheetRef.el)}),(0,t.onWillUnmount)(()=>{this.unbindModelEvents(),e.off(`store-updated`,this),a.disconnect(),Xl()}),(0,t.onPatched)(()=>{this.checkViewportSize()});let a=new ResizeObserver(()=>{this.sidePanel.changeSpreadsheetWidth(this.spreadsheetRect.width)})}bindModelEvents(){this.model.on(`update`,this,()=>this.render(!0)),this.model.on(`notify-ui`,this,e=>this.notificationStore.notifyUser(e)),this.model.on(`raise-error-ui`,this,({text:e})=>this.notificationStore.raiseError(e))}unbindModelEvents(){this.model.off(`update`,this),this.model.off(`notify-ui`,this),this.model.off(`raise-error-ui`,this)}checkViewportSize(){let{xRatio:e,yRatio:t}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());if(!(!isFinite(e)||!isFinite(t)))if(t>.85||e>.85){if(this.isViewportTooSmall)return;this.notificationStore.notifyUser({text:k(`The current window is too small to display this sheet properly. Consider resizing your browser window or adjusting frozen rows and columns.`),type:`warning`,sticky:!1}),this.isViewportTooSmall=!0}else this.isViewportTooSmall=!1}focusGrid(){this._focusGrid&&this._focusGrid()}get gridHeight(){return this.env.model.getters.getSheetViewDimension().height}get gridContainerStyle(){let e=21*this.rowLayers.length,t=21*this.colLayers.length,n=this.env.model.getters.getViewportZoomLevel();return U({"grid-template-columns":`${e?e+2:0}px auto`,"grid-template-rows":`${t?t+2:0}px auto`,zoom:`${n}`})}get rowLayers(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,`ROW`)}get colLayers(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,`COL`)}getGridSize(){let e=this.spreadsheetRef.el;if(!e)return{width:0,height:0};let t=this.env.model.getters.getViewportZoomLevel(),n=this.env.model.getters.getScrollBarWidth(),r=n=>e.querySelector(n)&&$f(e.querySelector(n),t).height||0,i=n=>e.querySelector(n)&&$f(e.querySelector(n),t).width||0,a=e.getBoundingClientRect(),o=r(`.o-spreadsheet-topbar-wrapper`),s=r(`.o-spreadsheet-bottombar-wrapper`),c=r(`.o-column-groups`),l=i(`.o-grid`),u=a.height-c-o-s;return{width:Math.max(l/t-n,0),height:Math.max(u/t-n,0)}}getSpreadSheetClasses(){return[this.env.isSmall?`o-spreadsheet-mobile`:``,this.props.colorScheme===`dark`?`dark`:``].join(` `)}},$J=class{transportService;constructor(e){this.transportService=e}async sendMessage(e){(e.type===`CLIENT_JOINED`||e.type===`CLIENT_LEFT`||e.type===`CLIENT_MOVED`)&&await this.transportService.sendMessage(e)}onNewMessage(e,t){this.transportService.onNewMessage(e,t)}leave(e){this.transportService.leave(e)}};function eY(e){return wq.get(e.type)(e)}var tY=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)}}},nY=class{id;data;constructor(e,t){this.id=e,this.data=t}transformed(e){return new rY(this.id,mt(()=>e(this.data)))}},rY=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))}},iY=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))}},aY=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 iY(Qe(this._execution(e),this._execution(e)))}revertedExecution(e){return new iY(Qe(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):[]}}},oY=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 tY(this.buildTransformation),this.tree=new aY(this.buildTransformation,this.HEAD_BRANCH);let t=e.initialOperationId,n=new nY(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 nY(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 nY(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 sY(e){return new oY({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=>cY([e]),buildEmpty:e=>new jK(e,`empty`,[]),buildTransformation:{with:e=>t=>new jK(t.id,t.clientId,xK(t.commands,e.commands),t.rootCommand,void 0,t.timestamp),without:e=>t=>new jK(t.id,t.clientId,xK(t.commands,e.commands.map(eY).flat()),t.rootCommand,void 0,t.timestamp)}})}function cY(e){for(let t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){let n=t.changes[e];lY(n)}}function lY(e){let t=e.target,n=e.key,r=e.before;r===void 0?delete t[n]:t[n]=r}var uY=class{getters;providers=[];isAdaptingRanges=!1;constructor(e){this.getters=e}static getters=[`copyFormulaStringForSheet`,`extendRange`,`getRangeString`,`getRangeFromSheetXC`,`createAdaptedRanges`,`getRangeData`,`getRangeDataFromXc`,`getRangeDataFromZone`,`getRangeFromRangeData`,`getRangeFromZone`,`getRangesUnion`,`recomputeRanges`,`isRangeValid`,`removeRangesSheetPrefix`];allowDispatch(e){return e.type===`MOVE_RANGES`?e.target.length===1?`Success`:`InvalidZones`:`Success`}beforeHandle(e){}handle(e){if(this.isAdaptingRanges)throw Error(`Plugins cannot dispatch commands during adaptRanges phase`);let t=nl(e);t&&this.executeOnAllRanges(t)}finalize(){}verifyRangeRemoved(e){return t=>{let n=e(t);return n.changeType!==`NONE`&&!pn(n.range.zone)?{range:n.range,changeType:`REMOVE`}:n}}executeOnAllRanges(e){this.isAdaptingRanges=!0;let t={applyChange:this.verifyRangeRemoved(e.applyChange),adaptRangeString:(t,n)=>Gu(t,n,e),adaptFormulaString:(t,n)=>Wu(t,n,e)};for(let n of this.providers)n(t,e.sheetId,e.sheetName);this.isAdaptingRanges=!1}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,n,r){return e.map(e=>{if(!pn(e.zone))return e;let i=e.prefixSheet?e.sheetId:r,a=Jc(e),o=qc(e),s={...e.unboundedZone,left:a&&!e.unboundedZone.hasHeader?e.unboundedZone.left:e.unboundedZone.left+(e.parts[0].colFixed?0:t),right:a?e.unboundedZone.right:e.unboundedZone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:o&&!e.unboundedZone.hasHeader?e.unboundedZone.top:e.unboundedZone.top+(e.parts[0].rowFixed?0:n),bottom:o?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:n)};return tl(Wc({...e,sheetId:i,zone:s},this.getters.getSheetSize))})}removeRangesSheetPrefix(e,t){return t.map(t=>t.prefixSheet&&t.sheetId===e?{...t,prefixSheet:!1}:t)}extendRange(e,t,n){let r=t===`COL`?e.zone.right+n:e.zone.right,i=t===`ROW`?e.zone.bottom+n:e.zone.bottom,a={left:e.zone.left,top:e.zone.top,right:Jc(e)?void 0:r,bottom:qc(e)?void 0:i};return Wc({...e,zone:a},this.getters.getSheetSize)}getRangeFromSheetXC(e,t){if(!Oc.test(t)||!this.getters.tryGetSheet(e))return Kc(t);let{sheetName:n}=Pc(t);return Gc({xc:t,sheetId:this.getters.getSheetIdByName(n)||e,invalidSheetName:n&&!this.getters.getSheetIdByName(n)?n:void 0},this.getters.getSheetSize)}getRangeString(e,t,n={useBoundedReference:!1,useFixedReference:!1}){return e?e.invalidXc?e.invalidXc:this.getters.tryGetSheet(e.sheetId)?Yc(e,t,this.getters.getSheetName,n):A.InvalidReference:A.InvalidReference}getRangeDataFromXc(e,t){let n=this.getters.getRangeFromSheetXC(e,t);return this.getRangeDataFromZone(n.sheetId,n.unboundedZone)}getRangeDataFromZone(e,t){return t=this.getters.getUnboundedZone(e,t),{_sheetId:e,_zone:t}}getRangeData(e){return this.getRangeDataFromZone(e.sheetId,e.unboundedZone)}getRangeFromZone(e,t){return Wc({sheetId:e,zone:t,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}],prefixSheet:!1},this.getters.getSheetSize)}recomputeRanges(e,t){return Qt(e.map(e=>e.unboundedZone),t.map(e=>e.unboundedZone)).map(t=>this.getRangeFromZone(e[0].sheetId,t))}getRangeFromRangeData(e){return this.getters.tryGetSheet(e._sheetId)?Wc({prefixSheet:!1,zone:e._zone,sheetId:e._sheetId,invalidSheetName:void 0,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}]},this.getters.getSheetSize):Kc(A.InvalidReference)}isRangeValid(e){if(!e)return!1;let{xc:t,sheetName:n}=Pc(e);return t.match(Oc)!==null&&(!n||this.getters.getSheetIdByName(n)!==void 0)}getRangesUnion(e){let t=xn(...e.map(e=>e.unboundedZone));return this.getRangeFromZone(e[0].sheetId,t)}copyFormulaStringForSheet(e,t,n,r){if(!n.startsWith(`=`))return n;let i=lU(n),a=i.dependencies.map(n=>{let i=this.getters.getRangeFromSheetXC(e,n);return r===`keepSameReference`?i:Xc(e,t,i)});return this.getters.getFormulaString(t,i.tokens,a)}},dY=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})}unobserve(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))}},fY=class{getters;stream;anchor;defaultAnchor;constructor(e){this.getters=e,this.stream=new dY,this.anchor={cell:{col:0,row:0},zone:E({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)}unobserve(e){this.stream.unobserve(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=E({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 Ws(`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=this.getters.expandZone(n,a);if(Cn(this.anchor.zone,o))return new Ws(`NoChanges`);let s={zone:o,cell:{col:r,row:i}};return this.processEvent({mode:`updateAnchor`,anchor:s,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,E({col:e,row:t}));return this.processEvent({options:{scrollIntoView:!0},anchor:{zone:r,cell:{col:e,row:t}},mode:`newAnchor`})}commitSelection(){return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:this.anchor,mode:`commitSelection`})}resizeAnchorZone(e,t=1){if(t!==`end`&&t<=0)return new Ws(`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 Ws.Success;let p=r.zone,m=e=>{e=Nn(e);let{left:t,right:r,top:i,bottom:a}=this.getters.expandZone(n,e);return{left:Math.max(0,t),right:Math.min(this.getters.getNumberCols(n)-1,r),top:Math.max(0,i),bottom:Math.min(this.getters.getNumberRows(n)-1,a)}},{cell:h,zone:g}=this.getReferenceAnchor(),{col:_,row:v}=h,y=0;for(;p!==null;){if(y++,d<0){let e=this.getNextAvailableCol(d,s-(y-1),v);p=g.right<=s-y?m({top:c,left:o,bottom:l,right:e}):null}if(d>0){let e=this.getNextAvailableCol(d,o+(y-1),v);p=o+y<=g.left?m({top:c,left:e,bottom:l,right:s}):null}if(f<0){let e=this.getNextAvailableRow(f,_,l-(y-1));p=g.bottom<=l-y?m({top:c,left:o,bottom:e,right:s}):null}if(f>0){let e=this.getNextAvailableRow(f,_,c+(y-1));p=c+y<=g.top?m({top:e,left:o,bottom:l,right:s}):null}if(p&&=Nn(p),p&&!Cn(p,r.zone))return this.processEvent({options:{scrollIntoView:!0},mode:`updateAnchor`,anchor:{zone:p,cell:{col:i,row:a}}})}p=m(bn({top:a,bottom:a,left:i,right:i},Nn({top:this.getNextAvailableRow(f,_,c),left:this.getNextAvailableCol(d,o,v),bottom:this.getNextAvailableRow(f,_,l),right:this.getNextAvailableCol(d,s,v)})));let ee={zone:p,cell:{col:i,row:a}};return this.processEvent({anchor:ee,mode:`updateAnchor`,options:{scrollIntoView:!0}})}selectColumn(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.getNumberRows(n)-1,i={left:e,right:e,top:0,bottom:r},a=this.getters.findFirstVisibleColRowIndex(n,`ROW`),o,s;switch(t){case`overrideSelection`:case`newAnchor`:o=e,s=a;break;case`updateAnchor`:({col:o,row:s}=this.anchor.cell),i=bn(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=bn(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(Cn(this.anchor.zone,this.getters.getSheetZone(e)))return this.modifyAnchor({...t,zone:E(t.cell)},`updateAnchor`,{scrollIntoView:!1});let n=this.getters.getContiguousZone(e,t.zone);return w(n,t.zone)?this.selectAll():this.modifyAnchor({...t,zone:n},`updateAnchor`,{scrollIntoView:!1})}selectTableAroundSelection(){let e=this.getters.getActiveSheetId(),t=this.getters.getContiguousZone(e,this.anchor.zone);return this.modifyAnchor({...this.anchor,zone:t},`updateAnchor`,{scrollIntoView:!1})}selectAll(){let e=this.getters.getActiveSheetId(),t={left:0,top:0,bottom:this.getters.getNumberRows(e)-1,right:this.getters.getNumberCols(e)-1};return this.processEvent({mode:`overrideSelection`,anchor:{zone:t,cell:this.anchor.cell},options:{scrollIntoView:!1}})}isListening(e){return this.stream.isListening(e)}processEvent(e){let t={...e,previousAnchor:b(this.anchor)},n=this.checkEventAnchorZone(t);return n===`Success`?(this.anchor=t.anchor,this.stream.send(t),Ws.Success):new Ws(n)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){let{cell:t,zone:n}=e;if(!En(t.col,t.row,n))return`InvalidAnchorZone`;let{left:r,right:i,top:a,bottom:o}=n,s=this.getters.getActiveSheetId(),c=this.getters.findVisibleHeader(s,`COL`,r,i);return this.getters.findVisibleHeader(s,`ROW`,a,o)===void 0||c===void 0?`SelectionOutOfBound`:`Success`}checkAnchorZoneOrThrow(e){if(this.checkAnchorZone(e)===`InvalidAnchorZone`)throw Error(`The provided anchor is invalid. The cell must be part of the zone.`)}getNextAvailablePosition(e,t=1){let{col:n,row:r}=this.anchor.cell,i=this.deltaToTarget({col:n,row:r},e,t);return{col:this.getNextAvailableCol(i[0],n,r),row:this.getNextAvailableRow(i[1],n,r)}}getNextAvailableCol(e,t,n){let r=this.getters.getActiveSheetId(),i={col:t,row:n};return this.getNextAvailableHeader(e,`COL`,t,i,e=>this.getters.isInSameMerge(r,t,n,e,n))}getNextAvailableRow(e,t,n){let r=this.getters.getActiveSheetId(),i={col:t,row:n};return this.getNextAvailableHeader(e,`ROW`,n,i,e=>this.getters.isInSameMerge(r,t,n,t,e))}getNextAvailableHeader(e,t,n,r,i){let a=this.getters.getActiveSheetId();if(e===0)return n;let o=Math.sign(e),s=n+e;for(;i(s);)s+=o;for(;this.getters.isHeaderHidden(a,t,s);)s+=o;return s<0||s>this.getters.getNumberHeaders(a,t)-1?this.getters.isHeaderHidden(a,t,n)?this.getNextAvailableHeader(-o,t,n,r,i):n:s}getReferenceAnchor(){let e=this.getters.getActiveSheetId(),t=this.anchor,{left:n,right:r,top:i,bottom:a}=t.zone,{col:o,row:s}=t.cell,c=this.getters.isColHidden(e,o)&&this.getters.findVisibleHeader(e,`COL`,n,r)||o,l=this.getters.isRowHidden(e,s)&&this.getters.findVisibleHeader(e,`ROW`,i,a)||s,u=this.getters.expandZone(e,{left:c,right:c,top:l,bottom:l});return{cell:{col:c,row:l},zone:u}}deltaToTarget(e,t,n){switch(t){case`up`:return n===`end`?[0,this.getEndOfCluster(e,`rows`,-1)-e.row]:[0,-n];case`down`:return n===`end`?[0,this.getEndOfCluster(e,`rows`,1)-e.row]:[0,n];case`left`:return n===`end`?[this.getEndOfCluster(e,`cols`,-1)-e.col,0]:[-n,0];case`right`:return n===`end`?[this.getEndOfCluster(e,`cols`,1)-e.col,0]:[n,0]}}getStartingPosition(e){let{col:t,row:n}=this.getPosition(),r=this.anchor.zone;switch(e){case`down`:case`up`:n=n===r.top?r.bottom:r.top;break;case`left`:case`right`:t=t===r.right?r.left:r.right;break}return{col:t,row:n}}getEndOfCluster(e,t,n){let r=this.getters.getActiveSheetId(),i=e,a=this.getNextCellPosition(e,t,n),o=!this.isCellSkippableInCluster({...i,sheetId:r})&&!this.isCellSkippableInCluster({...a,sheetId:r})?`endOfCluster`:`nextCluster`;for(;;){let e=this.getNextCellPosition(i,t,n);if(i.col===e.col&&i.row===e.row)break;let a=this.isCellSkippableInCluster({...e,sheetId:r});if(o===`endOfCluster`&&a)break;if(o===`nextCluster`&&!a){i=e;break}i=e}return t===`cols`?i.col:i.row}getNextCellPosition(e,t,n){let r=t===`cols`?`col`:`row`,i={...e};return i[r]=t===`cols`?this.getNextAvailableCol(n,i.col,i.row):this.getNextAvailableRow(n,i.col,i.row),{col:i.col,row:i.row}}getPosition(){return{...this.anchor.cell}}isCellSkippableInCluster(e){let t=this.getters.getMainCellPosition(e),n=this.getters.getEvaluatedCell(t);return n.type===`empty`||n.type===`text`&&n.value===``}},pY=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]=bl(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 mY=17781237,hY=17781238,gY=88853993,_Y=88853994;function vY(e,t,n){let r=[[`xmlns:r`,du],[`xmlns:a`,su],[`xmlns:c`,cu]],i=yY({backgroundColor:e.data.backgroundColor,line:{color:`000000`}}),a=$``;if(e.data.title?.text){let t=V(sd(e.data.backgroundColor)),n=e.data.title.fontSize??16;a=$`
|
|
124
124
|
<c:title>
|
|
125
|
-
${
|
|
125
|
+
${SY(e.data.title.text,t,n,e.data.title)}
|
|
126
126
|
<c:overlay val="0" />
|
|
127
127
|
</c:title>
|
|
128
|
-
`}let o=$``;switch(e.data.type){case`bar`:o=
|
|
128
|
+
`}let o=$``;switch(e.data.type){case`bar`:o=OY(e.data);break;case`combo`:o=kY(e.data);break;case`pyramid`:o=AY(e.data);break;case`line`:o=MY(e.data);break;case`scatter`:o=NY(e.data);break;case`pie`:o=FY(e.data,t,n);break;case`radar`:o=PY(e.data)}let s=`none`;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 DN($`
|
|
129
129
|
<c:chartSpace ${Z(r)}>
|
|
130
130
|
<c:roundedCorners val="0" />
|
|
131
131
|
<!-- <manualLayout/> to manually position the chart in the figure container -->
|
|
@@ -137,26 +137,26 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
137
137
|
<!-- how the chart element is placed on the chart -->
|
|
138
138
|
<c:layout />
|
|
139
139
|
${o}
|
|
140
|
-
${
|
|
140
|
+
${yY({backgroundColor:e.data.backgroundColor})}
|
|
141
141
|
</c:plotArea>
|
|
142
|
-
${s===`none`?``:
|
|
142
|
+
${s===`none`?``:RY(s,c)}
|
|
143
143
|
</c:chart>
|
|
144
144
|
</c:chartSpace>
|
|
145
|
-
`)}function
|
|
145
|
+
`)}function yY(e){return $`
|
|
146
146
|
<c:spPr>
|
|
147
|
-
${e.backgroundColor?
|
|
148
|
-
${e.line?
|
|
147
|
+
${e.backgroundColor?bY(e.backgroundColor):``}
|
|
148
|
+
${e.line?xY(e.line):``}
|
|
149
149
|
</c:spPr>
|
|
150
|
-
`}function
|
|
150
|
+
`}function bY(e){return $`
|
|
151
151
|
<a:solidFill>
|
|
152
152
|
<a:srgbClr val="${e}"/>
|
|
153
153
|
</a:solidFill>
|
|
154
|
-
`}function
|
|
154
|
+
`}function xY(e){let t=[[`cmpd`,`sng`]];e.width&&t.push([`w`,dM(e.width)]);let n=e.style?$`<a:prstDash val="${e.style}"/>`:``;return $`
|
|
155
155
|
<a:ln ${Z(t)}>
|
|
156
|
-
${
|
|
156
|
+
${bY(e.color)}
|
|
157
157
|
${n}
|
|
158
158
|
</a:ln>
|
|
159
|
-
`}function
|
|
159
|
+
`}function SY(e,t=`000000`,n=16,r={}){return $`
|
|
160
160
|
<c:tx>
|
|
161
161
|
<c:rich>
|
|
162
162
|
<a:bodyPr />
|
|
@@ -164,7 +164,7 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
164
164
|
<a:p>
|
|
165
165
|
<a:pPr lvl="0">
|
|
166
166
|
<a:defRPr b="${+!!r?.bold}" i="${+!!r?.italic}">
|
|
167
|
-
${
|
|
167
|
+
${bY(t)}
|
|
168
168
|
<a:latin typeface="+mn-lt"/>
|
|
169
169
|
</a:defRPr>
|
|
170
170
|
</a:pPr>
|
|
@@ -175,29 +175,29 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
175
175
|
</a:p>
|
|
176
176
|
</c:rich>
|
|
177
177
|
</c:tx>
|
|
178
|
-
`}function
|
|
178
|
+
`}function CY(e=12,t=`000000`,n=!1,r=!1){return $`
|
|
179
179
|
<c:txPr>
|
|
180
180
|
<a:bodyPr/>
|
|
181
181
|
<a:lstStyle/>
|
|
182
182
|
<a:p>
|
|
183
183
|
<a:pPr lvl="0">
|
|
184
184
|
<a:defRPr ${Z([[`b`,n?`1`:`0`],[`i`,r?`1`:`0`],[`sz`,e*100]])}>
|
|
185
|
-
${
|
|
185
|
+
${bY(t)}
|
|
186
186
|
<a:latin typeface="+mn-lt"/>
|
|
187
187
|
</a:defRPr>
|
|
188
188
|
</a:pPr>
|
|
189
189
|
</a:p>
|
|
190
190
|
</c:txPr>
|
|
191
|
-
`}function
|
|
191
|
+
`}function wY(e,t){if(!e)return $``;let{type:n,order:r,window:i}=e,a=[];switch(n){case`poly`:r&&r>1?(a.push($`<c:trendlineType val="poly" />`),a.push($`<c:order val="${r}" />`)):a.push($`<c:trendlineType val="linear" />`);break;case`movingAvg`:a.push($`<c:trendlineType val="movingAvg" />`),i&&a.push($`<c:period val="${i}" />`);break;default:a.push($`<c:trendlineType val="${n}" />`);break}return $`
|
|
192
192
|
<c:trendline>
|
|
193
|
-
${
|
|
193
|
+
${TY(e,t)}
|
|
194
194
|
${Q(a)}
|
|
195
195
|
</c:trendline>
|
|
196
|
-
`}function
|
|
196
|
+
`}function TY(e,t){return e?$`
|
|
197
197
|
<c:spPr>
|
|
198
198
|
<a:ln w="19050" cap="rnd">
|
|
199
199
|
<a:solidFill>
|
|
200
|
-
<a:srgbClr ${Z([[`val`,e.color?V(e.color).slice(-6):
|
|
200
|
+
<a:srgbClr ${Z([[`val`,e.color?V(e.color).slice(-6):EY(t)]])}/>
|
|
201
201
|
</a:solidFill>
|
|
202
202
|
<a:prstDash val="sysDot" />
|
|
203
203
|
</a:ln>
|
|
@@ -205,22 +205,22 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
205
205
|
</c:spPr>
|
|
206
206
|
<c:dispRSqr val="0" />
|
|
207
207
|
<c:dispEq val="0" />
|
|
208
|
-
`:$``}function
|
|
208
|
+
`:$``}function EY(e){return V(Vr(e,.5))}function DY(e){return e?`text`in e&&e.text?$`
|
|
209
209
|
<c:tx><c:v>${e.text}</c:v></c:tx>
|
|
210
210
|
`:`reference`in e&&e.reference?$`
|
|
211
211
|
<c:tx>
|
|
212
|
-
${
|
|
212
|
+
${BY(e.reference)}
|
|
213
213
|
</c:tx>
|
|
214
|
-
`:$``:$``}function
|
|
214
|
+
`:$``:$``}function OY(e){let t=e.horizontal?`bar`:`col`,n=e.dataSets.map(e=>e.backgroundColor??``),r=new ei(e.dataSets.length,n),i=[],a=[];for(let[t,n]of Object.entries(e.dataSets)){let o=V(r.next()),s=yY({backgroundColor:o,line:{color:o}}),c=$`
|
|
215
215
|
<c:ser>
|
|
216
216
|
<c:idx val="${t}"/>
|
|
217
217
|
<c:order val="${t}"/>
|
|
218
|
-
${
|
|
219
|
-
${
|
|
218
|
+
${wY(n.trend,o)}
|
|
219
|
+
${DY(n.label)}
|
|
220
220
|
${s}
|
|
221
|
-
${e.labelRange?$`<c:cat>${
|
|
221
|
+
${e.labelRange?$`<c:cat>${BY(e.labelRange)}</c:cat>`:``} <!-- x-coordinate values -->
|
|
222
222
|
<c:val> <!-- x-coordinate values -->
|
|
223
|
-
${
|
|
223
|
+
${VY(n.range)}
|
|
224
224
|
</c:val>
|
|
225
225
|
</c:ser>
|
|
226
226
|
`;n.rightYAxis?a.push(c):i.push(c)}let o=e.stacked?`stacked`:`clustered`,s=e.stacked?100:-20;return $`
|
|
@@ -233,11 +233,11 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
233
233
|
<!-- each data marker in the series does not have a different color -->
|
|
234
234
|
<c:varyColors val="0"/>
|
|
235
235
|
${Q(i)}
|
|
236
|
-
<c:axId val="${
|
|
237
|
-
<c:axId val="${
|
|
236
|
+
<c:axId val="${mY}" />
|
|
237
|
+
<c:axId val="${gY}" />
|
|
238
238
|
</c:barChart>
|
|
239
|
-
${t===`col`?
|
|
240
|
-
${t===`col`?
|
|
239
|
+
${t===`col`?LY(`b`,`c:catAx`,mY,gY,e.axesDesign?.x?.title,e.fontColor):LY(`b`,`c:catAx`,mY,gY,e.axesDesign?.y?.title,e.fontColor,void 0,`maxMin`)}
|
|
240
|
+
${t===`col`?LY(`l`,`c:valAx`,gY,mY,e.axesDesign?.y?.title,e.fontColor):LY(`l`,`c:valAx`,gY,mY,e.axesDesign?.x?.title,e.fontColor,void 0,void 0,`max`)}
|
|
241
241
|
`:``}
|
|
242
242
|
${a.length?$`
|
|
243
243
|
<c:barChart>
|
|
@@ -248,25 +248,25 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
248
248
|
<!-- each data marker in the series does not have a different color -->
|
|
249
249
|
<c:varyColors val="0"/>
|
|
250
250
|
${Q(a)}
|
|
251
|
-
<c:axId val="${
|
|
252
|
-
<c:axId val="${
|
|
251
|
+
<c:axId val="${mY+1}" />
|
|
252
|
+
<c:axId val="${gY+1}" />
|
|
253
253
|
</c:barChart>
|
|
254
|
-
${
|
|
255
|
-
${
|
|
256
|
-
`:``}`}function
|
|
254
|
+
${LY(`b`,`c:catAx`,mY+1,gY+1,e.axesDesign?.x?.title,e.fontColor,+!!i.length)}
|
|
255
|
+
${LY(`r`,`c:valAx`,gY+1,mY+1,e.axesDesign?.y1?.title,e.fontColor)}
|
|
256
|
+
`:``}`}function kY(e){let t=e.dataSets,n=t.map(e=>e.backgroundColor??``),r=new ei(t.length,n),i=t[0],a=V(r.next()),o=i.rightYAxis??!1,s=$`
|
|
257
257
|
<c:ser>
|
|
258
258
|
<c:idx val="0"/>
|
|
259
259
|
<c:order val="0"/>
|
|
260
|
-
${
|
|
261
|
-
${
|
|
262
|
-
${
|
|
263
|
-
${e.labelRange?$`<c:cat>${
|
|
260
|
+
${wY(i.trend,a)}
|
|
261
|
+
${DY(i.label)}
|
|
262
|
+
${yY({backgroundColor:a,line:{color:a}})}
|
|
263
|
+
${e.labelRange?$`<c:cat>${BY(e.labelRange)}</c:cat>`:``}
|
|
264
264
|
<!-- x-coordinate values -->
|
|
265
265
|
<c:val>
|
|
266
|
-
${
|
|
266
|
+
${VY(i.range)}
|
|
267
267
|
</c:val>
|
|
268
268
|
</c:ser>
|
|
269
|
-
`,c=[],l=[];for(let n=1;n<t.length;n++){i=t[n];let a=V(r.next()),o=
|
|
269
|
+
`,c=[],l=[];for(let n=1;n<t.length;n++){i=t[n];let a=V(r.next()),o=yY({backgroundColor:a,line:{color:a}}),s=$`
|
|
270
270
|
<c:ser>
|
|
271
271
|
<c:idx val="${n}"/>
|
|
272
272
|
<c:order val="${n}"/>
|
|
@@ -276,13 +276,13 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
276
276
|
<c:size val="5"/>
|
|
277
277
|
${o}
|
|
278
278
|
</c:marker>
|
|
279
|
-
${
|
|
280
|
-
${
|
|
279
|
+
${wY(i.trend,a)}
|
|
280
|
+
${DY(i.label)}
|
|
281
281
|
${o}
|
|
282
|
-
${e.labelRange?$`<c:cat>${
|
|
282
|
+
${e.labelRange?$`<c:cat>${BY(e.labelRange)}</c:cat>`:``}
|
|
283
283
|
<!-- x-coordinate values -->
|
|
284
284
|
<c:val>
|
|
285
|
-
${
|
|
285
|
+
${VY(i.range)}
|
|
286
286
|
</c:val>
|
|
287
287
|
</c:ser>
|
|
288
288
|
`;i.rightYAxis?l.push(s):c.push(s)}return $`
|
|
@@ -294,8 +294,8 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
294
294
|
<!-- each data marker in the series does not have a different color -->
|
|
295
295
|
<c:varyColors val="0"/>
|
|
296
296
|
${s}
|
|
297
|
-
<c:axId val="${o?mY
|
|
298
|
-
<c:axId val="${o?gY
|
|
297
|
+
<c:axId val="${o?hY:mY}" />
|
|
298
|
+
<c:axId val="${o?_Y:gY}" />
|
|
299
299
|
</c:barChart>
|
|
300
300
|
${c.length?$`
|
|
301
301
|
<c:lineChart>
|
|
@@ -303,8 +303,8 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
303
303
|
<!-- each data marker in the series does not have a different color -->
|
|
304
304
|
<c:varyColors val="0"/>
|
|
305
305
|
${Q(c)}
|
|
306
|
-
<c:axId val="${
|
|
307
|
-
<c:axId val="${
|
|
306
|
+
<c:axId val="${mY}" />
|
|
307
|
+
<c:axId val="${gY}" />
|
|
308
308
|
</c:lineChart>
|
|
309
309
|
`:``}
|
|
310
310
|
${l.length?$`
|
|
@@ -313,19 +313,19 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
313
313
|
<!-- each data marker in the series does not have a different color -->
|
|
314
314
|
<c:varyColors val="0"/>
|
|
315
315
|
${Q(l)}
|
|
316
|
-
<c:axId val="${
|
|
317
|
-
<c:axId val="${
|
|
316
|
+
<c:axId val="${hY}" />
|
|
317
|
+
<c:axId val="${_Y}" />
|
|
318
318
|
</c:lineChart>
|
|
319
319
|
`:``}
|
|
320
320
|
${!o||c.length?$`
|
|
321
|
-
${
|
|
322
|
-
${
|
|
321
|
+
${LY(`b`,`c:catAx`,mY,gY,e.axesDesign?.x?.title,e.fontColor,0)}
|
|
322
|
+
${LY(`l`,`c:valAx`,gY,mY,e.axesDesign?.y?.title,e.fontColor)}
|
|
323
323
|
`:``}
|
|
324
324
|
${o||l.length?$`
|
|
325
|
-
${
|
|
326
|
-
${
|
|
325
|
+
${LY(`b`,`c:catAx`,hY,_Y,e.axesDesign?.x?.title,e.fontColor,c.length||!o?1:0)}
|
|
326
|
+
${LY(`r`,`c:valAx`,_Y,hY,e.axesDesign?.y1?.title,e.fontColor)}
|
|
327
327
|
`:``}
|
|
328
|
-
`}function
|
|
328
|
+
`}function AY(e){let t=e.dataSets,n=t.map(e=>e.backgroundColor??``),r=new ei(t.length,n),i=t[0],a=t[1],o=V(r.next()),s=V(r.next()),{maxValue:c,majorUnit:l}=jY(e.maxValue),u=e.labelRange?$`<c:cat>${BY(e.labelRange)}</c:cat>`:``;return $`
|
|
329
329
|
<c:barChart>
|
|
330
330
|
<c:barDir val="bar"/>
|
|
331
331
|
<c:grouping val="clustered"/>
|
|
@@ -335,18 +335,18 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
335
335
|
<c:idx val="0"/>
|
|
336
336
|
<c:order val="0"/>
|
|
337
337
|
<c:invertIfNegative val="0" />
|
|
338
|
-
${
|
|
339
|
-
${
|
|
338
|
+
${DY(i.label)}
|
|
339
|
+
${yY({backgroundColor:o,line:{color:o}})}
|
|
340
340
|
${u}
|
|
341
341
|
<!-- x-coordinate values -->
|
|
342
342
|
<c:val>
|
|
343
|
-
${
|
|
343
|
+
${VY(i.range)}
|
|
344
344
|
</c:val>
|
|
345
345
|
</c:ser>
|
|
346
346
|
`}
|
|
347
347
|
<c:gapWidth val="50" />
|
|
348
|
-
<c:axId val="${
|
|
349
|
-
<c:axId val="${
|
|
348
|
+
<c:axId val="${mY}" />
|
|
349
|
+
<c:axId val="${gY}" />
|
|
350
350
|
</c:barChart>
|
|
351
351
|
<c:barChart>
|
|
352
352
|
<c:barDir val="bar"/>
|
|
@@ -357,24 +357,24 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
357
357
|
<c:idx val="1"/>
|
|
358
358
|
<c:order val="1"/>
|
|
359
359
|
<c:invertIfNegative val="0" />
|
|
360
|
-
${
|
|
361
|
-
${
|
|
362
|
-
${e.labelRange?$`<c:cat>${
|
|
360
|
+
${DY(a.label)}
|
|
361
|
+
${yY({backgroundColor:s,line:{color:s}})}
|
|
362
|
+
${e.labelRange?$`<c:cat>${BY(e.labelRange)}</c:cat>`:``}
|
|
363
363
|
<!-- x-coordinate values -->
|
|
364
364
|
<c:val>
|
|
365
|
-
${
|
|
365
|
+
${VY(a.range)}
|
|
366
366
|
</c:val>
|
|
367
367
|
</c:ser>
|
|
368
368
|
`}
|
|
369
369
|
<c:gapWidth val="50" />
|
|
370
|
-
<c:axId val="${
|
|
371
|
-
<c:axId val="${
|
|
370
|
+
<c:axId val="${hY}" />
|
|
371
|
+
<c:axId val="${_Y}" />
|
|
372
372
|
</c:barChart>
|
|
373
|
-
${
|
|
374
|
-
${
|
|
375
|
-
${
|
|
376
|
-
${
|
|
377
|
-
`}function
|
|
373
|
+
${LY(`r`,`c:catAx`,mY,gY,e.axesDesign?.y?.title,e.fontColor,0,`maxMin`,`autoZero`,`high`)}
|
|
374
|
+
${LY(`b`,`c:valAx`,gY,mY,e.axesDesign?.x?.title,e.fontColor,0,`maxMin`,`max`,`nextTo`,c,l,`#0;#0`)}
|
|
375
|
+
${LY(`t`,`c:valAx`,_Y,hY,void 0,e.fontColor,1)}
|
|
376
|
+
${LY(`l`,`c:catAx`,hY,_Y,void 0,e.fontColor,1,`maxMin`)}
|
|
377
|
+
`}function jY(e){let t=((e,t)=>{let n=Math.ceil(e);for(;n%t!==0;)n++;return n})(e,3);return{maxValue:t,majorUnit:t/3}}function MY(e){let t=e.dataSets.map(e=>e.backgroundColor??``),n=new ei(e.dataSets.length,t),r=[],i=[];for(let[t,a]of Object.entries(e.dataSets)){let o=V(n.next()),s=yY({line:{width:2.5,style:`solid`,color:o}}),c=$`
|
|
378
378
|
<c:ser>
|
|
379
379
|
<c:idx val="${t}"/>
|
|
380
380
|
<c:order val="${t}"/>
|
|
@@ -382,14 +382,14 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
382
382
|
<c:marker>
|
|
383
383
|
<c:symbol val="circle" />
|
|
384
384
|
<c:size val="5"/>
|
|
385
|
-
${
|
|
385
|
+
${yY({backgroundColor:o,line:{color:o}})}
|
|
386
386
|
</c:marker>
|
|
387
|
-
${
|
|
388
|
-
${
|
|
387
|
+
${wY(a.trend,o)}
|
|
388
|
+
${DY(a.label)}
|
|
389
389
|
${s}
|
|
390
|
-
${e.labelRange?$`<c:cat>${
|
|
390
|
+
${e.labelRange?$`<c:cat>${BY(e.labelRange)}</c:cat>`:``} <!-- x-coordinate values -->
|
|
391
391
|
<c:val> <!-- x-coordinate values -->
|
|
392
|
-
${
|
|
392
|
+
${VY(a.range)}
|
|
393
393
|
</c:val>
|
|
394
394
|
</c:ser>
|
|
395
395
|
`;a.rightYAxis?i.push(c):r.push(c)}let a=e.stacked?`stacked`:`standard`;return $`
|
|
@@ -399,11 +399,11 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
399
399
|
<!-- each data marker in the series does not have a different color -->
|
|
400
400
|
<c:varyColors val="0"/>
|
|
401
401
|
${Q(r)}
|
|
402
|
-
<c:axId val="${
|
|
403
|
-
<c:axId val="${
|
|
402
|
+
<c:axId val="${mY}" />
|
|
403
|
+
<c:axId val="${gY}" />
|
|
404
404
|
</c:lineChart>
|
|
405
|
-
${
|
|
406
|
-
${
|
|
405
|
+
${LY(`b`,`c:catAx`,mY,gY,e.axesDesign?.x?.title,e.fontColor)}
|
|
406
|
+
${LY(`l`,`c:valAx`,gY,mY,e.axesDesign?.y?.title,e.fontColor)}
|
|
407
407
|
`:``}
|
|
408
408
|
${i.length?$`
|
|
409
409
|
<c:lineChart>
|
|
@@ -411,13 +411,13 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
411
411
|
<!-- each data marker in the series does not have a different color -->
|
|
412
412
|
<c:varyColors val="0"/>
|
|
413
413
|
${Q(i)}
|
|
414
|
-
<c:axId val="${
|
|
415
|
-
<c:axId val="${
|
|
414
|
+
<c:axId val="${mY+1}" />
|
|
415
|
+
<c:axId val="${gY+1}" />
|
|
416
416
|
</c:lineChart>
|
|
417
|
-
${
|
|
418
|
-
${
|
|
417
|
+
${LY(`b`,`c:catAx`,mY+1,gY+1,e.axesDesign?.x?.title,e.fontColor,+!!r.length)}
|
|
418
|
+
${LY(`r`,`c:valAx`,gY+1,mY+1,e.axesDesign?.y1?.title,e.fontColor)}
|
|
419
419
|
`:``}
|
|
420
|
-
`}function
|
|
420
|
+
`}function NY(e){let t=e.dataSets.map(e=>e.backgroundColor??``),n=new ei(e.dataSets.length,t),r=[],i=[];for(let[t,a]of Object.entries(e.dataSets)){let o=V(n.next()),s=$`
|
|
421
421
|
<c:ser>
|
|
422
422
|
<c:idx val="${t}"/>
|
|
423
423
|
<c:order val="${t}"/>
|
|
@@ -432,15 +432,15 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
432
432
|
<c:marker>
|
|
433
433
|
<c:symbol val="circle" />
|
|
434
434
|
<c:size val="5"/>
|
|
435
|
-
${
|
|
435
|
+
${yY({backgroundColor:o,line:{color:o}})}
|
|
436
436
|
</c:marker>
|
|
437
|
-
${
|
|
438
|
-
${
|
|
437
|
+
${wY(a.trend,o)}
|
|
438
|
+
${DY(a.label)}
|
|
439
439
|
${e.labelRange?$`<c:xVal> <!-- x-coordinate values -->
|
|
440
|
-
${
|
|
440
|
+
${VY(e.labelRange)}
|
|
441
441
|
</c:xVal>`:``}
|
|
442
442
|
<c:yVal> <!-- y-coordinate values -->
|
|
443
|
-
${
|
|
443
|
+
${VY(a.range)}
|
|
444
444
|
</c:yVal>
|
|
445
445
|
</c:ser>
|
|
446
446
|
`;a.rightYAxis?i.push(s):r.push(s)}return $`
|
|
@@ -450,11 +450,11 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
450
450
|
<c:varyColors val="0"/>
|
|
451
451
|
<c:scatterStyle val="lineMarker"/>
|
|
452
452
|
${Q(r)}
|
|
453
|
-
<c:axId val="${
|
|
454
|
-
<c:axId val="${
|
|
453
|
+
<c:axId val="${mY}" />
|
|
454
|
+
<c:axId val="${gY}" />
|
|
455
455
|
</c:scatterChart>
|
|
456
|
-
${
|
|
457
|
-
${
|
|
456
|
+
${LY(`b`,`c:valAx`,mY,gY,e.axesDesign?.x?.title,e.fontColor)}
|
|
457
|
+
${LY(`l`,`c:valAx`,gY,mY,e.axesDesign?.y?.title,e.fontColor)}
|
|
458
458
|
`:``}
|
|
459
459
|
${i.length?$`
|
|
460
460
|
<c:scatterChart>
|
|
@@ -462,12 +462,12 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
462
462
|
<c:varyColors val="0"/>
|
|
463
463
|
<c:scatterStyle val="lineMarker"/>
|
|
464
464
|
${Q(i)}
|
|
465
|
-
<c:axId val="${
|
|
466
|
-
<c:axId val="${
|
|
465
|
+
<c:axId val="${mY+1}" />
|
|
466
|
+
<c:axId val="${gY+1}" />
|
|
467
467
|
</c:scatterChart>
|
|
468
|
-
${
|
|
469
|
-
${
|
|
470
|
-
`:``}`}function
|
|
468
|
+
${LY(`b`,`c:valAx`,mY+1,gY+1,e.axesDesign?.x?.title,e.fontColor,+!!r.length)}
|
|
469
|
+
${LY(`r`,`c:valAx`,gY+1,mY+1,e.axesDesign?.y1?.title,e.fontColor)}
|
|
470
|
+
`:``}`}function PY(e){let t=e.dataSets.map(e=>e.backgroundColor??``),n=new ei(e.dataSets.length,t),r=[];for(let[t,i]of Object.entries(e.dataSets)){let a=V(n.next()),o=yY({line:{width:2.5,style:`solid`,color:a}}),s=$`
|
|
471
471
|
<c:ser>
|
|
472
472
|
<c:idx val="${t}"/>
|
|
473
473
|
<c:order val="${t}"/>
|
|
@@ -475,13 +475,13 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
475
475
|
<c:marker>
|
|
476
476
|
<c:symbol val="circle" />
|
|
477
477
|
<c:size val="5"/>
|
|
478
|
-
${
|
|
478
|
+
${yY({backgroundColor:a,line:{color:a}})}
|
|
479
479
|
</c:marker>
|
|
480
|
-
${
|
|
480
|
+
${DY(i.label)}
|
|
481
481
|
${o}
|
|
482
|
-
${e.labelRange?$`<c:cat>${
|
|
482
|
+
${e.labelRange?$`<c:cat>${BY(e.labelRange)}</c:cat>`:``} <!-- x-coordinate values -->
|
|
483
483
|
<c:val> <!-- x-coordinate values -->
|
|
484
|
-
${
|
|
484
|
+
${VY(i.range)}
|
|
485
485
|
</c:val>
|
|
486
486
|
</c:ser>
|
|
487
487
|
`;r.push(s)}return $`
|
|
@@ -490,13 +490,13 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
490
490
|
<c:radarStyle val="marker"/>
|
|
491
491
|
<c:varyColors val="0"/>
|
|
492
492
|
${Q(r)}
|
|
493
|
-
<c:axId val="${
|
|
494
|
-
<c:axId val="${
|
|
493
|
+
<c:axId val="${mY}" />
|
|
494
|
+
<c:axId val="${gY}" />
|
|
495
495
|
</c:radarChart>
|
|
496
|
-
${
|
|
497
|
-
${
|
|
496
|
+
${LY(`b`,`c:catAx`,mY,gY,e.axesDesign?.x?.title,e.fontColor)}
|
|
497
|
+
${LY(`l`,`c:valAx`,gY,mY,e.axesDesign?.y?.title,e.fontColor)}
|
|
498
498
|
`}
|
|
499
|
-
`}function
|
|
499
|
+
`}function FY(e,t,n){let r=Pt(e.dataSets.map(e=>fM(e.range,t,n))),i=new ei(r),a=S(0,r).map(()=>V(i.next())),o=[];for(let[r,i]of Object.entries(e.dataSets).reverse()){let s=fM(i.range,t,n),c=[];for(let e of S(0,s)){let t=yY({backgroundColor:a[e],line:{color:`FFFFFF`,width:1.5}});c.push($`
|
|
500
500
|
<c:dPt>
|
|
501
501
|
<c:idx val="${e}"/>
|
|
502
502
|
${t}
|
|
@@ -505,22 +505,22 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
505
505
|
<c:ser>
|
|
506
506
|
<c:idx val="${r}"/>
|
|
507
507
|
<c:order val="${r}"/>
|
|
508
|
-
${
|
|
508
|
+
${DY(i.label)}
|
|
509
509
|
${Q(c)}
|
|
510
|
-
${
|
|
511
|
-
${e.labelRange?$`<c:cat>${
|
|
510
|
+
${IY({showLeaderLines:!0})}
|
|
511
|
+
${e.labelRange?$`<c:cat>${BY(e.labelRange)}</c:cat>`:``}
|
|
512
512
|
<c:val>
|
|
513
|
-
${
|
|
513
|
+
${VY(i.range)}
|
|
514
514
|
</c:val>
|
|
515
515
|
</c:ser>
|
|
516
516
|
`)}return $`
|
|
517
517
|
<c:doughnutChart>
|
|
518
518
|
<c:varyColors val="1" />
|
|
519
519
|
<c:holeSize val="${e.pieHolePercentage??(e.isDoughnut?50:0)}" />
|
|
520
|
-
${
|
|
520
|
+
${IY()}
|
|
521
521
|
${Q(o)}
|
|
522
522
|
</c:doughnutChart>
|
|
523
|
-
`}function
|
|
523
|
+
`}function IY({showLeaderLines:e}={showLeaderLines:!1}){return $`
|
|
524
524
|
<dLbls>
|
|
525
525
|
<c:showLegendKey val="0"/>
|
|
526
526
|
<c:showVal val="0"/>
|
|
@@ -530,7 +530,7 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
530
530
|
<c:showBubbleSize val="0"/>
|
|
531
531
|
<c:showLeaderLines val="${e?`1`:`0`}"/>
|
|
532
532
|
</dLbls>
|
|
533
|
-
`}function
|
|
533
|
+
`}function LY(e,t,n,r,i,a,o=0,s=`minMax`,c,l=`nextTo`,u,d,f=`General`){let p=i?.color?V(i.color):a,m=i?.fontSize??12,h=t===`c:valAx`?$`<c:crossBetween val="between" />`:``,g=u?$`<c:max val="${u}" />`:``,_=u?$`<c:min val="${-u}" />`:``,v=d?$`<c:majorUnit val="${d}" />`:``;return $`
|
|
534
534
|
<${t}>
|
|
535
535
|
<c:axId val="${n}"/>
|
|
536
536
|
<c:crossAx val="${r}"/> <!-- reference to the other axe of the chart -->
|
|
@@ -546,42 +546,42 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
546
546
|
${v}
|
|
547
547
|
<c:axPos val="${e}" />
|
|
548
548
|
<c:tickLblPos val="${l}" />
|
|
549
|
-
${
|
|
549
|
+
${zY()}
|
|
550
550
|
<c:majorTickMark val="out" />
|
|
551
551
|
<c:minorTickMark val="none" />
|
|
552
552
|
<c:numFmt formatCode="${f}" sourceLinked="${f===`General`?`1`:`0`}" />
|
|
553
553
|
<c:title>
|
|
554
|
-
${
|
|
554
|
+
${SY(i?.text??``,p,m,i)}
|
|
555
555
|
</c:title>
|
|
556
|
-
${
|
|
556
|
+
${CY(10,a)}
|
|
557
557
|
</${t}>
|
|
558
558
|
<!-- <tickLblPos/> omitted -->
|
|
559
|
-
`}function
|
|
559
|
+
`}function RY(e,t){return $`
|
|
560
560
|
<c:legend>
|
|
561
561
|
<c:legendPos val="${e}"/>
|
|
562
562
|
<c:overlay val="0"/>
|
|
563
|
-
${
|
|
563
|
+
${CY(10,t)}
|
|
564
564
|
</c:legend>
|
|
565
|
-
`}function
|
|
565
|
+
`}function zY(e=`B7B7B7`){return $`
|
|
566
566
|
<c:majorGridlines>
|
|
567
|
-
${
|
|
567
|
+
${yY({line:{color:e}})}
|
|
568
568
|
</c:majorGridlines>
|
|
569
|
-
`}function
|
|
569
|
+
`}function BY(e){return $`
|
|
570
570
|
<c:strRef>
|
|
571
571
|
<c:f>${e}</c:f>
|
|
572
572
|
</c:strRef>
|
|
573
|
-
`}function
|
|
573
|
+
`}function VY(e){return $`
|
|
574
574
|
<c:numRef>
|
|
575
575
|
<c:f>${e}</c:f>
|
|
576
576
|
<c:numCache />
|
|
577
577
|
</c:numRef>
|
|
578
|
-
`}function
|
|
578
|
+
`}function HY(e,t,n){if(!e)return{attrs:[],node:$``};let r=Yj(t);return r===void 0?{attrs:[],node:$``}:{attrs:[[`cm`,`1`],[`t`,r]],node:$`<f t="array" ref="${n}">${WY(e)}</f><v>${GY(t)}</v>`}}function UY(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||!$i(r,R))&&(r=sM(e,t),i.push([`t`,`s`])),{attrs:i,node:$`<v>${r}</v>`}}function WY(e){e[0]===`=`&&(e=e.slice(1));let t;try{t=KO(e)}catch{return e}return t=JO(t,`STRING`,JY),t=JO(t,`FUNCALL`,e=>(e={...e,value:e.value.toUpperCase()},e=qY(e),e=KY(e),e)),t=JO(t,`REFERENCE`,e=>e.value===A.InvalidReference?{...e,value:`#REF!`}:e),t?yB(t):e}function GY(e){return e===A.InvalidReference?`#REF!`:e}function KY(e){let t=e.value.toUpperCase(),n=e.args,r=gu[t];if(r){let i=yO.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,tokenEndIndex:0,tokenStartIndex:0})}}return{...e,args:n}}function qY(e){let t=e.value.toUpperCase();return{...e,value:_u.includes(t)?`_xlfn.${t}`:t}}function JY(e){let t=e.value.replace(RegExp(`"`,`g`),``),n=Ci(t,R);if(n){let r=[];return(mi.test(t)||hi.test(t))&&r.push(`yyyy-mm-dd`),yi.test(t)&&r.push(`hh:mm:ss`),{...e,value:z(n.value,{format:r.join(` `),locale:R})}}else return{...e,value:e.value.replace(/\\"/g,`""`)}}function YY(e,t){let n=[];for(let r of t)switch(r.rule.type){case`CellIsRule`:n.push(XY(r,r.rule,e));break;case`ColorScaleRule`:n.push(eX(r,r.rule));break;case`IconSetRule`:n.push(tX(r,r.rule));break;case`DataBarRule`:n.push($Y(r,r.rule));break;default:console.warn(`Conditional formatting ${r.rule.type} not implemented`);break}return n}function XY(e,t,n){let r=nX(e),i=Jj(t.operator);r.push(...QY(t)),i.length&&r.push([`operator`,i]);let a=ZY(e.ranges,t).map(e=>$`<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`,sM(o,n)]),$`
|
|
579
579
|
<conditionalFormatting sqref="${e.ranges.join(` `)}">
|
|
580
580
|
<cfRule ${Z(r)}>
|
|
581
581
|
${Q(a)}
|
|
582
582
|
</cfRule>
|
|
583
583
|
</conditionalFormatting>
|
|
584
|
-
`}function
|
|
584
|
+
`}function ZY(e,t){let n=e[0].split(`:`)[0],r=t.values;switch(t.operator){case`containsText`:return[`NOT(ISERROR(SEARCH("${r[0]}",${n})))`];case`notContainsText`:return[`ISERROR(SEARCH("${r[0]}",${n}))`];case`beginsWithText`:return[`LEFT(${n},LEN("${r[0]}"))="${r[0]}"`];case`endsWithText`:return[`RIGHT(${n},LEN("${r[0]}"))="${r[0]}"`];case`isEmpty`:return[`LEN(TRIM(${n}))=0`];case`isNotEmpty`:return[`LEN(TRIM(${n}))>0`];case`isEqual`:case`isNotEqual`:case`isGreaterThan`:case`isGreaterOrEqualTo`:case`isLessThan`:case`isLessOrEqualTo`:return[r[0]];case`customFormula`:return r[0].startsWith(`=`)?[r[0].slice(1)]:[r[0]];case`isBetween`:case`isNotBetween`:return[r[0],r[1]];case`dateIs`:switch(t.dateValue){case`exactDate`:{let e=`ROUNDDOWN(${r[0].startsWith(`=`)?r[0].slice(1):(nc(r[0],R)||``).toString()},0)`;return[`AND(${n}>=${e},${n}<${e}+1)`]}case`today`:return[`AND(${n}>=TODAY(),${n}<TODAY()+1)`];case`yesterday`:return[`AND(${n}>=TODAY()-1,${n}<TODAY())`];case`tomorrow`:return[`AND(${n}>=TODAY()+1,${n}<TODAY()+2)`];case`lastWeek`:return[`AND(${n}>=TODAY()-7,${n}<TODAY())`];case`lastMonth`:return[`AND(${n}>=EDATE(TODAY(),-1),${n}<TODAY())`];case`lastYear`:return[`AND(${n}>=EDATE(TODAY(),-12),${n}<TODAY())`];case void 0:throw Error(`dateValue should be defined`)}case`dateIsBefore`:case`dateIsAfter`:case`dateIsOnOrAfter`:case`dateIsOnOrBefore`:switch(t.dateValue){case`exactDate`:return r[0].startsWith(`=`)?[r[0].slice(1)]:[(nc(r[0],R)||``).toString()];case`today`:return[`TODAY()`];case`yesterday`:return[`TODAY()-1`];case`tomorrow`:return[`TODAY()+1`];case`lastWeek`:return[`TODAY()-7`];case`lastMonth`:return[`EDATE(TODAY(),-1)`];case`lastYear`:return[`EDATE(TODAY(),-12)`];case void 0:throw Error(`dateValue should be defined`)}}}function QY(e){let t=Jj(e.operator);switch(e.operator){case`containsText`:case`notContainsText`:case`beginsWithText`:case`endsWithText`:return[[`type`,t],[`text`,e.values[0]]];case`isEmpty`:case`isNotEmpty`:return[[`type`,t]];case`isEqual`:case`isNotEqual`:case`isGreaterThan`:case`isGreaterOrEqualTo`:case`isLessThan`:case`isLessOrEqualTo`:case`isBetween`:case`isNotBetween`:case`dateIsBefore`:case`dateIsAfter`:case`dateIsOnOrAfter`:case`dateIsOnOrBefore`:return[[`type`,`cellIs`]];case`dateIs`:case`customFormula`:return[[`type`,`expression`]]}}function $Y(e,t){let n=nX(e);return n.push([`type`,`dataBar`]),$`
|
|
585
585
|
<conditionalFormatting sqref="${e.ranges.join(` `)}">
|
|
586
586
|
<cfRule ${Z(n)}>
|
|
587
587
|
<dataBar>
|
|
@@ -591,7 +591,7 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
591
591
|
</dataBar>
|
|
592
592
|
</cfRule>
|
|
593
593
|
</conditionalFormatting>
|
|
594
|
-
`}function
|
|
594
|
+
`}function eX(e,t){let n=nX(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(oX(r,n)),a.push([[`rgb`,V(Sr(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=>$`<cfvo ${Z(e)}/>`),c=a.map(e=>$`<color ${Z(e)}/>`);r.push($`
|
|
595
595
|
<conditionalFormatting sqref="${i}">
|
|
596
596
|
<cfRule ${Z(n)}>
|
|
597
597
|
<colorScale>
|
|
@@ -600,7 +600,7 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
600
600
|
</colorScale>
|
|
601
601
|
</cfRule>
|
|
602
602
|
</conditionalFormatting>
|
|
603
|
-
`)}return Q(r)}function
|
|
603
|
+
`)}return Q(r)}function tX(e,t){let n=nX(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([...oX(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=>$`<cfvo ${Z(e)} />`),s=[[`iconSet`,iX(t.icons)]];rX(t.icons)&&s.push([`reverse`,`1`]),r.push($`
|
|
604
604
|
<conditionalFormatting sqref="${i}">
|
|
605
605
|
<cfRule ${Z(n)}>
|
|
606
606
|
<iconSet ${Z(s)}>
|
|
@@ -608,7 +608,7 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
608
608
|
</iconSet>
|
|
609
609
|
</cfRule>
|
|
610
610
|
</conditionalFormatting>
|
|
611
|
-
`)}return Q(r)}function
|
|
611
|
+
`)}return Q(r)}function nX(e){return[[`priority`,1],[`stopIfTrue`,+!!e.stopIfTrue]]}function rX(e){let t=lj[aX(e)];return e.upper===t.bad&&e.lower===t.good}function iX(e){return au[aX(e)]}function aX(e){return Object.keys(lj).find(t=>Object.values(lj[t]).includes(e.upper))||`dots`}function oX(e,t){let n=sX(e.type,t),r=[[`type`,n]];if(n!==`min`&&n!==`max`){let t=e.value;if(n===`formula`)try{t=WY(e.value)}catch{t=e.value}r.push([`val`,t])}return r}function sX(e,t){switch(e){case`value`:return t===`minimum`?`min`:`max`;case`number`:return`num`;case`percentage`:return`percent`;default:return e}}function cX(e){let t=e.length;if(t===0)return[];let n=[new zA(`<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(lX(t));break;case`isEqual`:case`isNotEqual`:case`isGreaterThan`:case`isGreaterOrEqualTo`:case`isLessThan`:case`isLessOrEqualTo`:case`isBetween`:case`isNotBetween`:n.push(uX(t));break;case`isValueInRange`:case`isValueInList`:n.push(dX(t));break;case`customFormula`:n.push(fX(t));break;default:console.warn(`Data validation ${t.criterion.type} is not supported in xlsx.`);break}return n.push(new zA(`</dataValidations>`)),n}function lX(e){let t=e.criterion,n=WY(t.values[0]),r=t.values[1]?WY(t.values[1]):void 0,i=_M(e.criterion.type),a=pX(e);return a.push([`type`,`date`],[`operator`,i]),r?$`
|
|
612
612
|
<dataValidation ${Z(a)}>
|
|
613
613
|
<formula1>${N(n,R)}</formula1>
|
|
614
614
|
<formula2>${N(r,R)}</formula2>
|
|
@@ -617,7 +617,7 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
617
617
|
<dataValidation ${Z(a)}>
|
|
618
618
|
<formula1>${N(n,R)}</formula1>
|
|
619
619
|
</dataValidation>
|
|
620
|
-
`}function
|
|
620
|
+
`}function uX(e){let t=e.criterion,n=WY(t.values[0]),r=t.values[1]?WY(t.values[1]):void 0,i=gM(e.criterion.type),a=pX(e);return a.push([`type`,`decimal`],[`operator`,i]),r?$`
|
|
621
621
|
<dataValidation ${Z(a)}>
|
|
622
622
|
<formula1>${n}</formula1>
|
|
623
623
|
<formula2>${r}</formula2>
|
|
@@ -626,19 +626,19 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
626
626
|
<dataValidation ${Z(a)}>
|
|
627
627
|
<formula1>${n}</formula1>
|
|
628
628
|
</dataValidation>
|
|
629
|
-
`}function
|
|
629
|
+
`}function dX(e){let t=e.criterion,n=e.criterion.type===`isValueInRange`?WY(t.values[0]):`"${t.values.join(`,`)}"`,r=pX(e);return r.push([`type`,`list`]),$`
|
|
630
630
|
<dataValidation ${Z(r)}>
|
|
631
631
|
<formula1>${n}</formula1>
|
|
632
632
|
</dataValidation>
|
|
633
|
-
`}function
|
|
633
|
+
`}function fX(e){let t=e.criterion,n=WY(t.values[0]),r=pX(e);return r.push([`type`,`custom`]),$`
|
|
634
634
|
<dataValidation ${Z(r)}>
|
|
635
635
|
<formula1>${n}</formula1>
|
|
636
636
|
</dataValidation>
|
|
637
|
-
`}function
|
|
637
|
+
`}function pX(e){return[[`allowBlank`,`1`],[`showInputMessage`,`1`],[`showErrorMessage`,`1`],[`errorStyle`,e.isBlocking?``:`warning`],[`sqref`,e.ranges.join(` `)]]}function mX(e,t,n,r){let i=[[`xmlns:xdr`,ou.drawing],[`xmlns:r`,du],[`xmlns:a`,su],[`xmlns:c`,cu]],a=[];for(let[i,o]of Object.entries(n))switch(o?.tag){case`chart`:a.push(_X(o,t,e[i],r));break;case`image`:a.push(vX(o,t,e[i]));break}return DN($`
|
|
638
638
|
<xdr:wsDr ${Z(i)}>
|
|
639
639
|
${Q(a)}
|
|
640
640
|
</xdr:wsDr>
|
|
641
|
-
`)}function
|
|
641
|
+
`)}function hX(e,t){let{col:n,row:r,offset:i,width:a,height:o}=e,{x:s,y:c}=i,l=Object.values(t.rows),{index:u,offset:d}=gX(l,r,c),{index:f,offset:p}=gX(l,r,c+o),m=Object.values(t.cols),{index:h,offset:g}=gX(m,n,s),{index:_,offset:v}=gX(m,n,s+a);return{from:{col:h,colOff:g,row:u,rowOff:d},to:{col:_,colOff:v,row:f,rowOff:p}}}function gX(e,t,n){let r=0;for(let[i,a]of e.slice(t).entries())if(r<=n&&n<r+a.size)return{index:t+i,offset:dM(n-r+1)};else i<e.length-1&&(r+=a.size);return{index:e.length-1,offset:dM(n-r+1)}}function _X(e,t,n,r){let{from:i,to:a}=hX(e,t),o=cM(e.id,r),s=[[`id`,o],[`name`,`Chart ${o}`],[`title`,`Chart`]];return $`
|
|
642
642
|
<xdr:twoCellAnchor>
|
|
643
643
|
<xdr:from>
|
|
644
644
|
<xdr:col>${i.col}</xdr:col>
|
|
@@ -669,7 +669,7 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
669
669
|
</xdr:graphicFrame>
|
|
670
670
|
<xdr:clientData fLocksWithSheet="0"/>
|
|
671
671
|
</xdr:twoCellAnchor>
|
|
672
|
-
`}function
|
|
672
|
+
`}function vX(e,t,n){let{from:r,to:i}=hX(e,t),a=uM(e.id),o=[[`id`,a],[`name`,`Image ${a}`],[`title`,`Image`]],s=dM(e.width),c=dM(e.height);return $`
|
|
673
673
|
<xdr:twoCellAnchor editAs="oneCell">
|
|
674
674
|
<xdr:from>
|
|
675
675
|
<xdr:col>${r.col}</xdr:col>
|
|
@@ -706,13 +706,13 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
706
706
|
</xdr:pic>
|
|
707
707
|
<xdr:clientData fLocksWithSheet="0"/>
|
|
708
708
|
</xdr:twoCellAnchor>
|
|
709
|
-
`}function
|
|
709
|
+
`}function yX(e){let t=[];for(let[n,r]of Object.entries(e)){let e=[[`numFmtId`,parseInt(n)+164],[`formatCode`,r.format]];t.push($`
|
|
710
710
|
<numFmt ${Z(e)}/>
|
|
711
711
|
`)}return $`
|
|
712
712
|
<numFmts count="${e.length}">
|
|
713
713
|
${Q(t)}
|
|
714
714
|
</numFmts>
|
|
715
|
-
`}function
|
|
715
|
+
`}function bX(e){return ut(e)?$``:$`
|
|
716
716
|
<font>
|
|
717
717
|
${e.bold?$`<b />`:``}
|
|
718
718
|
${e.italic?$`<i />`:``}
|
|
@@ -722,11 +722,11 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
722
722
|
${e.color&&e.color.rgb?$`<color rgb="${V(e.color.rgb)}" />`:``}
|
|
723
723
|
${e.name?$`<name val="${e.name}" />`:``}
|
|
724
724
|
</font>
|
|
725
|
-
`}function
|
|
725
|
+
`}function xX(e){return $`
|
|
726
726
|
<fonts count="${e.length}">
|
|
727
|
-
${Q(Object.values(e).map(
|
|
727
|
+
${Q(Object.values(e).map(bX))}
|
|
728
728
|
</fonts>
|
|
729
|
-
`}function
|
|
729
|
+
`}function SX(e){let t=[];for(let n of Object.values(e))n.reservedAttribute===void 0?t.push($`
|
|
730
730
|
<fill>
|
|
731
731
|
<patternFill patternType="solid">
|
|
732
732
|
<fgColor rgb="${V(n.fgColor.rgb)}" />
|
|
@@ -741,35 +741,35 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
741
741
|
<fills count="${e.length}">
|
|
742
742
|
${Q(t)}
|
|
743
743
|
</fills>
|
|
744
|
-
`}function
|
|
744
|
+
`}function CX(e){let t=[];for(let n of Object.values(e))t.push($`
|
|
745
745
|
<border>
|
|
746
|
-
<left ${
|
|
747
|
-
${
|
|
746
|
+
<left ${wX(n.left)}>
|
|
747
|
+
${TX(n.left)}
|
|
748
748
|
</left>
|
|
749
|
-
<right ${
|
|
750
|
-
${
|
|
749
|
+
<right ${wX(n.right)}>
|
|
750
|
+
${TX(n.right)}
|
|
751
751
|
</right>
|
|
752
|
-
<top ${
|
|
753
|
-
${
|
|
752
|
+
<top ${wX(n.top)}>
|
|
753
|
+
${TX(n.top)}
|
|
754
754
|
</top>
|
|
755
|
-
<bottom ${
|
|
756
|
-
${
|
|
755
|
+
<bottom ${wX(n.bottom)}>
|
|
756
|
+
${TX(n.bottom)}
|
|
757
757
|
</bottom>
|
|
758
|
-
<diagonal ${
|
|
759
|
-
${
|
|
758
|
+
<diagonal ${wX(n.diagonal)}>
|
|
759
|
+
${TX(n.diagonal)}
|
|
760
760
|
</diagonal>
|
|
761
761
|
</border>
|
|
762
762
|
`);return $`
|
|
763
763
|
<borders count="${e.length}">
|
|
764
764
|
${Q(t)}
|
|
765
765
|
</borders>
|
|
766
|
-
`}function
|
|
766
|
+
`}function wX(e){return e?Z([[`style`,e.style]]):$``}function TX(e){return e?$`
|
|
767
767
|
<color ${Z([[`rgb`,V(e.color.rgb)]])}/>
|
|
768
|
-
`:$``}function
|
|
768
|
+
`:$``}function EX(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.textRotation&&r.push([`textRotation`,n.alignment.textRotation]),n.alignment&&n.alignment.shrinkToFit&&r.push([`shrinkToFit`,`1`]),r.length>0?(e.push([`applyAlignment`,`1`]),t.push($`<xf ${Z(e)}><alignment ${Z(r)} /></xf> `)):t.push($`<xf ${Z(e)} />`)}return $`
|
|
769
769
|
<cellXfs count="${e.length}">
|
|
770
770
|
${Q(t)}
|
|
771
771
|
</cellXfs>
|
|
772
|
-
`}function
|
|
772
|
+
`}function DX(e){let t=[];for(let n of e){let e=$``;n.font&&(e=bX(n.font));let r=$``;n.fill&&(r=$`
|
|
773
773
|
<fill>
|
|
774
774
|
<patternFill>
|
|
775
775
|
<bgColor rgb="${V(n.fill.fgColor.rgb)}" />
|
|
@@ -784,35 +784,35 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
784
784
|
<dxfs count="${e.length}">
|
|
785
785
|
${Q(t)}
|
|
786
786
|
</dxfs>
|
|
787
|
-
`}function
|
|
787
|
+
`}function OX(e,t,n){return DN($`
|
|
788
788
|
<table ${Z([[`id`,t],[`name`,`Table${t}`],[`displayName`,`Table${t}`],[`ref`,e.range],[`headerRowCount`,e.config.numberOfHeaders],[`totalsRowCount`,+!!e.config.totalRow],[`xmlns`,ou.table],[`xmlns:xr`,ou.revision],[`xmlns:xr3`,ou.revision3],[`xmlns:mc`,ou.markupCompatibility]])}>
|
|
789
|
-
${e.config.hasFilters?
|
|
790
|
-
${
|
|
791
|
-
${
|
|
789
|
+
${e.config.hasFilters?kX(e):``}
|
|
790
|
+
${MX(e,n)}
|
|
791
|
+
${NX(e)}
|
|
792
792
|
</table>
|
|
793
|
-
`)}function
|
|
793
|
+
`)}function kX(e){return $`
|
|
794
794
|
<autoFilter ${Z([[`ref`,e.range]])}>
|
|
795
|
-
${Q(
|
|
795
|
+
${Q(AX(e))}
|
|
796
796
|
</autoFilter>
|
|
797
|
-
`}function
|
|
797
|
+
`}function AX(e){let t=[];for(let n of e.filters){let e=$`
|
|
798
798
|
<filterColumn ${Z([[`colId`,n.colId]])}>
|
|
799
|
-
${
|
|
799
|
+
${jX(n)}
|
|
800
800
|
</filterColumn>
|
|
801
|
-
`;t.push(e)}return t}function
|
|
801
|
+
`;t.push(e)}return t}function jX(e){let t=e.displayedValues.map(e=>$`<filter ${Z([[`val`,e]])}/>`);return $`
|
|
802
802
|
<filters ${Z(e.displayBlanks?[[`blank`,1]]:[])}>
|
|
803
803
|
${Q(t)}
|
|
804
804
|
</filters>
|
|
805
|
-
`}function
|
|
805
|
+
`}function MX(e,t){let n=un(e.range),r=[];for(let i of S(0,On(n).numberOfCols)){let a=T(n.left+i,n.top),o=t.cells[a]||`col${i}`,s=[[`id`,i+1],[`name`,o]];if(e.config.totalRow){let e=T(n.left+i,n.bottom);t.cells[e]?.startsWith(`=`)&&s.push([`totalsRowFunction`,`custom`])}r.push($`<tableColumn ${Z(s)}/>`)}return $`
|
|
806
806
|
<tableColumns ${Z([[`count`,r.length]])}>
|
|
807
807
|
${Q(r)}
|
|
808
808
|
</tableColumns>
|
|
809
|
-
`}function
|
|
809
|
+
`}function NX(e){return $`<tableStyleInfo ${Z([[`name`,e.config.styleId],[`showFirstColumn`,+!!e.config.firstColumn],[`showLastColumn`,+!!e.config.lastColumn],[`showRowStripes`,+!!e.config.bandedRows],[`showColumnStripes`,+!!e.config.bandedColumns]])}/>`}function PX(e){if(!Object.values(e).length)return $``;let t=[];for(let[n,r]of Object.entries(e)){let e=[[`min`,parseInt(n)+1],[`max`,parseInt(n)+1],[`width`,Zj(r.size||96)],[`customWidth`,1],[`hidden`,+!!r.isHidden]];r.outlineLevel&&e.push([`outlineLevel`,r.outlineLevel]),r.collapsed&&e.push([`collapsed`,1]),t.push($`
|
|
810
810
|
<col ${Z(e)}/>
|
|
811
811
|
`)}return $`
|
|
812
812
|
<cols>
|
|
813
813
|
${Q(t)}
|
|
814
814
|
</cols>
|
|
815
|
-
`}function
|
|
815
|
+
`}function FX(e,t,n){let r=[],i=new bF(yc(n.id,n.styles)),a=new bF(yc(n.id,n.borders)),o=new bF(yc(n.id,n.formats));for(let s=0;s<n.rowNumber;s++){let c=[[`r`,s+1]],l=n.rows[s]||{};l.size&&l.size!==23&&c.push([`ht`,Xj(l.size)],[`customHeight`,1]),l.isHidden&&c.push([`hidden`,1]),l.outlineLevel&&c.push([`outlineLevel`,l.outlineLevel]),l.collapsed&&c.push([`collapsed`,1]);let u=[];for(let r=0;r<n.colNumber;r++){let c=T(r,s),l=n.cells[c],d=n.cellValues[c],f={sheetId:n.id,col:r,row:s},p=i.get(f),m=o.get(f),h=a.get(f);if(l||p||m||h||d!==void 0){let i=[[`r`,c]],a=rM(e,eM(t,l,p,m,h));a&&i.push([`s`,a]);let o=[],f=$``;if(l?.startsWith(`=`)&&d!==void 0){let e=HY(l,d,n.formulaSpillRanges[c]??c);if(!e)continue;({attrs:o,node:f}=e)}else if(l&&nt(l)){let{label:t}=at(l);({attrs:o,node:f}=UY(t,e.sharedStrings))}else if(l&&l!==``){let i=IX(r,s,n),a=LX(r,s,n),c=!!(m&&ws(t.formats[m]));({attrs:o,node:f}=UY(l,e.sharedStrings,i||a||c))}i.push(...o),u.push($`<c ${Z(i)}>
|
|
816
816
|
${f}
|
|
817
817
|
</c>`)}}(u.length||l.size!==23||l.isHidden||l.outlineLevel||l.collapsed)&&r.push($`
|
|
818
818
|
<row ${Z(c)}>
|
|
@@ -822,7 +822,7 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
822
822
|
<sheetData>
|
|
823
823
|
${Q(r)}
|
|
824
824
|
</sheetData>
|
|
825
|
-
`}function
|
|
825
|
+
`}function IX(e,t,n){return n.tables.some(n=>{let r=un(n.range);return En(e,t,{...r,bottom:r.top})})}function LX(e,t,n){return n.tables.some(n=>{if(!n.config.totalRow)return!1;let r=un(n.range);return En(e,t,{...r,top:r.bottom})})}function RX(e,t,n){let r=t.sheets[n].cells,i=[];for(let a in r){let o=r[a];if(o&&nt(o)){let{label:r,url:s}=at(o);if(st(s)){let e=lt(s),n=t.sheets.find(t=>t.id===e),o=n?`${n.name}!A1`:A.InvalidReference,c=[[`display`,r],[`location`,o],[`ref`,a]];i.push($`
|
|
826
826
|
<hyperlink ${Z(c)}/>
|
|
827
827
|
`)}else{let t=[[`r:id`,aM(e.relsFiles,`xl/worksheets/_rels/sheet${n}.xml.rels`,{target:qs(s),type:uu.hyperlink,targetMode:`External`})],[`ref`,a]];i.push($`
|
|
828
828
|
<hyperlink ${Z(t)}/>
|
|
@@ -830,11 +830,11 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
830
830
|
<hyperlinks>
|
|
831
831
|
${Q(i)}
|
|
832
832
|
</hyperlinks>
|
|
833
|
-
`:$``}function
|
|
833
|
+
`:$``}function zX(e){if(e.length){let t=e.map(e=>$`<mergeCell ref="${e}" />`);return $`
|
|
834
834
|
<mergeCells count="${e.length}">
|
|
835
835
|
${Q(t)}
|
|
836
836
|
</mergeCells>
|
|
837
|
-
`}else return $``}function
|
|
837
|
+
`}else return $``}function BX(e){let t=e.panes,n=$``;if(t&&(t.xSplit||t.ySplit)){let e=T(t.xSplit,t.ySplit),r=t.xSplit?$`xSplit="${t.xSplit}"`:``,i=t.ySplit?$`ySplit="${t.ySplit}"`:``,a=t.xSplit?$`<selection pane="topRight"/>`:``,o=t.ySplit?$`<selection pane="bottomLeft"/>`:``,s=t.xSplit&&t.ySplit?$`<selection pane="bottomRight"/>`:``;n=$`
|
|
838
838
|
<pane
|
|
839
839
|
${r}
|
|
840
840
|
${i}
|
|
@@ -850,11 +850,11 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
850
850
|
${n}
|
|
851
851
|
</sheetView>
|
|
852
852
|
</sheetViews>
|
|
853
|
-
`}function
|
|
853
|
+
`}function VX(e){return e.color?$`
|
|
854
854
|
<sheetPr>
|
|
855
855
|
<tabColor ${Z([[`rgb`,V(e.color)]])} />
|
|
856
856
|
</sheetPr>
|
|
857
|
-
`:``}function
|
|
857
|
+
`:``}function HX(e){e=ZX(e),e=QX(e);let t=[],n=kN(e);return t.push(UX(e,n)),t.push(...WX(e,n)),t.push(KX(n)),t.push(qX(n.sharedStrings)),t.push(...JX(n.relsFiles)),t.push(YX(t)),t.push(XX()),{name:`my_spreadsheet.xlsx`,files:t}}function UX(e,t){let n=[[`xmlns`,ou.workbook],[`xmlns:r`,du]],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($`
|
|
858
858
|
<sheet ${Z(e)} />
|
|
859
859
|
`),aM(t.relsFiles,`xl/_rels/workbook.xml.rels`,{type:uu.sheet,target:`worksheets/sheet${n}.xml`})}return TN(DN($`
|
|
860
860
|
<workbook ${Z(n)}>
|
|
@@ -862,17 +862,17 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
862
862
|
${Q(r)}
|
|
863
863
|
</sheets>
|
|
864
864
|
</workbook>
|
|
865
|
-
`),`xl/workbook.xml`,`workbook`)}function
|
|
865
|
+
`),`xl/workbook.xml`,`workbook`)}function WX(e,t){let n=[],r=1;for(let[i,a]of Object.entries(e.sheets)){let o=[[`xmlns`,ou.worksheet],[`xmlns:r`,du]],s=[[`defaultRowHeight`,Xj(23)],[`defaultColWidth`,Zj(96)]],c=GX(a,i,r,t,n);r+=a.tables.length;let l=$``,u=[];for(let r of a.charts){let a=cM(r.id,t),o=aM(t.relsFiles,`xl/drawings/_rels/drawing${i}.xml.rels`,{target:`../charts/chart${a}.xml`,type:uu.chart});u.push(o),n.push(TN(vY(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=Bj[r];if(a===void 0)continue;let o=`image${uM(e.id)}.${a}`,s=aM(t.relsFiles,`xl/drawings/_rels/drawing${i}.xml.rels`,{target:`../media/${o}`,type:uu.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=aM(t.relsFiles,`xl/worksheets/_rels/sheet${i}.xml.rels`,{target:`../drawings/drawing${i}.xml`,type:uu.drawing});n.push(TN(mX(u,a,d,t),`xl/drawings/drawing${i}.xml`,`drawing`)),l=$`<drawing r:id="${e}" />`}let f=$`
|
|
866
866
|
<worksheet ${Z(o)}>
|
|
867
|
+
${VX(a)}
|
|
867
868
|
${BX(a)}
|
|
868
|
-
${zX(a)}
|
|
869
869
|
<sheetFormatPr ${Z(s)} />
|
|
870
|
-
${
|
|
871
|
-
${
|
|
872
|
-
${
|
|
873
|
-
${Q(
|
|
874
|
-
${Q(
|
|
875
|
-
${
|
|
870
|
+
${PX(a.cols)}
|
|
871
|
+
${FX(t,e,a)}
|
|
872
|
+
${zX(a.merges)}
|
|
873
|
+
${Q(YY(t.dxfs,a.conditionalFormats))}
|
|
874
|
+
${Q(cX(a.dataValidationRules))}
|
|
875
|
+
${RX(t,e,i)}
|
|
876
876
|
${l}
|
|
877
877
|
${c}
|
|
878
878
|
</worksheet>
|
|
@@ -898,38 +898,38 @@ You can download it directly instead.`,5),sticky:!1,type:`warning`});return}r=aw
|
|
|
898
898
|
</bk>
|
|
899
899
|
</cellMetadata>
|
|
900
900
|
</metadata>
|
|
901
|
-
`;return n.push(TN(DN(i),`xl/metadata.xml`,`metadata`)),aM(t.relsFiles,`xl/_rels/workbook.xml.rels`,{type:uu.sharedStrings,target:`sharedStrings.xml`}),aM(t.relsFiles,`xl/_rels/workbook.xml.rels`,{type:uu.styles,target:`styles.xml`}),aM(t.relsFiles,`xl/_rels/workbook.xml.rels`,{type:uu.metadata,target:`metadata.xml`}),n}function
|
|
901
|
+
`;return n.push(TN(DN(i),`xl/metadata.xml`,`metadata`)),aM(t.relsFiles,`xl/_rels/workbook.xml.rels`,{type:uu.sharedStrings,target:`sharedStrings.xml`}),aM(t.relsFiles,`xl/_rels/workbook.xml.rels`,{type:uu.styles,target:`styles.xml`}),aM(t.relsFiles,`xl/_rels/workbook.xml.rels`,{type:uu.metadata,target:`metadata.xml`}),n}function GX(e,t,n,r,i){let a=n;if(!e.tables.length)return new zA(``);let o=`xl/worksheets/_rels/sheet${t}.xml.rels`,s=[];for(let t of e.tables){let n=aM(r.relsFiles,o,{target:`../tables/table${a}.xml`,type:uu.table});i.push(TN(OX(t,a,e),`xl/tables/table${a}.xml`,`table`)),s.push($`<tablePart r:id="${n}" />`),a++}return $`
|
|
902
902
|
<tableParts count="${e.tables.length}">
|
|
903
903
|
${Q(s)}
|
|
904
904
|
</tableParts>
|
|
905
|
-
`}function
|
|
905
|
+
`}function KX(e){return TN(DN($`
|
|
906
906
|
<styleSheet ${Z([[`xmlns`,ou.styleSheet],[`xmlns:r`,du]])}>
|
|
907
|
-
${
|
|
908
|
-
${
|
|
909
|
-
${
|
|
910
|
-
${
|
|
911
|
-
${
|
|
912
|
-
${
|
|
907
|
+
${yX(e.numFmts)}
|
|
908
|
+
${xX(e.fonts)}
|
|
909
|
+
${SX(e.fills)}
|
|
910
|
+
${CX(e.borders)}
|
|
911
|
+
${EX(e.styles)}
|
|
912
|
+
${DX(e.dxfs)}
|
|
913
913
|
</styleSheet>
|
|
914
|
-
`),`xl/styles.xml`,`styles`)}function
|
|
914
|
+
`),`xl/styles.xml`,`styles`)}function qX(e){let t=[[`xmlns`,ou.sst],[`count`,e.length],[`uniqueCount`,e.length]],n=e.map(e=>e.trim()===e?$`<si><t>${e}</t></si>`:$`<si><t xml:space="preserve">${e}</t></si>`);return TN(DN($`
|
|
915
915
|
<sst ${Z(t)}>
|
|
916
916
|
${Q(n)}
|
|
917
917
|
</sst>
|
|
918
|
-
`),`xl/sharedStrings.xml`,`sharedStrings`)}function
|
|
918
|
+
`),`xl/sharedStrings.xml`,`sharedStrings`)}function JX(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($`
|
|
919
919
|
<Relationship ${Z(n)} />
|
|
920
920
|
`)}let r=$`
|
|
921
921
|
<Relationships xmlns="${ou.Relationships}">
|
|
922
922
|
${Q(e)}
|
|
923
923
|
</Relationships>
|
|
924
|
-
`;t.push(TN(DN(r),n.path))}return t}function
|
|
924
|
+
`;t.push(TN(DN(r),n.path))}return t}function YX(e){let t=[],n=Object.entries(Bj).map(([e,t])=>jN(t,e));for(let n of e)`contentType`in n&&n.contentType&&t.push(AN(`/`+n.path,lu[n.contentType]));return TN(DN($`
|
|
925
925
|
<Types xmlns="${ou.Types}">
|
|
926
926
|
${Q(Object.values(n))}
|
|
927
927
|
<Default ${Z([[`Extension`,`rels`],[`ContentType`,`application/vnd.openxmlformats-package.relationships+xml`]])} />
|
|
928
928
|
<Default ${Z([[`Extension`,`xml`],[`ContentType`,`application/xml`]])} />
|
|
929
929
|
${Q(t)}
|
|
930
930
|
</Types>
|
|
931
|
-
`),`[Content_Types].xml`)}function
|
|
931
|
+
`),`[Content_Types].xml`)}function XX(){let e=[[`Id`,`rId1`],[`Type`,uu.document],[`Target`,`xl/workbook.xml`]];return TN(DN($`
|
|
932
932
|
<Relationships xmlns="${ou.Relationships}">
|
|
933
933
|
<Relationship ${Z(e)} />
|
|
934
934
|
</Relationships>
|
|
935
|
-
`),`_rels/.rels`)}function XX(e){let t={},n=[];for(let r of e.sheets){let e=r.name.slice(0,31);e=zt(e,n,{compute:(e,t)=>e.slice(0,31-String(t).length)+t}),n.push(e),e!==r.name&&(t[r.name]=e,r.name=e)}if(!Object.keys(t).length)return e;let r=Object.keys(t).sort((e,t)=>t.length-e.length),i=JSON.stringify(e);for(let e of r){let n=RegExp(`'?${Ge(e)}'?!`,`g`);i=i.replaceAll(n,n=>{let r=t[e];return n.replace(e,r)})}return JSON.parse(i)}function ZX(e){for(let t of e.sheets)t.tables=t.tables.filter(e=>On(un(e.range)).numberOfRows>1);return e}var QX=class extends er{corePlugins=[];statefulUIPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;coreViewPluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},t={},n=[],r=new Gl,i=!1){let a=performance.now();console.debug(`##### Model creation #####`),super(),la(),n=hP(e,n);let o=sP(e,i);this.state=new fY,this.uuidGenerator=r,this.config=this.setupConfig(t),this.session=this.setupSession(o.revisionId),this.coreGetters={},this.range=new lY(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.coreGetters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.coreGetters.getRangeData=this.range.getRangeData.bind(this.range),this.coreGetters.getRangeDataFromXc=this.range.getRangeDataFromXc.bind(this.range),this.coreGetters.getRangeDataFromZone=this.range.getRangeDataFromZone.bind(this.range),this.coreGetters.getRangeFromRangeData=this.range.getRangeFromRangeData.bind(this.range),this.coreGetters.getRangeFromZone=this.range.getRangeFromZone.bind(this.range),this.coreGetters.recomputeRanges=this.range.recomputeRanges.bind(this.range),this.coreGetters.isRangeValid=this.range.isRangeValid.bind(this.range),this.coreGetters.extendRange=this.range.extendRange.bind(this.range),this.coreGetters.getRangesUnion=this.range.getRangesUnion.bind(this.range),this.coreGetters.removeRangesSheetPrefix=this.range.removeRangesSheetPrefix.bind(this.range),this.coreGetters.copyFormulaStringForSheet=this.range.copyFormulaStringForSheet.bind(this.range),this.getters={isReadonly:()=>this.config.mode===`readonly`||this.config.mode===`dashboard`,isDashboard:()=>this.config.mode===`dashboard`},this.selection=new dY(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.coreViewPluginConfig=this.setupCoreViewPluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(let e of uq.getAll())this.setupCorePlugin(e,o);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(n);for(let e of pq.getAll()){let t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(let e of fq.getAll()){let t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(let e of dq.getAll()){let t=this.setupUiPlugin(e);this.handlers.push(t),this.uiHandlers.push(t)}if(this.dispatch(`START`),this.selection.observe(this,{handleEvent:()=>this.trigger(`update`)}),this.setupSessionEvents(),this.joinSession(),t.snapshotRequested||e[`[Content_Types].xml`]&&!this.getters.isReadonly()){let e=performance.now();console.debug(`Snapshot requested`),this.session.snapshot(this.exportData()),console.debug(`Snapshot taken in`,performance.now()-e,`ms`)}console.debug(`Model created in`,performance.now()-a,`ms`),console.debug(`######`)}joinSession(){this.session.join(this.config.client)}async leaveSession(){let e=this.getters.isReadonly()?void 0:mt(()=>this.exportData());await this.session.leave(e)}setupUiPlugin(e){let t=new e(this.uiPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}for(let n of e.layers)this.renderers[n]||(this.renderers[n]=[]),this.renderers[n].push(t);return t}setupCoreViewPlugin(e){let t=new e(this.coreViewPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}return t}setupCorePlugin(e,t){let n=new e(this.corePluginConfig);for(let t of e.getters){if(!(t in n))throw Error(`Invalid getter name: ${t} for plugin ${n.constructor}`);if(t in this.coreGetters)throw Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=n[t].bind(n)}n.import(t),this.corePlugins.push(n),this.coreHandlers.push(n),this.handlers.push(n)}onRemoteRevisionReceived({commands:e}){for(let t of e){let e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new MK(oY({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:k(`Anonymous`).toString()},n=e.transportService||new dJ,r=e.mode===`readonly`||e.mode===`dashboard`;return{...e,mode:e.mode||`normal`,custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:r?new QJ(n):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(uo));return{...e,loadLocales:t}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,canDispatch:this.canDispatch,custom:this.config.custom,external:this.config.external}}setupCoreViewPluginConfig(){return{getters:this.getters,stateObserver:this.state,custom:this.config.custom,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,canDispatch:this.canDispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}checkDispatchAllowed(e){let t=Hs(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return t.some(e=>e!==`Success`)?new Ws(t.flat()):Ws.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($X(e,t));dispatch=(e,t)=>{let n=$X(e,t),r=this.status;if(this.getters.isReadonly()&&!Us(n))return new Ws(`Readonly`);if(!this.session.canApplyOptimisticUpdate())return new Ws(`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();Hs(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(Hs(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(Hs(n))throw Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,n)}return Ws.Success};dispatchFromCorePlugin=(e,t)=>{let n=$X(e,t),r=this.status;this.status=2;let i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,n),this.status=r,Ws.Success};dispatchToHandlers(e,t){let n=Hs(t);for(let r of e)!n&&r instanceof dW||r.beforeHandle(t);for(let r of e)!n&&r instanceof dW||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=SP();for(let t of this.handlers)t instanceof dW&&t.export(e);return e.revisionId=this.session.getRevisionId()||`START_REVISION`,e=b(e),e}updateMode(e){this.config.mode=e,this.trigger(`update`)}async exportXLSX(){this.dispatch(`EVALUATE_CELLS`);let e=wP();for(let t of this.handlers)t instanceof sb&&await t.exportForExcel(e);return e=b(e),VX(e)}};function $X(e,t={}){let n=b(t);return n.type=e,n}function eZ(e){return!WV.includes(e.horizontalGroupBy)||!WV.includes(e.verticalGroupBy)?`InvalidChartDefinition`:`Success`}var tZ=class e extends Af{dataSets;labelRange;background;type=`calendar`;showValues;colorScale;axesDesign;horizontalGroupBy;verticalGroupBy;legendPosition;missingValueColor;constructor(e,t,n){super(e,t,n),this.dataSets=td(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Zc(n,t,e.labelRange),this.background=e.background,this.showValues=e.showValues,this.colorScale=e.colorScale,this.axesDesign=e.axesDesign,this.horizontalGroupBy=e.horizontalGroupBy,this.verticalGroupBy=e.verticalGroupBy,this.legendPosition=e.legendPosition,this.missingValueColor=e.missingValueColor}static transformDefinition(e,t,n){return ad(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,cd,ld,eZ)}static getDefinitionFromContextCreation(e){let t=`left`;return e.legendPosition===`right`&&(t=`right`),{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,title:e.title||{text:``},type:`calendar`,labelRange:e.auxiliaryRange||void 0,showValues:e.showValues,axesDesign:e.axesDesign,legendPosition:t,horizontalGroupBy:`day_of_week`,verticalGroupBy:`month_number`}}getContextCreation(){let e=[{dataRange:this.getters.getRangeString(this.dataSets[0].dataRange,this.sheetId)}];return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(t){let n=Qu(this.sheetId,t,this.dataSets),r=$u(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,n||this.sheetId)}));return{type:`calendar`,background:this.background,dataSets:r,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,showValues:this.showValues,colorScale:this.colorScale,axesDesign:this.axesDesign,horizontalGroupBy:this.horizontalGroupBy,verticalGroupBy:this.verticalGroupBy,legendPosition:this.legendPosition,missingValueColor:this.missingValueColor}}getDefinitionForExcel(){}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=Zu(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function nZ(e,t){let n=e.getDefinition(),r=Hh(n,e.dataSets,e.labelRange,t),{labels:i,datasets:a}=Zd(n,r);return{chartJsConfig:{type:`calendar`,data:{labels:i,datasets:a},options:{...Vp,indexAxis:`x`,layout:Eg(n,r),scales:Pd(n,a),plugins:{title:Gg(n,t),legend:{display:!1},tooltip:Xg(n,r),chartShowValuesPlugin:Bg(n,r),chartColorScalePlugin:Fd(n,r)},chartBackground:n.background||`#FFFFFF`}},background:e.background||`#FFFFFF`}}var rZ=class e extends Af{dataSets;labelRange;background;legendPosition;aggregated;dataSetsHaveTitle;dataSetDesign;axesDesign;type=`combo`;showValues;hideDataMarkers;zoomable;constructor(e,t,n){super(e,t,n),this.dataSets=td(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Zc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues,this.hideDataMarkers=e.hideDataMarkers,this.zoomable=e.zoomable}static transformDefinition(e,t,n){return ad(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,cd,ld)}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId),type:this.dataSetDesign?.[t]?.type??(t?`line`:`bar`)});return{type:`combo`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,axesDesign:this.axesDesign,showValues:this.showValues,hideDataMarkers:this.hideDataMarkers,zoomable:this.zoomable,humanize:this.humanize}}getDefinitionForExcel(){let{dataSets:e,labelRange:t}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,ud(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),n=this.getDefinition();return{...n,backgroundColor:V(this.background||`#FFFFFF`),fontColor:V(od(this.background)),dataSets:e,labelRange:t,verticalAxis:fd(n)}}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=Zu(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}static getDefinitionFromContextCreation(e){let t=(e.range??[]).map((e,t)=>({...e,type:t?`line`:`bar`}));return{background:e.background,dataSets:t,dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},labelRange:e.auxiliaryRange||void 0,type:`combo`,axesDesign:e.axesDesign,showValues:e.showValues,hideDataMarkers:e.hideDataMarkers,zoomable:e.zoomable,humanize:e.humanize}}duplicateInDuplicatedSheet(t){let n=Qu(this.sheetId,t,this.dataSets),r=$u(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}};function iZ(e,t){let n=e.getDefinition(),r=zh(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`bar`,data:{labels:r.labels,datasets:nf(n,r)},options:{...Vp,layout:Tg(n,r),scales:Nd(n,r),plugins:{title:Gg(n,t),legend:Mg(n,r),tooltip:Yg(n,r),chartShowValuesPlugin:zg(n,r)}}},background:e.background||`#FFFFFF`}}var aZ=class e extends Af{dataSets;labelRange;background;legendPosition;aggregated;type=`funnel`;dataSetsHaveTitle;dataSetDesign;axesDesign;horizontal=!0;showValues;funnelColors;cumulative;constructor(e,t,n){super(e,t,n),this.dataSets=td(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Zc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues,this.horizontal=!0,this.funnelColors=e.funnelColors,this.cumulative=e.cumulative}static transformDefinition(e,t,n){return ad(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,cd,ld)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated??!1,legendPosition:`none`,title:e.title||{text:``},type:`funnel`,labelRange:e.auxiliaryRange||void 0,showValues:e.showValues,axesDesign:e.axesDesign,funnelColors:e.funnelColors,horizontal:!0,cumulative:e.cumulative,humanize:e.humanize}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(t){let n=Qu(this.sheetId,t,this.dataSets),r=$u(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`funnel`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,horizontal:this.horizontal,axesDesign:this.axesDesign,showValues:this.showValues,funnelColors:this.funnelColors,cumulative:this.cumulative,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=Zu(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function oZ(e,t){let n=e.getDefinition(),r=Jh(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`funnel`,data:{labels:r.labels,datasets:of(n,r)},options:{...Vp,indexAxis:`y`,layout:Tg(n,r),scales:Hd(n,r),plugins:{title:Gg(n,t),legend:{display:!1},tooltip:r_(n,r),chartShowValuesPlugin:zg(n,r)}}},background:e.background||`#FFFFFF`}}var sZ=class e extends Af{dataSets;labelRange;background;legendPosition;type=`geo`;dataSetsHaveTitle;dataSetDesign;colorScale;missingValueColor;region;constructor(e,t,n){super(e,t,n),this.dataSets=td(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Zc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.colorScale=e.colorScale,this.missingValueColor=e.missingValueColor,this.region=e.region}static transformDefinition(e,t,n){return ad(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,cd,ld)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`geo`,labelRange:e.auxiliaryRange||void 0,humanize:e.humanize}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(t){let n=Qu(this.sheetId,t,this.dataSets),r=$u(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`geo`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,colorScale:this.colorScale,missingValueColor:this.missingValueColor,region:this.region,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=Zu(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function cZ(e,t){let n=e.getDefinition(),r=qh(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`choropleth`,data:{datasets:af(n,r)},options:{...Vp,layout:Tg(n,r),scales:Vd(n,r),plugins:{title:Gg(n,t),tooltip:n_(n,r),legend:{display:!1}}}},background:e.background||`#FFFFFF`}}var lZ=class e extends Af{dataSets;labelRange;background;legendPosition;aggregated;type=`pyramid`;dataSetsHaveTitle;dataSetDesign;axesDesign;horizontal=!0;stacked=!0;showValues;constructor(e,t,n){super(e,t,n),this.dataSets=td(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Zc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues}static transformDefinition(e,t,n){return ad(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,cd,ld)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`pyramid`,labelRange:e.auxiliaryRange||void 0,axesDesign:e.axesDesign,horizontal:!0,stacked:!0,showValues:e.showValues,humanize:e.humanize}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(t){let n=Qu(this.sheetId,t,this.dataSets),r=$u(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`pyramid`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,axesDesign:this.axesDesign,horizontal:!0,stacked:!0,showValues:this.showValues,humanize:this.humanize}}getDefinitionForExcel(e){let{dataSets:t,labelRange:n}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,ud(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),r=this.getDefinition(),{dataSetsValues:i}=Uh(r,this.dataSets,this.labelRange,e),a=Math.max(...i.map(e=>Math.max(...e.data.map(Math.abs))));return{...r,horizontal:!0,backgroundColor:V(this.background||`#FFFFFF`),fontColor:V(od(this.background)),dataSets:t,labelRange:n,verticalAxis:fd(r),maxValue:a}}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=Zu(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function uZ(e,t){let n=e.getDefinition(),r=Uh(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`bar`,data:{labels:r.labels,datasets:Xd(n,r)},options:{...Vp,indexAxis:`y`,layout:Tg(n,r),scales:zd(n,r),plugins:{title:Gg(n,t),legend:Og(n,r),tooltip:e_(n,r),chartShowValuesPlugin:Hg(n,r)}}},background:e.background||`#FFFFFF`}}var dZ=class e extends Af{dataSets;labelRange;background;legendPosition;stacked;aggregated;type=`radar`;dataSetsHaveTitle;dataSetDesign;fillArea;showValues;hideDataMarkers;constructor(e,t,n){super(e,t,n),this.dataSets=td(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Zc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.stacked=e.stacked,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.fillArea=e.fillArea,this.showValues=e.showValues,this.hideDataMarkers=e.hideDataMarkers}static transformDefinition(e,t,n){return ad(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,cd,ld)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,stacked:e.stacked??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`radar`,labelRange:e.auxiliaryRange||void 0,fillArea:e.fillArea??!1,showValues:e.showValues??!1,hideDataMarkers:e.hideDataMarkers,humanize:e.humanize}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(t){let n=Qu(this.sheetId,t,this.dataSets),r=$u(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`radar`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,stacked:this.stacked,aggregated:this.aggregated,fillArea:this.fillArea,showValues:this.showValues,hideDataMarkers:this.hideDataMarkers,humanize:this.humanize}}getDefinitionForExcel(){let{dataSets:e,labelRange:t}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,ud(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:V(this.background||`#FFFFFF`),fontColor:V(od(this.background)),dataSets:e,labelRange:t}}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=Zu(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function fZ(e,t){let n=e.getDefinition(),r=Kh(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`radar`,data:{labels:r.labels,datasets:rf(n,r)},options:{...Vp,layout:Tg(n,r),scales:Bd(n,r),plugins:{title:Gg(n,t),legend:Pg(n,r),tooltip:t_(n,r),chartShowValuesPlugin:zg(n,r)}}},background:e.background||`#FFFFFF`}}var pZ=class e extends Af{dataSets;labelRange;background;legendPosition;type=`sunburst`;dataSetsHaveTitle;showValues;showLabels;valuesDesign;groupColors;pieHolePercentage;constructor(e,t,n){super(e,t,n),this.dataSets=td(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Zc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.showValues=e.showValues,this.showLabels=e.showLabels,this.valuesDesign=e.valuesDesign,this.groupColors=e.groupColors,this.pieHolePercentage=e.pieHolePercentage}static transformDefinition(e,t,n){return ad(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,cd,ld)}static getDefinitionFromContextCreation(e){let t=[];return e.hierarchicalRanges?.length?t.push(...e.hierarchicalRanges):e.auxiliaryRange&&t.push({...e.range?.[0],dataRange:e.auxiliaryRange}),{background:e.background,dataSets:t,dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`sunburst`,labelRange:e.range?.[0]?.dataRange,showValues:e.showValues,showLabels:e.showLabels,valuesDesign:e.valuesDesign,groupColors:e.groupColors,humanize:e.humanize}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getContextCreation(){let e=this.dataSets.at(-1)?.dataRange;return{...this,range:this.labelRange?[{dataRange:this.getters.getRangeString(this.labelRange,this.sheetId)}]:[],auxiliaryRange:e?this.getters.getRangeString(e,this.sheetId):void 0,hierarchicalRanges:this.dataSets.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,this.sheetId)}))}}getDefinitionWithSpecificDataSets(e,t,n){return{type:`sunburst`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,n||this.sheetId)})),legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,showValues:this.showValues,showLabels:this.showLabels,valuesDesign:this.valuesDesign,groupColors:this.groupColors,pieHolePercentage:this.pieHolePercentage,humanize:this.humanize}}duplicateInDuplicatedSheet(t){let n=Qu(this.sheetId,t,this.dataSets),r=$u(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinitionForExcel(){}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=Zu(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function mZ(e,t){let n=e.getDefinition(),r=Yh(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`doughnut`,data:{datasets:cf(n,r)},options:{cutout:e.pieHolePercentage===void 0?`25%`:`${e.pieHolePercentage}%`,...Vp,layout:Tg(n,r),plugins:{title:Gg(n,t),legend:Fg(n,r),tooltip:i_(n,r),sunburstLabelsPlugin:Vg(n,r),sunburstHoverPlugin:{enabled:!0}}}},background:e.background||`#FFFFFF`}}var hZ=class e extends Af{static defaults={background:oe,legendPosition:`top`,dataSetsHaveTitle:!1,showHeaders:!0,headersColor:`#000000`};dataSets;labelRange;background;legendPosition;type=`treemap`;dataSetsHaveTitle;showHeaders;headerDesign;showValues;showLabels;valuesDesign;coloringOptions;constructor(e,t,n){super(e,t,n),this.dataSets=td(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Zc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.showHeaders=e.showHeaders,this.headerDesign=e.headerDesign,this.showValues=e.showValues,this.showLabels=e.showLabels,this.valuesDesign=e.valuesDesign,this.coloringOptions=e.coloringOptions}static transformDefinition(e,t,n){return ad(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,cd,ld)}static getDefinitionFromContextCreation(e){let t=[];return e.hierarchicalRanges?.length?t.push(...e.hierarchicalRanges):e.auxiliaryRange&&t.push({...e.range?.[0],dataRange:e.auxiliaryRange}),{background:e.background,dataSets:t,dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`treemap`,labelRange:e.range?.[0]?.dataRange,showValues:e.showValues,showHeaders:e.showHeaders,headerDesign:e.headerDesign,showLabels:e.showLabels,valuesDesign:e.valuesDesign,coloringOptions:e.treemapColoringOptions,humanize:e.humanize}}getContextCreation(){let e=this.dataSets.at(-1)?.dataRange;return{...this,range:this.labelRange?[{dataRange:this.getters.getRangeString(this.labelRange,this.sheetId)}]:[],auxiliaryRange:e?this.getters.getRangeString(e,this.sheetId):void 0,hierarchicalRanges:this.dataSets.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,this.sheetId)}))}}duplicateInDuplicatedSheet(t){let n=Qu(this.sheetId,t,this.dataSets),r=$u(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,n||this.sheetId)}));return{type:`treemap`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,showValues:this.showValues,showHeaders:this.showHeaders,headerDesign:this.headerDesign,showLabels:this.showLabels,valuesDesign:this.valuesDesign,coloringOptions:this.coloringOptions,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=Zu(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function gZ(e,t){let n=e.getDefinition(),r=Yh(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`treemap`,data:{labels:r.labels,datasets:pf(n,r)},options:{...Vp,layout:Tg(n,r),plugins:{title:Gg(n,t),legend:{display:!1},tooltip:a_(n,r)}}},background:e.background||`#FFFFFF`}}f_.add(`bar`,{match:e=>e===`bar`,createChart:(e,t,n)=>new u_(e,t,n),getChartRuntime:d_,validateChartDefinition:u_.validateChartDefinition,transformDefinition:u_.transformDefinition,getChartDefinitionFromContextCreation:u_.getDefinitionFromContextCreation,sequence:10}),f_.add(`combo`,{match:e=>e===`combo`,createChart:(e,t,n)=>new rZ(e,t,n),getChartRuntime:iZ,validateChartDefinition:rZ.validateChartDefinition,transformDefinition:rZ.transformDefinition,getChartDefinitionFromContextCreation:rZ.getDefinitionFromContextCreation,sequence:15}),f_.add(`line`,{match:e=>e===`line`,createChart:(e,t,n)=>new k_(e,t,n),getChartRuntime:A_,validateChartDefinition:k_.validateChartDefinition,transformDefinition:k_.transformDefinition,getChartDefinitionFromContextCreation:k_.getDefinitionFromContextCreation,sequence:20}),f_.add(`pie`,{match:e=>e===`pie`,createChart:(e,t,n)=>new j_(e,t,n),getChartRuntime:M_,validateChartDefinition:j_.validateChartDefinition,transformDefinition:j_.transformDefinition,getChartDefinitionFromContextCreation:j_.getDefinitionFromContextCreation,sequence:30}),f_.add(`scorecard`,{match:e=>e===`scorecard`,createChart:(e,t,n)=>new Bf(e,t,n),getChartRuntime:Hf,validateChartDefinition:Bf.validateChartDefinition,transformDefinition:Bf.transformDefinition,getChartDefinitionFromContextCreation:Bf.getDefinitionFromContextCreation,sequence:40}),f_.add(`gauge`,{match:e=>e===`gauge`,createChart:(e,t,n)=>new C_(e,t,n),getChartRuntime:w_,validateChartDefinition:C_.validateChartDefinition,transformDefinition:C_.transformDefinition,getChartDefinitionFromContextCreation:C_.getDefinitionFromContextCreation,sequence:50}),f_.add(`scatter`,{match:e=>e===`scatter`,createChart:(e,t,n)=>new lH(e,t,n),getChartRuntime:uH,validateChartDefinition:lH.validateChartDefinition,transformDefinition:lH.transformDefinition,getChartDefinitionFromContextCreation:lH.getDefinitionFromContextCreation,sequence:60}),f_.add(`waterfall`,{match:e=>e===`waterfall`,createChart:(e,t,n)=>new N_(e,t,n),getChartRuntime:P_,validateChartDefinition:N_.validateChartDefinition,transformDefinition:N_.transformDefinition,getChartDefinitionFromContextCreation:N_.getDefinitionFromContextCreation,sequence:70}),f_.add(`pyramid`,{match:e=>e===`pyramid`,createChart:(e,t,n)=>new lZ(e,t,n),getChartRuntime:uZ,validateChartDefinition:lZ.validateChartDefinition,transformDefinition:lZ.transformDefinition,getChartDefinitionFromContextCreation:lZ.getDefinitionFromContextCreation,sequence:80,dataSeriesLimit:2}),f_.add(`radar`,{match:e=>e===`radar`,createChart:(e,t,n)=>new dZ(e,t,n),getChartRuntime:fZ,validateChartDefinition:dZ.validateChartDefinition,transformDefinition:dZ.transformDefinition,getChartDefinitionFromContextCreation:dZ.getDefinitionFromContextCreation,sequence:80}),f_.add(`geo`,{match:e=>e===`geo`,createChart:(e,t,n)=>new sZ(e,t,n),getChartRuntime:cZ,validateChartDefinition:sZ.validateChartDefinition,transformDefinition:sZ.transformDefinition,getChartDefinitionFromContextCreation:sZ.getDefinitionFromContextCreation,sequence:90,dataSeriesLimit:1}),f_.add(`funnel`,{match:e=>e===`funnel`,createChart:(e,t,n)=>new aZ(e,t,n),getChartRuntime:oZ,validateChartDefinition:aZ.validateChartDefinition,transformDefinition:aZ.transformDefinition,getChartDefinitionFromContextCreation:aZ.getDefinitionFromContextCreation,sequence:100,dataSeriesLimit:1}),f_.add(`sunburst`,{match:e=>e===`sunburst`,createChart:(e,t,n)=>new pZ(e,t,n),getChartRuntime:mZ,validateChartDefinition:pZ.validateChartDefinition,transformDefinition:pZ.transformDefinition,getChartDefinitionFromContextCreation:pZ.getDefinitionFromContextCreation,sequence:30}),f_.add(`treemap`,{match:e=>e===`treemap`,createChart:(e,t,n)=>new hZ(e,t,n),getChartRuntime:gZ,validateChartDefinition:hZ.validateChartDefinition,transformDefinition:hZ.transformDefinition,getChartDefinitionFromContextCreation:hZ.getDefinitionFromContextCreation,sequence:100}),f_.add(`calendar`,{match:e=>e===`calendar`,createChart:(e,t,n)=>new tZ(e,t,n),getChartRuntime:(e,t)=>nZ(e,t),validateChartDefinition:tZ.validateChartDefinition,transformDefinition:tZ.transformDefinition,getChartDefinitionFromContextCreation:tZ.getDefinitionFromContextCreation,sequence:110,dataSeriesLimit:1}),K_.add(`line`,{matcher:e=>e.type===`line`&&!e.stacked&&!e.fillArea,displayName:k(`Line`),chartType:`line`,chartSubtype:`line`,subtypeDefinition:{stacked:!1,fillArea:!1},category:`line`,preview:`o-spreadsheet-ChartPreview.LINE_CHART`}).add(`stacked_line`,{matcher:e=>e.type===`line`&&!e.fillArea&&!!e.stacked,displayName:k(`Stacked Line`),chartType:`line`,chartSubtype:`stacked_line`,subtypeDefinition:{stacked:!0,fillArea:!1},category:`line`,preview:`o-spreadsheet-ChartPreview.STACKED_LINE_CHART`}).add(`area`,{matcher:e=>e.type===`line`&&!e.stacked&&!!e.fillArea,displayName:k(`Area`),chartType:`line`,chartSubtype:`area`,subtypeDefinition:{stacked:!1,fillArea:!0},category:`area`,preview:`o-spreadsheet-ChartPreview.AREA_CHART`}).add(`stacked_area`,{matcher:e=>e.type===`line`&&e.stacked&&!!e.fillArea,displayName:k(`Stacked Area`),chartType:`line`,chartSubtype:`stacked_area`,subtypeDefinition:{stacked:!0,fillArea:!0},category:`area`,preview:`o-spreadsheet-ChartPreview.STACKED_AREA_CHART`}).add(`scatter`,{displayName:k(`Scatter`),chartType:`scatter`,chartSubtype:`scatter`,category:`misc`,preview:`o-spreadsheet-ChartPreview.SCATTER_CHART`}).add(`column`,{matcher:e=>e.type===`bar`&&!e.stacked&&!e.horizontal,displayName:k(`Column`),chartType:`bar`,chartSubtype:`column`,subtypeDefinition:{stacked:!1,horizontal:!1},category:`column`,preview:`o-spreadsheet-ChartPreview.COLUMN_CHART`}).add(`stacked_column`,{matcher:e=>e.type===`bar`&&e.stacked&&!e.horizontal,displayName:k(`Stacked Column`),chartType:`bar`,chartSubtype:`stacked_column`,subtypeDefinition:{stacked:!0,horizontal:!1},category:`column`,preview:`o-spreadsheet-ChartPreview.STACKED_COLUMN_CHART`}).add(`bar`,{matcher:e=>e.type===`bar`&&!e.stacked&&!!e.horizontal,displayName:k(`Bar`),chartType:`bar`,chartSubtype:`bar`,subtypeDefinition:{horizontal:!0,stacked:!1},category:`bar`,preview:`o-spreadsheet-ChartPreview.BAR_CHART`}).add(`stacked_bar`,{matcher:e=>e.type===`bar`&&e.stacked&&!!e.horizontal,displayName:k(`Stacked Bar`),chartType:`bar`,chartSubtype:`stacked_bar`,subtypeDefinition:{horizontal:!0,stacked:!0},category:`bar`,preview:`o-spreadsheet-ChartPreview.STACKED_BAR_CHART`}).add(`combo`,{displayName:k(`Combo`),chartSubtype:`combo`,chartType:`combo`,category:`line`,preview:`o-spreadsheet-ChartPreview.COMBO_CHART`}).add(`pie`,{matcher:e=>e.type===`pie`&&!e.isDoughnut,displayName:k(`Pie`),chartSubtype:`pie`,chartType:`pie`,subtypeDefinition:{isDoughnut:!1},category:`pie`,preview:`o-spreadsheet-ChartPreview.PIE_CHART`}).add(`doughnut`,{matcher:e=>e.type===`pie`&&!!e.isDoughnut,displayName:k(`Doughnut`),chartSubtype:`doughnut`,chartType:`pie`,subtypeDefinition:{isDoughnut:!0},category:`pie`,preview:`o-spreadsheet-ChartPreview.DOUGHNUT_CHART`}).add(`gauge`,{displayName:k(`Gauge`),chartSubtype:`gauge`,chartType:`gauge`,category:`misc`,preview:`o-spreadsheet-ChartPreview.GAUGE_CHART`}).add(`scorecard`,{displayName:k(`Scorecard`),chartSubtype:`scorecard`,chartType:`scorecard`,category:`misc`,preview:`o-spreadsheet-ChartPreview.SCORECARD_CHART`}).add(`waterfall`,{displayName:k(`Waterfall`),chartSubtype:`waterfall`,chartType:`waterfall`,category:`misc`,preview:`o-spreadsheet-ChartPreview.WATERFALL_CHART`}).add(`pyramid`,{displayName:k(`Population Pyramid`),chartSubtype:`pyramid`,chartType:`pyramid`,category:`misc`,preview:`o-spreadsheet-ChartPreview.POPULATION_PYRAMID_CHART`}).add(`radar`,{matcher:e=>e.type===`radar`&&!e.fillArea,displayName:k(`Radar`),chartSubtype:`radar`,chartType:`radar`,subtypeDefinition:{fillArea:!1},category:`misc`,preview:`o-spreadsheet-ChartPreview.RADAR_CHART`}).add(`filled_radar`,{matcher:e=>e.type===`radar`&&!!e.fillArea,displayName:k(`Filled Radar`),chartType:`radar`,chartSubtype:`filled_radar`,subtypeDefinition:{fillArea:!0},category:`misc`,preview:`o-spreadsheet-ChartPreview.FILLED_RADAR_CHART`}).add(`geo`,{displayName:k(`Geo Chart`),chartSubtype:`geo`,chartType:`geo`,category:`misc`,preview:`o-spreadsheet-ChartPreview.GEO_CHART`}).add(`funnel`,{displayName:k(`Funnel`),chartSubtype:`funnel`,chartType:`funnel`,category:`misc`,preview:`o-spreadsheet-ChartPreview.FUNNEL_CHART`}).add(`sunburst`,{matcher:e=>e.type===`sunburst`,displayName:k(`Sunburst`),chartSubtype:`sunburst`,chartType:`sunburst`,category:`hierarchical`,preview:`o-spreadsheet-ChartPreview.SUNBURST_CHART`}).add(`treemap`,{matcher:e=>e.type===`treemap`,displayName:k(`Tree Map`),chartType:`treemap`,chartSubtype:`treemap`,category:`hierarchical`,preview:`o-spreadsheet-ChartPreview.TREE_MAP_CHART`}).add(`calendar`,{displayName:k(`Calendar`),chartSubtype:`calendar`,chartType:`calendar`,category:`misc`,preview:`o-spreadsheet-ChartPreview.CALENDAR_CHART`});var _Z=class extends DG{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(E(t))}executeQueuedChanges(e){for(let t in this.queuedBordersToAdd){let n=this.queuedBordersToAdd[t],r=JSON.parse(t),i=Qt(n,[]);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,target:i,border:r})}this.queuedBordersToAdd={}}},vZ=class extends EG{copy(e){}},yZ=class extends vZ{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!==`carousel`)return;let r={...n},i=this.getters.getCarousel(e.figureId),a={};for(let e of i.items)if(e.type===`chart`){let n=this.getters.getChart(e.chartId);if(!n)throw Error(`No chart for the given id: ${e.chartId}`);a[e.chartId]=n.copyInSheetId(t)}return{figureId:e.figureId,copiedFigure:r,copiedCarousel:i,copiedCharts:a,copiedSheetId:t}}getPasteTarget(e){return{zones:[],figureId:new Gl().smallUuid(),sheetId:e}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=e.sheetId,{width:o,height:s}=t.copiedFigure,c=this.getters.getMaxAnchorOffset(a,s,o),{left:l,top:u}=r[0],d={x:0,y:0};l>c.col&&(l=c.col,d.x=c.offset.x),u>c.row&&(u=c.row,d.y=c.offset.y),this.dispatch(`CREATE_CAROUSEL`,{figureId:i,sheetId:a,definition:{items:[]},col:l,row:u,offset:d,size:{height:s,width:o}});let f=new Gl,p=b(t.copiedCarousel.items);for(let e of p){if(e.type!==`chart`)continue;let n=t.copiedCharts[e.chartId],r=f.smallUuid(),o=n.copyInSheetId(a).getDefinition();this.dispatch(`CREATE_CHART`,{figureId:i,chartId:r,sheetId:a,definition:o}),e.chartId=r}this.dispatch(`UPDATE_CAROUSEL`,{sheetId:a,figureId:i,definition:{...t.copiedCarousel,items:p}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.copiedSheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},bZ=class extends vZ{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.getChartFromFigureId(e.figureId);if(!i)throw Error(`No chart for the given id: ${e.figureId}`);let a=i.copyInSheetId(t);return{figureId:e.figureId,copiedFigure:r,copiedChart:a}}getPasteTarget(e,t,n,r){return{zones:[],figureId:new Gl().smallUuid(),sheetId:e}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=e.sheetId,{width:o,height:s}=t.copiedFigure,c=t.copiedChart.copyInSheetId(a),l=this.getters.getMaxAnchorOffset(a,s,o),{left:u,top:d}=r[0],f={x:0,y:0};u>l.col&&(u=l.col,f.x=l.offset.x),d>l.row&&(d=l.row,f.y=l.offset.y),this.dispatch(`CREATE_CHART`,{figureId:i,chartId:new Gl().smallUuid(),sheetId:a,definition:c.getDefinition(),col:u,row:d,offset:f,size:{height:s,width:o}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.copiedChart.sheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},xZ=class extends DG{uuidGenerator=new Gl;queuedChanges={};copy(e){if(!e.zones.length)return;let{rowsIndexes:t,columnsIndexes:n}=e,r=e.sheetId,i=[];for(let e of t){let t=[];for(let i of n){let n=Array.from(this.getters.getRulesByCell(r,i,e));t.push({position:{col:i,row:e,sheetId:r},rules:n})}i.push(t)}return{cfRules:i}}paste(e,t,n){if(this.queuedChanges={},n.pasteOption===`asValue`)return;let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t):this.pasteFromCopy(i,r,t.cfRules,n),this.executeQueuedChanges()}pasteFromCut(e,t,n){let r=t[0];this.pasteZone(e,r.left,r.top,n.cfRules,{isCutOperation:!0})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){let o={col:t+r,row:n+a,sheetId:e};this.pasteCf(s,o,i?.isCutOperation)}}pasteCf(e,t,n){if(e?.rules&&e.rules.length>0){let r=E(e.position),i=E(t);for(let a of e.rules){let o=[];if(n&&o.push(r),e.position.sheetId===t.sheetId)this.adaptCFRules(e.position.sheetId,a,[i],o);else{this.adaptCFRules(e.position.sheetId,a,[],o);let n=this.getCFToCopyTo(t.sheetId,a);this.adaptCFRules(t.sheetId,n,[i],[])}}}}adaptCFRules(e,t,n,r){this.queuedChanges[e]||(this.queuedChanges[e]=[]);let i=this.queuedChanges[e].find(e=>e.cf.id===t.id);i?(i.toAdd.push(...n),i.toRemove.push(...r)):this.queuedChanges[e].push({toAdd:n,toRemove:r,cf:t})}executeQueuedChanges(){for(let e in this.queuedChanges)for(let{toAdd:t,toRemove:n,cf:r}of this.queuedChanges[e]){let i=this.getters.getAdaptedCfRanges(e,r,t,n);if(i){if(i.length===0){this.dispatch(`REMOVE_CONDITIONAL_FORMAT`,{id:r.id,sheetId:e});continue}this.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{id:r.id,rule:r.rule,stopIfTrue:r.stopIfTrue},ranges:i,sheetId:e})}}}getCFToCopyTo(e,t){let n=this.getters.getConditionalFormats(e).find(e=>e.stopIfTrue===t.stopIfTrue&&w(e.rule,t.rule)),r=this.queuedChanges[e];return!n&&r&&(n=r.find(e=>e.cf.stopIfTrue===t.stopIfTrue&&w(e.cf.rule,t.rule))?.cf),n||{...t,id:this.uuidGenerator.smallUuid(),ranges:[]}}},SZ=class extends DG{uuidGenerator=new Gl;queuedChanges={};copy(e){let{rowsIndexes:t,columnsIndexes:n}=e,r=e.sheetId,i=[];for(let e of t){let t=[];for(let i of n){let n={sheetId:r,col:i,row:e},a=this.getters.getValidationRuleForCell(n);t.push({position:n,rule:a})}i.push(t)}return{dvRules:i}}paste(e,t,n){if(this.queuedChanges={},n.pasteOption)return;let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t):this.pasteFromCopy(i,r,t.dvRules),this.executeQueuedChanges()}pasteFromCut(e,t,n){let r=t[0];this.pasteZone(e,r.left,r.top,n.dvRules,{isCutOperation:!0})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){let o={col:t+r,row:n+a,sheetId:e};this.pasteDataValidation(s,o,i?.isCutOperation)}}pasteDataValidation(e,t,n){if(e){let r=E(t),i=E(e.position),a=e.rule;if(!a){let e=this.getters.getValidationRuleForCell(t);e&&this.adaptDataValidationRule(t.sheetId,e,[],[r]);return}let o=[];if(n&&o.push(i),e.position.sheetId===t.sheetId){let n=this.getDataValidationRuleToCopyTo(t.sheetId,a,!1);this.adaptDataValidationRule(e.position.sheetId,n,[r],o)}else{let n=this.getters.getValidationRuleForCell(e.position);n&&this.adaptDataValidationRule(e.position.sheetId,n,[],o);let i=this.getDataValidationRuleToCopyTo(t.sheetId,a);this.adaptDataValidationRule(t.sheetId,i,[r],[])}}}getDataValidationRuleToCopyTo(e,t,n=!0){let r=this.getters.getDataValidationRules(e).find(e=>w(t.criterion,e.criterion)&&t.isBlocking===e.isBlocking),i=this.queuedChanges[e];return!r&&i&&(r=i.find(e=>w(t.criterion,e.rule.criterion)&&t.isBlocking===e.rule.isBlocking)?.rule),r||{...t,id:n?this.uuidGenerator.smallUuid():t.id,ranges:[]}}adaptDataValidationRule(e,t,n,r){this.queuedChanges[e]||(this.queuedChanges[e]=[]);let i=this.queuedChanges[e].find(e=>e.rule.id===t.id);i?(i.toAdd.push(...n),i.toRemove.push(...r)):this.queuedChanges[e].push({toAdd:n,toRemove:r,rule:t})}executeQueuedChanges(){for(let e in this.queuedChanges)for(let{toAdd:t,toRemove:n,rule:r}of this.queuedChanges[e]){let i=Qt([...Qt(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})}}},CZ=class extends vZ{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);let r={...n};if(n.tag!==`image`)return;let i=b(this.getters.getImage(e.figureId));return{figureId:e.figureId,copiedFigure:r,copiedImage:i,sheetId:t}}getPasteTarget(e,t,n,r){return{sheetId:e,zones:[],figureId:new Gl().smallUuid()}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=this.getters.getActiveSheetId(),{width:o,height:s}=t.copiedFigure,c=b(t.copiedImage),l=this.getters.getMaxAnchorOffset(a,s,o),{left:u,top:d}=r[0],f={x:0,y:0};u>l.col&&(u=l.col,f.x=l.offset.x),d>l.row&&(d=l.row,f.y=l.offset.y),this.dispatch(`CREATE_IMAGE`,{figureId:i,sheetId:a,col:u,row:d,offset:f,size:{height:s,width:o},definition:c}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.sheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},wZ=class extends DG{copy(e){let t=this.getters.getActiveSheetId(),{rowsIndexes:n,columnsIndexes:r}=e,i=[];for(let e of n){let n=[];for(let i of r){let r={col:i,row:e,sheetId:t};n.push(this.getters.getMerge(r))}i.push(n)}return{merges:i,sheetId:t}}paste(e,t,n){if(n.isCutOperation){let e=t.merges.flat().filter(C);this.dispatch(`REMOVE_MERGE`,{sheetId:t.sheetId,target:e})}this.pasteFromCopy(e.sheetId,e.zones,t.merges,n)}pasteZone(e,t,n,r){for(let[i,a]of r.entries())for(let[r,o]of a.entries()){let a={col:t+r,row:n+i,sheetId:e};this.pasteMerge(o,a)}}pasteMerge(e,t){if(!e||this.getters.isInMerge(t))return;let{sheetId:n,col:r,row:i}=t;this.dispatch(`ADD_MERGE`,{sheetId:n,force:!0,target:[{left:r,top:i,right:r+e.right-e.left,bottom:i+e.bottom-e.top}]})}},TZ=class extends DG{copy(e){return{zones:e.clippedZones,sheetId:e.sheetId}}paste(e,t,n){if(n.isCutOperation){let n=e.zones[0];this.dispatch(`MOVE_RANGES`,{target:t.zones,sheetId:t.sheetId,sheetName:this.getters.getSheetName(t.sheetId),targetSheetId:e.sheetId,col:n.left,row:n.top})}}},EZ=class extends DG{isPasteAllowed(e,t,n,r){if(!(`cells`in n))return`Success`;let{xSplit:i,ySplit:a}=this.getters.getPaneDivisions(e);return Un(rA(t,n.cells),i,a)?`FrozenPaneOverlap`:`Success`}},DZ=class extends DG{copy(e){let t=e.sheetId;if(e.zones.length===0)return;let n=[],r=0;for(let i of Ze(e.columnsIndexes)){let a=0;for(let o of Ze(e.rowsIndexes)){let e={left:i[0],right:i[i.length-1],top:o[0],bottom:o[o.length-1]};n.push(...this.getters.getZoneStyles(t,e).map(t=>({zone:{left:t.zone.left-e.left+r,right:t.zone.right&&t.zone.right-e.left+r,top:t.zone.top-e.top+a,bottom:t.zone.bottom&&t.zone.bottom-e.top+a},style:t.style}))),a+=o.length}r+=i.length}return{styles:n,width:e.columnsIndexes.length,height:e.rowsIndexes.length}}paste(e,t,n){let r=e.sheetId;if(n.pasteOption===`asValue`)return;let i=e.zones;if(n.isCutOperation){let{left:e,top:n}=i[0];this.pasteStyleZone(r,e,n,t.styles)}else for(let e of i)for(let n of nA(e,t.width,t.height))this.pasteStyleZone(r,n.left,n.top,t.styles)}pasteStyleZone(e,t,n,r){for(let i of r){let r={left:i.zone.left+t,right:i.zone.right&&i.zone.right+t||i.zone.left+t,top:i.zone.top+n,bottom:i.zone.bottom&&i.zone.bottom+n||i.zone.top+n};this.dispatch(`SET_FORMATTING`,{sheetId:e,target:[r],style:i.style})}}},OZ=class extends DG{copy(e,t,n=`copyPaste`){let r=e.sheetId,{rowsIndexes:i,columnsIndexes:a,zones:o}=e,s=new Set,c=[];for(let e of i){let l=[];c.push(l);for(let c of a){let a={col:c,row:e,sheetId:r},u=this.getters.getTable(a);if(!u){l.push({});continue}let d=this.getters.getCoreTable(a),f=d?.range.zone,p;if(!s.has(u.id)&&d&&f&&o.some(e=>Dn(f,e))){s.add(u.id);let{numberOfRows:e}=On(f);for(let n=f.top;n<=f.bottom;n++)!t&&!i.includes(n)&&e--;let n=d.range,r=this.getters.extendRange(d.range,`ROW`,n.zone.top+e-1-n.zone.bottom);p={range:this.getters.getRangeData(r),config:d.config,type:d.type}}n!==`shiftCells`&&l.push({table:p,style:this.getTableStyleToCopy(a),isWholeTableCopied:s.has(u.id)})}}return{tableCells:c,sheetId:e.sheetId}}getTableStyleToCopy(e){let t=this.getters.getCellTableStyle(e),n=this.getters.getCellStyle(e),r=this.getters.getCellTableBorder(e),i=this.getters.getCellBorder(e);return{style:{...t,...bt(n)},border:{...r,...bt(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=On(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}))}};BB.figureHandlers.add(`chart`,bZ).add(`image`,CZ).add(`carousel`,yZ),BB.cellHandlers.add(`dataValidation`,SZ).add(`cell`,OG).add(`sheet`,EZ).add(`merge`,wZ).add(`border`,_Z).add(`table`,OZ).add(`conditionalFormat`,xZ).add(`references`,TZ).add(`style`,DZ);let kZ={},AZ={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:26,HEADER_WIDTH:48,DESKTOP_BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:96,DEFAULT_CELL_HEIGHT:23,SCROLLBAR_WIDTH:15},jZ={autoCompleteProviders:ak,autofillModifiersRegistry:AG,autofillRulesRegistry:jG,cellMenuRegistry:SR,colMenuRegistry:Bz,errorTypes:da,linkMenuRegistry:Qk,functionRegistry:yO,featurePluginRegistry:dq,iconsOnCellRegistry:lG,statefulUIPluginRegistry:fq,coreViewsPluginRegistry:pq,corePluginRegistry:uq,rowMenuRegistry:qz,sidePanelRegistry:tW,figureRegistry:Mv,chartSidePanelComponentRegistry:xH,chartComponentRegistry:sv,chartRegistry:f_,chartSubtypeRegistry:K_,topbarMenuRegistry:Wq,topbarComponentRegistry:uJ,clickableCellRegistry:bq,otRegistry:XG,inverseCommandRegistry:Cq,urlRegistry:Js,cellPopoverRegistry:Fv,numberFormatMenuRegistry:zq,repeatLocalCommandTransformRegistry:VK,repeatCommandTransformRegistry:BK,clipboardHandlersRegistries:BB,pivotRegistry:ZL,pivotTimeAdapterRegistry:Um,pivotSidePanelRegistry:FU,pivotNormalizationValueRegistry:xh,supportedPivotPositionalFormulaRegistry:sW,pivotToFunctionValueRegistry:Sh,migrationStepRegistry:nP,chartJsExtensionRegistry:ql},MZ={arg:G,isEvaluationError:M,toBoolean:F,toJsDate:I,toNumber:N,toString:P,toNormalizedPivotValue:_h,toFunctionPivotValue:yh,toXC:T,toZone:un,toUnboundedZone:ln,toCartesian:Zt,numberToLetters:Ht,lettersToNumber:Ut,UuidGenerator:Gl,formatValue:z,createCurrencyFormat:ls,ColorGenerator:ei,computeTextWidth:Dl,createEmptyWorkbookData:SP,createEmptySheet:xP,createEmptyExcelSheet:CP,rgbaToHex:jr,colorToRGBA:Mr,positionToZone:E,isDefined:C,isMatrix:xa,lazy:mt,genericRepeat:lJ,createAction:h,createActions:p,transformRangeData:$n,deepEquals:w,overlap:wn,union:bn,isInside:En,deepCopy:b,expandZoneOnInsertion:gn,reduceZoneOnDeletion:yn,unquote:Je,getMaxObjectId:lh,getFunctionsFromTokens:CU,getFirstPivotFunction:EU,getNumberOfPivotFunctions:DU,parseDimension:fh,isDateOrDatetimeField:ph,makeFieldProposal:OU,insertTokenAfterArgSeparator:AU,insertTokenAfterLeftParenthesis:jU,mergeContiguousZones:Xn,getPivotHighlights:GH,pivotTimeAdapter:Wm,UNDO_REDO_PIVOT_COMMANDS:CG,createPivotFormula:gh,areDomainArgsFieldsValid:hh,splitReference:Pc,sanitizeSheetName:Xe,getUniqueText:zt,isNumber:$i,isDateTime:xi,createCustomFields:Oh,schemeToColorScale:Mm,isDateTimeFormat:ns,jsDateToNumber:Fi,numberToJsDate:Ni,DateTime:O,parseFormat:Eo,isFormula:Bt},NZ={isMarkdownLink:nt,parseMarkdownLink:at,markdownLink:it,openLink:$s,urlRepresentation:Qs},PZ={Checkbox:Fk,Section:q,RoundColorPicker:bk,ChartDataSeries:TV,ChartErrorSection:EV,ChartLabelRange:DV,ChartTitle:jV,ChartPanel:TH,ChartFigure:Av,ChartJsComponent:kf,ClickableCellSortIcon:cW,ZoomableChartJsComponent:$_,Grid:oW,GridOverlay:KB,ScorecardChart:Cp,GaugeChartComponent:av,LineConfigPanel:iH,BarConfigPanel:kV,PieChartDesignPanel:sH,GenericChartConfigPanel:OV,ChartWithAxisDesignPanel:VV,GenericZoomableChartDesignPanel:HV,LineChartDesignPanel:aH,GaugeChartConfigPanel:QV,GaugeChartDesignPanel:$V,ScorecardChartConfigPanel:fH,ScorecardChartDesignPanel:pH,GeoChartDesignPanel:nH,RadarChartDesignPanel:cH,WaterfallChartDesignPanel:bH,ComboChartDesignPanel:YV,FunnelChartDesignPanel:ZV,SunburstChartDesignPanel:mH,TreeMapChartDesignPanel:yH,ChartTypePicker:CH,FigureComponent:Nv,MenuPopover:Dv,Popover:Cv,SelectionInput:kk,ValidationMessages:IB,AddDimensionButton:XH,PivotDimensionGranularity:QH,PivotDimensionOrder:$H,PivotDimension:ZH,PivotLayoutConfigurator:yU,PivotHTMLRenderer:uW,PivotDeferUpdate:qH,PivotTitleSection:bU,CogWheelMenu:SV,TextInput:gV,SidePanelCollapsible:Vv,RadioSelection:NV,GeoChartRegionSelectSection:eH,ChartDashboardMenu:Ov,FullScreenFigure:lW,NumberInput:LV,TopBar:JJ,Composer:PO},FZ={useDragAndDropListItems:Sk,useHighlights:OH,useHighlightsOnHover:DH},IZ={useStoreProvider:ar,DependencyContainer:tr,CellPopoverStore:Bk,ComposerFocusStore:_r,CellComposerStore:CB,FindAndReplaceStore:LH,HighlightStore:sk,DelayedHoveredCellStore:Pv,HoveredTableStore:UB,ModelStore:ur,NotificationStore:ck,RendererStore:mr,SelectionInputStore:Ok,SpreadsheetStore:hr,useStore:D,useLocalStore:or,SidePanelStore:rW,PivotSidePanelStore:NU,PivotMeasureDisplayPanelStore:UH,ClientFocusStore:Yz,GridRenderer:eV};function LZ(e,t){return yO.add(e,t),{addFunction:(e,t)=>LZ(e,t)}}let RZ={DEFAULT_LOCALE:R,HIGHLIGHT_COLOR:ee,PIVOT_TABLE_CONFIG:Le,ChartTerms:Yp,FIGURE_ID_SPLITTER:`??`,GRID_ICON_EDGE_LENGTH:17,GRID_ICON_MARGIN:2},zZ={...F_,...l_};e.AbstractCellClipboardHandler=DG,e.AbstractChart=Af,e.AbstractFigureClipboardHandler=vZ,e.CellErrorType=A,e.ClientDisconnectedError=jK,e.CommandResult=Ks,e.CorePlugin=dW,e.CoreViewPlugin=LW,e.DEFAULT_LOCALE=R,e.DEFAULT_LOCALES=uo,e.DispatchResult=Ws,e.EvaluationError=j,e.LocalTransportService=dJ,e.Model=QX,e.PivotRuntimeDefinition=LL,e.Registry=B,e.Revision=AK,e.SPREADSHEET_DIMENSIONS=AZ,e.Spreadsheet=ZJ,e.SpreadsheetPivotTable=zL,e.UIPlugin=cb,e.__info__=kZ,e.addFunction=LZ,e.addRenderingLayer=pr,e.astToFormula=yB,e.categories=bO,e.chartHelpers=zZ,e.components=PZ,e.constants=RZ,e.convertAstNodes=JO,e.coreTypes=Vs,e.createAutocompleteArgumentsProvider=mq,e.findCellInNewZone=Ln,e.functionCache=cU,e.getCaretDownSvg=ZA,e.getCaretUpSvg=QA,e.helpers=MZ,e.hooks=FZ,e.invalidateCFEvaluationCommands=Ls,e.invalidateChartEvaluationCommands=Fs,e.invalidateDependenciesCommands=Is,e.invalidateEvaluationCommands=Ps,e.iterateAstNodes=YO,e.links=NZ,e.load=sP,e.parse=KO,e.parseTokens=qO,e.readonlyAllowedCommands=Bs,e.registries=jZ,e.setDefaultSheetViewSize=Fe,e.setTranslationMethod=ca,e.stores=IZ,e.tokenColors=He,e.tokenize=bu,kZ.version=`19.1.20`,kZ.date=`2026-05-15T07:06:03.182Z`,kZ.hash=`b6a68b8`})(this.o_spreadsheet=this.o_spreadsheet||{},owl);
|
|
935
|
+
`),`_rels/.rels`)}function ZX(e){let t={},n=[];for(let r of e.sheets){let e=r.name.slice(0,31);e=zt(e,n,{compute:(e,t)=>e.slice(0,31-String(t).length)+t}),n.push(e),e!==r.name&&(t[r.name]=e,r.name=e)}if(!Object.keys(t).length)return e;let r=Object.keys(t).sort((e,t)=>t.length-e.length),i=JSON.stringify(e);for(let e of r){let n=RegExp(`'?${Ge(e)}'?!`,`g`);i=i.replaceAll(n,n=>{let r=t[e];return n.replace(e,r)})}return JSON.parse(i)}function QX(e){for(let t of e.sheets)t.tables=t.tables.filter(e=>On(un(e.range)).numberOfRows>1);return e}var $X=class extends er{corePlugins=[];statefulUIPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;coreViewPluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},t={},n=[],r=new Gl,i=!1){let a=performance.now();console.debug(`##### Model creation #####`),super(),la(),n=hP(e,n);let o=sP(e,i);this.state=new pY,this.uuidGenerator=r,this.config=this.setupConfig(t),this.session=this.setupSession(o.revisionId),this.coreGetters={},this.range=new uY(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.coreGetters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.coreGetters.getRangeData=this.range.getRangeData.bind(this.range),this.coreGetters.getRangeDataFromXc=this.range.getRangeDataFromXc.bind(this.range),this.coreGetters.getRangeDataFromZone=this.range.getRangeDataFromZone.bind(this.range),this.coreGetters.getRangeFromRangeData=this.range.getRangeFromRangeData.bind(this.range),this.coreGetters.getRangeFromZone=this.range.getRangeFromZone.bind(this.range),this.coreGetters.recomputeRanges=this.range.recomputeRanges.bind(this.range),this.coreGetters.isRangeValid=this.range.isRangeValid.bind(this.range),this.coreGetters.extendRange=this.range.extendRange.bind(this.range),this.coreGetters.getRangesUnion=this.range.getRangesUnion.bind(this.range),this.coreGetters.removeRangesSheetPrefix=this.range.removeRangesSheetPrefix.bind(this.range),this.coreGetters.copyFormulaStringForSheet=this.range.copyFormulaStringForSheet.bind(this.range),this.getters={isReadonly:()=>this.config.mode===`readonly`||this.config.mode===`dashboard`,isDashboard:()=>this.config.mode===`dashboard`},this.selection=new fY(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.coreViewPluginConfig=this.setupCoreViewPluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(let e of dq.getAll())this.setupCorePlugin(e,o);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(n);for(let e of mq.getAll()){let t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(let e of pq.getAll()){let t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(let e of fq.getAll()){let t=this.setupUiPlugin(e);this.handlers.push(t),this.uiHandlers.push(t)}if(this.dispatch(`START`),this.selection.observe(this,{handleEvent:()=>this.trigger(`update`)}),this.setupSessionEvents(),this.joinSession(),t.snapshotRequested||e[`[Content_Types].xml`]&&!this.getters.isReadonly()){let e=performance.now();console.debug(`Snapshot requested`),this.session.snapshot(this.exportData()),console.debug(`Snapshot taken in`,performance.now()-e,`ms`)}console.debug(`Model created in`,performance.now()-a,`ms`),console.debug(`######`)}joinSession(){this.session.join(this.config.client)}async leaveSession(){let e=this.getters.isReadonly()?void 0:mt(()=>this.exportData());await this.session.leave(e)}setupUiPlugin(e){let t=new e(this.uiPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}for(let n of e.layers)this.renderers[n]||(this.renderers[n]=[]),this.renderers[n].push(t);return t}setupCoreViewPlugin(e){let t=new e(this.coreViewPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}return t}setupCorePlugin(e,t){let n=new e(this.corePluginConfig);for(let t of e.getters){if(!(t in n))throw Error(`Invalid getter name: ${t} for plugin ${n.constructor}`);if(t in this.coreGetters)throw Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=n[t].bind(n)}n.import(t),this.corePlugins.push(n),this.coreHandlers.push(n),this.handlers.push(n)}onRemoteRevisionReceived({commands:e}){for(let t of e){let e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new NK(sY({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:k(`Anonymous`).toString()},n=e.transportService||new fJ,r=e.mode===`readonly`||e.mode===`dashboard`;return{...e,mode:e.mode||`normal`,custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:r?new $J(n):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(uo));return{...e,loadLocales:t}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,canDispatch:this.canDispatch,custom:this.config.custom,external:this.config.external}}setupCoreViewPluginConfig(){return{getters:this.getters,stateObserver:this.state,custom:this.config.custom,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,canDispatch:this.canDispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}checkDispatchAllowed(e){let t=Hs(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return t.some(e=>e!==`Success`)?new Ws(t.flat()):Ws.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(eZ(e,t));dispatch=(e,t)=>{let n=eZ(e,t),r=this.status;if(this.getters.isReadonly()&&!Us(n))return new Ws(`Readonly`);if(!this.session.canApplyOptimisticUpdate())return new Ws(`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();Hs(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(Hs(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(Hs(n))throw Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,n)}return Ws.Success};dispatchFromCorePlugin=(e,t)=>{let n=eZ(e,t),r=this.status;this.status=2;let i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,n),this.status=r,Ws.Success};dispatchToHandlers(e,t){let n=Hs(t);for(let r of e)!n&&r instanceof fW||r.beforeHandle(t);for(let r of e)!n&&r instanceof fW||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=SP();for(let t of this.handlers)t instanceof fW&&t.export(e);return e.revisionId=this.session.getRevisionId()||`START_REVISION`,e=b(e),e}updateMode(e){this.config.mode=e,this.trigger(`update`)}async exportXLSX(){this.dispatch(`EVALUATE_CELLS`);let e=wP();for(let t of this.handlers)t instanceof sb&&await t.exportForExcel(e);return e=b(e),HX(e)}};function eZ(e,t={}){let n=b(t);return n.type=e,n}function tZ(e){return!WV.includes(e.horizontalGroupBy)||!WV.includes(e.verticalGroupBy)?`InvalidChartDefinition`:`Success`}var nZ=class e extends Af{dataSets;labelRange;background;type=`calendar`;showValues;colorScale;axesDesign;horizontalGroupBy;verticalGroupBy;legendPosition;missingValueColor;constructor(e,t,n){super(e,t,n),this.dataSets=td(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Zc(n,t,e.labelRange),this.background=e.background,this.showValues=e.showValues,this.colorScale=e.colorScale,this.axesDesign=e.axesDesign,this.horizontalGroupBy=e.horizontalGroupBy,this.verticalGroupBy=e.verticalGroupBy,this.legendPosition=e.legendPosition,this.missingValueColor=e.missingValueColor}static transformDefinition(e,t,n){return ad(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,cd,ld,tZ)}static getDefinitionFromContextCreation(e){let t=`left`;return e.legendPosition===`right`&&(t=`right`),{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,title:e.title||{text:``},type:`calendar`,labelRange:e.auxiliaryRange||void 0,showValues:e.showValues,axesDesign:e.axesDesign,legendPosition:t,horizontalGroupBy:`day_of_week`,verticalGroupBy:`month_number`}}getContextCreation(){let e=[{dataRange:this.getters.getRangeString(this.dataSets[0].dataRange,this.sheetId)}];return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(t){let n=Qu(this.sheetId,t,this.dataSets),r=$u(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,n||this.sheetId)}));return{type:`calendar`,background:this.background,dataSets:r,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,showValues:this.showValues,colorScale:this.colorScale,axesDesign:this.axesDesign,horizontalGroupBy:this.horizontalGroupBy,verticalGroupBy:this.verticalGroupBy,legendPosition:this.legendPosition,missingValueColor:this.missingValueColor}}getDefinitionForExcel(){}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=Zu(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function rZ(e,t){let n=e.getDefinition(),r=Hh(n,e.dataSets,e.labelRange,t),{labels:i,datasets:a}=Zd(n,r);return{chartJsConfig:{type:`calendar`,data:{labels:i,datasets:a},options:{...Vp,indexAxis:`x`,layout:Eg(n,r),scales:Pd(n,a),plugins:{title:Gg(n,t),legend:{display:!1},tooltip:Xg(n,r),chartShowValuesPlugin:Bg(n,r),chartColorScalePlugin:Fd(n,r)},chartBackground:n.background||`#FFFFFF`}},background:e.background||`#FFFFFF`}}var iZ=class e extends Af{dataSets;labelRange;background;legendPosition;aggregated;dataSetsHaveTitle;dataSetDesign;axesDesign;type=`combo`;showValues;hideDataMarkers;zoomable;constructor(e,t,n){super(e,t,n),this.dataSets=td(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Zc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues,this.hideDataMarkers=e.hideDataMarkers,this.zoomable=e.zoomable}static transformDefinition(e,t,n){return ad(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,cd,ld)}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId),type:this.dataSetDesign?.[t]?.type??(t?`line`:`bar`)});return{type:`combo`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,axesDesign:this.axesDesign,showValues:this.showValues,hideDataMarkers:this.hideDataMarkers,zoomable:this.zoomable,humanize:this.humanize}}getDefinitionForExcel(){let{dataSets:e,labelRange:t}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,ud(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),n=this.getDefinition();return{...n,backgroundColor:V(this.background||`#FFFFFF`),fontColor:V(od(this.background)),dataSets:e,labelRange:t,verticalAxis:fd(n)}}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=Zu(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}static getDefinitionFromContextCreation(e){let t=(e.range??[]).map((e,t)=>({...e,type:t?`line`:`bar`}));return{background:e.background,dataSets:t,dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},labelRange:e.auxiliaryRange||void 0,type:`combo`,axesDesign:e.axesDesign,showValues:e.showValues,hideDataMarkers:e.hideDataMarkers,zoomable:e.zoomable,humanize:e.humanize}}duplicateInDuplicatedSheet(t){let n=Qu(this.sheetId,t,this.dataSets),r=$u(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}};function aZ(e,t){let n=e.getDefinition(),r=zh(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`bar`,data:{labels:r.labels,datasets:nf(n,r)},options:{...Vp,layout:Tg(n,r),scales:Nd(n,r),plugins:{title:Gg(n,t),legend:Mg(n,r),tooltip:Yg(n,r),chartShowValuesPlugin:zg(n,r)}}},background:e.background||`#FFFFFF`}}var oZ=class e extends Af{dataSets;labelRange;background;legendPosition;aggregated;type=`funnel`;dataSetsHaveTitle;dataSetDesign;axesDesign;horizontal=!0;showValues;funnelColors;cumulative;constructor(e,t,n){super(e,t,n),this.dataSets=td(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Zc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues,this.horizontal=!0,this.funnelColors=e.funnelColors,this.cumulative=e.cumulative}static transformDefinition(e,t,n){return ad(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,cd,ld)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated??!1,legendPosition:`none`,title:e.title||{text:``},type:`funnel`,labelRange:e.auxiliaryRange||void 0,showValues:e.showValues,axesDesign:e.axesDesign,funnelColors:e.funnelColors,horizontal:!0,cumulative:e.cumulative,humanize:e.humanize}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(t){let n=Qu(this.sheetId,t,this.dataSets),r=$u(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`funnel`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,horizontal:this.horizontal,axesDesign:this.axesDesign,showValues:this.showValues,funnelColors:this.funnelColors,cumulative:this.cumulative,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=Zu(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function sZ(e,t){let n=e.getDefinition(),r=Jh(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`funnel`,data:{labels:r.labels,datasets:of(n,r)},options:{...Vp,indexAxis:`y`,layout:Tg(n,r),scales:Hd(n,r),plugins:{title:Gg(n,t),legend:{display:!1},tooltip:r_(n,r),chartShowValuesPlugin:zg(n,r)}}},background:e.background||`#FFFFFF`}}var cZ=class e extends Af{dataSets;labelRange;background;legendPosition;type=`geo`;dataSetsHaveTitle;dataSetDesign;colorScale;missingValueColor;region;constructor(e,t,n){super(e,t,n),this.dataSets=td(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Zc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.colorScale=e.colorScale,this.missingValueColor=e.missingValueColor,this.region=e.region}static transformDefinition(e,t,n){return ad(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,cd,ld)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`geo`,labelRange:e.auxiliaryRange||void 0,humanize:e.humanize}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(t){let n=Qu(this.sheetId,t,this.dataSets),r=$u(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`geo`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,colorScale:this.colorScale,missingValueColor:this.missingValueColor,region:this.region,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=Zu(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function lZ(e,t){let n=e.getDefinition(),r=qh(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`choropleth`,data:{datasets:af(n,r)},options:{...Vp,layout:Tg(n,r),scales:Vd(n,r),plugins:{title:Gg(n,t),tooltip:n_(n,r),legend:{display:!1}}}},background:e.background||`#FFFFFF`}}var uZ=class e extends Af{dataSets;labelRange;background;legendPosition;aggregated;type=`pyramid`;dataSetsHaveTitle;dataSetDesign;axesDesign;horizontal=!0;stacked=!0;showValues;constructor(e,t,n){super(e,t,n),this.dataSets=td(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Zc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues}static transformDefinition(e,t,n){return ad(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,cd,ld)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`pyramid`,labelRange:e.auxiliaryRange||void 0,axesDesign:e.axesDesign,horizontal:!0,stacked:!0,showValues:e.showValues,humanize:e.humanize}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(t){let n=Qu(this.sheetId,t,this.dataSets),r=$u(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`pyramid`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,axesDesign:this.axesDesign,horizontal:!0,stacked:!0,showValues:this.showValues,humanize:this.humanize}}getDefinitionForExcel(e){let{dataSets:t,labelRange:n}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,ud(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),r=this.getDefinition(),{dataSetsValues:i}=Uh(r,this.dataSets,this.labelRange,e),a=Math.max(...i.map(e=>Math.max(...e.data.map(Math.abs))));return{...r,horizontal:!0,backgroundColor:V(this.background||`#FFFFFF`),fontColor:V(od(this.background)),dataSets:t,labelRange:n,verticalAxis:fd(r),maxValue:a}}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=Zu(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function dZ(e,t){let n=e.getDefinition(),r=Uh(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`bar`,data:{labels:r.labels,datasets:Xd(n,r)},options:{...Vp,indexAxis:`y`,layout:Tg(n,r),scales:zd(n,r),plugins:{title:Gg(n,t),legend:Og(n,r),tooltip:e_(n,r),chartShowValuesPlugin:Hg(n,r)}}},background:e.background||`#FFFFFF`}}var fZ=class e extends Af{dataSets;labelRange;background;legendPosition;stacked;aggregated;type=`radar`;dataSetsHaveTitle;dataSetDesign;fillArea;showValues;hideDataMarkers;constructor(e,t,n){super(e,t,n),this.dataSets=td(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Zc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.stacked=e.stacked,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.dataSetDesign=e.dataSets,this.fillArea=e.fillArea,this.showValues=e.showValues,this.hideDataMarkers=e.hideDataMarkers}static transformDefinition(e,t,n){return ad(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,cd,ld)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,stacked:e.stacked??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`radar`,labelRange:e.auxiliaryRange||void 0,fillArea:e.fillArea??!1,showValues:e.showValues??!1,hideDataMarkers:e.hideDataMarkers,humanize:e.humanize}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}duplicateInDuplicatedSheet(t){let n=Qu(this.sheetId,t,this.dataSets),r=$u(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`radar`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,stacked:this.stacked,aggregated:this.aggregated,fillArea:this.fillArea,showValues:this.showValues,hideDataMarkers:this.hideDataMarkers,humanize:this.humanize}}getDefinitionForExcel(){let{dataSets:e,labelRange:t}=this.getCommonDataSetAttributesForExcel(this.labelRange,this.dataSets,ud(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:V(this.background||`#FFFFFF`),fontColor:V(od(this.background)),dataSets:e,labelRange:t}}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=Zu(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function pZ(e,t){let n=e.getDefinition(),r=Kh(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`radar`,data:{labels:r.labels,datasets:rf(n,r)},options:{...Vp,layout:Tg(n,r),scales:Bd(n,r),plugins:{title:Gg(n,t),legend:Pg(n,r),tooltip:t_(n,r),chartShowValuesPlugin:zg(n,r)}}},background:e.background||`#FFFFFF`}}var mZ=class e extends Af{dataSets;labelRange;background;legendPosition;type=`sunburst`;dataSetsHaveTitle;showValues;showLabels;valuesDesign;groupColors;pieHolePercentage;constructor(e,t,n){super(e,t,n),this.dataSets=td(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Zc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.showValues=e.showValues,this.showLabels=e.showLabels,this.valuesDesign=e.valuesDesign,this.groupColors=e.groupColors,this.pieHolePercentage=e.pieHolePercentage}static transformDefinition(e,t,n){return ad(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,cd,ld)}static getDefinitionFromContextCreation(e){let t=[];return e.hierarchicalRanges?.length?t.push(...e.hierarchicalRanges):e.auxiliaryRange&&t.push({...e.range?.[0],dataRange:e.auxiliaryRange}),{background:e.background,dataSets:t,dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`sunburst`,labelRange:e.range?.[0]?.dataRange,showValues:e.showValues,showLabels:e.showLabels,valuesDesign:e.valuesDesign,groupColors:e.groupColors,humanize:e.humanize}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getContextCreation(){let e=this.dataSets.at(-1)?.dataRange;return{...this,range:this.labelRange?[{dataRange:this.getters.getRangeString(this.labelRange,this.sheetId)}]:[],auxiliaryRange:e?this.getters.getRangeString(e,this.sheetId):void 0,hierarchicalRanges:this.dataSets.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,this.sheetId)}))}}getDefinitionWithSpecificDataSets(e,t,n){return{type:`sunburst`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,n||this.sheetId)})),legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,showValues:this.showValues,showLabels:this.showLabels,valuesDesign:this.valuesDesign,groupColors:this.groupColors,pieHolePercentage:this.pieHolePercentage,humanize:this.humanize}}duplicateInDuplicatedSheet(t){let n=Qu(this.sheetId,t,this.dataSets),r=$u(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinitionForExcel(){}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=Zu(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function hZ(e,t){let n=e.getDefinition(),r=Yh(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`doughnut`,data:{datasets:cf(n,r)},options:{cutout:e.pieHolePercentage===void 0?`25%`:`${e.pieHolePercentage}%`,...Vp,layout:Tg(n,r),plugins:{title:Gg(n,t),legend:Fg(n,r),tooltip:i_(n,r),sunburstLabelsPlugin:Vg(n,r),sunburstHoverPlugin:{enabled:!0}}}},background:e.background||`#FFFFFF`}}var gZ=class e extends Af{static defaults={background:oe,legendPosition:`top`,dataSetsHaveTitle:!1,showHeaders:!0,headersColor:`#000000`};dataSets;labelRange;background;legendPosition;type=`treemap`;dataSetsHaveTitle;showHeaders;headerDesign;showValues;showLabels;valuesDesign;coloringOptions;constructor(e,t,n){super(e,t,n),this.dataSets=td(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Zc(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.showHeaders=e.showHeaders,this.headerDesign=e.headerDesign,this.showValues=e.showValues,this.showLabels=e.showLabels,this.valuesDesign=e.valuesDesign,this.coloringOptions=e.coloringOptions}static transformDefinition(e,t,n){return ad(e,t,n)}static validateChartDefinition(e,t){return e.checkValidations(t,cd,ld)}static getDefinitionFromContextCreation(e){let t=[];return e.hierarchicalRanges?.length?t.push(...e.hierarchicalRanges):e.auxiliaryRange&&t.push({...e.range?.[0],dataRange:e.auxiliaryRange}),{background:e.background,dataSets:t,dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`treemap`,labelRange:e.range?.[0]?.dataRange,showValues:e.showValues,showHeaders:e.showHeaders,headerDesign:e.headerDesign,showLabels:e.showLabels,valuesDesign:e.valuesDesign,coloringOptions:e.treemapColoringOptions,humanize:e.humanize}}getContextCreation(){let e=this.dataSets.at(-1)?.dataRange;return{...this,range:this.labelRange?[{dataRange:this.getters.getRangeString(this.labelRange,this.sheetId)}]:[],auxiliaryRange:e?this.getters.getRangeString(e,this.sheetId):void 0,hierarchicalRanges:this.dataSets.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,this.sheetId)}))}}duplicateInDuplicatedSheet(t){let n=Qu(this.sheetId,t,this.dataSets),r=$u(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,n||this.sheetId)}));return{type:`treemap`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,showValues:this.showValues,showHeaders:this.showHeaders,headerDesign:this.headerDesign,showLabels:this.showLabels,valuesDesign:this.valuesDesign,coloringOptions:this.coloringOptions,humanize:this.humanize}}getDefinitionForExcel(){}updateRanges({applyChange:t}){let{dataSets:n,labelRange:r,isStale:i}=Zu(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function _Z(e,t){let n=e.getDefinition(),r=Yh(n,e.dataSets,e.labelRange,t);return{chartJsConfig:{type:`treemap`,data:{labels:r.labels,datasets:pf(n,r)},options:{...Vp,layout:Tg(n,r),plugins:{title:Gg(n,t),legend:{display:!1},tooltip:a_(n,r)}}},background:e.background||`#FFFFFF`}}f_.add(`bar`,{match:e=>e===`bar`,createChart:(e,t,n)=>new u_(e,t,n),getChartRuntime:d_,validateChartDefinition:u_.validateChartDefinition,transformDefinition:u_.transformDefinition,getChartDefinitionFromContextCreation:u_.getDefinitionFromContextCreation,sequence:10}),f_.add(`combo`,{match:e=>e===`combo`,createChart:(e,t,n)=>new iZ(e,t,n),getChartRuntime:aZ,validateChartDefinition:iZ.validateChartDefinition,transformDefinition:iZ.transformDefinition,getChartDefinitionFromContextCreation:iZ.getDefinitionFromContextCreation,sequence:15}),f_.add(`line`,{match:e=>e===`line`,createChart:(e,t,n)=>new k_(e,t,n),getChartRuntime:A_,validateChartDefinition:k_.validateChartDefinition,transformDefinition:k_.transformDefinition,getChartDefinitionFromContextCreation:k_.getDefinitionFromContextCreation,sequence:20}),f_.add(`pie`,{match:e=>e===`pie`,createChart:(e,t,n)=>new j_(e,t,n),getChartRuntime:M_,validateChartDefinition:j_.validateChartDefinition,transformDefinition:j_.transformDefinition,getChartDefinitionFromContextCreation:j_.getDefinitionFromContextCreation,sequence:30}),f_.add(`scorecard`,{match:e=>e===`scorecard`,createChart:(e,t,n)=>new Bf(e,t,n),getChartRuntime:Hf,validateChartDefinition:Bf.validateChartDefinition,transformDefinition:Bf.transformDefinition,getChartDefinitionFromContextCreation:Bf.getDefinitionFromContextCreation,sequence:40}),f_.add(`gauge`,{match:e=>e===`gauge`,createChart:(e,t,n)=>new C_(e,t,n),getChartRuntime:w_,validateChartDefinition:C_.validateChartDefinition,transformDefinition:C_.transformDefinition,getChartDefinitionFromContextCreation:C_.getDefinitionFromContextCreation,sequence:50}),f_.add(`scatter`,{match:e=>e===`scatter`,createChart:(e,t,n)=>new lH(e,t,n),getChartRuntime:uH,validateChartDefinition:lH.validateChartDefinition,transformDefinition:lH.transformDefinition,getChartDefinitionFromContextCreation:lH.getDefinitionFromContextCreation,sequence:60}),f_.add(`waterfall`,{match:e=>e===`waterfall`,createChart:(e,t,n)=>new N_(e,t,n),getChartRuntime:P_,validateChartDefinition:N_.validateChartDefinition,transformDefinition:N_.transformDefinition,getChartDefinitionFromContextCreation:N_.getDefinitionFromContextCreation,sequence:70}),f_.add(`pyramid`,{match:e=>e===`pyramid`,createChart:(e,t,n)=>new uZ(e,t,n),getChartRuntime:dZ,validateChartDefinition:uZ.validateChartDefinition,transformDefinition:uZ.transformDefinition,getChartDefinitionFromContextCreation:uZ.getDefinitionFromContextCreation,sequence:80,dataSeriesLimit:2}),f_.add(`radar`,{match:e=>e===`radar`,createChart:(e,t,n)=>new fZ(e,t,n),getChartRuntime:pZ,validateChartDefinition:fZ.validateChartDefinition,transformDefinition:fZ.transformDefinition,getChartDefinitionFromContextCreation:fZ.getDefinitionFromContextCreation,sequence:80}),f_.add(`geo`,{match:e=>e===`geo`,createChart:(e,t,n)=>new cZ(e,t,n),getChartRuntime:lZ,validateChartDefinition:cZ.validateChartDefinition,transformDefinition:cZ.transformDefinition,getChartDefinitionFromContextCreation:cZ.getDefinitionFromContextCreation,sequence:90,dataSeriesLimit:1}),f_.add(`funnel`,{match:e=>e===`funnel`,createChart:(e,t,n)=>new oZ(e,t,n),getChartRuntime:sZ,validateChartDefinition:oZ.validateChartDefinition,transformDefinition:oZ.transformDefinition,getChartDefinitionFromContextCreation:oZ.getDefinitionFromContextCreation,sequence:100,dataSeriesLimit:1}),f_.add(`sunburst`,{match:e=>e===`sunburst`,createChart:(e,t,n)=>new mZ(e,t,n),getChartRuntime:hZ,validateChartDefinition:mZ.validateChartDefinition,transformDefinition:mZ.transformDefinition,getChartDefinitionFromContextCreation:mZ.getDefinitionFromContextCreation,sequence:30}),f_.add(`treemap`,{match:e=>e===`treemap`,createChart:(e,t,n)=>new gZ(e,t,n),getChartRuntime:_Z,validateChartDefinition:gZ.validateChartDefinition,transformDefinition:gZ.transformDefinition,getChartDefinitionFromContextCreation:gZ.getDefinitionFromContextCreation,sequence:100}),f_.add(`calendar`,{match:e=>e===`calendar`,createChart:(e,t,n)=>new nZ(e,t,n),getChartRuntime:(e,t)=>rZ(e,t),validateChartDefinition:nZ.validateChartDefinition,transformDefinition:nZ.transformDefinition,getChartDefinitionFromContextCreation:nZ.getDefinitionFromContextCreation,sequence:110,dataSeriesLimit:1}),K_.add(`line`,{matcher:e=>e.type===`line`&&!e.stacked&&!e.fillArea,displayName:k(`Line`),chartType:`line`,chartSubtype:`line`,subtypeDefinition:{stacked:!1,fillArea:!1},category:`line`,preview:`o-spreadsheet-ChartPreview.LINE_CHART`}).add(`stacked_line`,{matcher:e=>e.type===`line`&&!e.fillArea&&!!e.stacked,displayName:k(`Stacked Line`),chartType:`line`,chartSubtype:`stacked_line`,subtypeDefinition:{stacked:!0,fillArea:!1},category:`line`,preview:`o-spreadsheet-ChartPreview.STACKED_LINE_CHART`}).add(`area`,{matcher:e=>e.type===`line`&&!e.stacked&&!!e.fillArea,displayName:k(`Area`),chartType:`line`,chartSubtype:`area`,subtypeDefinition:{stacked:!1,fillArea:!0},category:`area`,preview:`o-spreadsheet-ChartPreview.AREA_CHART`}).add(`stacked_area`,{matcher:e=>e.type===`line`&&e.stacked&&!!e.fillArea,displayName:k(`Stacked Area`),chartType:`line`,chartSubtype:`stacked_area`,subtypeDefinition:{stacked:!0,fillArea:!0},category:`area`,preview:`o-spreadsheet-ChartPreview.STACKED_AREA_CHART`}).add(`scatter`,{displayName:k(`Scatter`),chartType:`scatter`,chartSubtype:`scatter`,category:`misc`,preview:`o-spreadsheet-ChartPreview.SCATTER_CHART`}).add(`column`,{matcher:e=>e.type===`bar`&&!e.stacked&&!e.horizontal,displayName:k(`Column`),chartType:`bar`,chartSubtype:`column`,subtypeDefinition:{stacked:!1,horizontal:!1},category:`column`,preview:`o-spreadsheet-ChartPreview.COLUMN_CHART`}).add(`stacked_column`,{matcher:e=>e.type===`bar`&&e.stacked&&!e.horizontal,displayName:k(`Stacked Column`),chartType:`bar`,chartSubtype:`stacked_column`,subtypeDefinition:{stacked:!0,horizontal:!1},category:`column`,preview:`o-spreadsheet-ChartPreview.STACKED_COLUMN_CHART`}).add(`bar`,{matcher:e=>e.type===`bar`&&!e.stacked&&!!e.horizontal,displayName:k(`Bar`),chartType:`bar`,chartSubtype:`bar`,subtypeDefinition:{horizontal:!0,stacked:!1},category:`bar`,preview:`o-spreadsheet-ChartPreview.BAR_CHART`}).add(`stacked_bar`,{matcher:e=>e.type===`bar`&&e.stacked&&!!e.horizontal,displayName:k(`Stacked Bar`),chartType:`bar`,chartSubtype:`stacked_bar`,subtypeDefinition:{horizontal:!0,stacked:!0},category:`bar`,preview:`o-spreadsheet-ChartPreview.STACKED_BAR_CHART`}).add(`combo`,{displayName:k(`Combo`),chartSubtype:`combo`,chartType:`combo`,category:`line`,preview:`o-spreadsheet-ChartPreview.COMBO_CHART`}).add(`pie`,{matcher:e=>e.type===`pie`&&!e.isDoughnut,displayName:k(`Pie`),chartSubtype:`pie`,chartType:`pie`,subtypeDefinition:{isDoughnut:!1},category:`pie`,preview:`o-spreadsheet-ChartPreview.PIE_CHART`}).add(`doughnut`,{matcher:e=>e.type===`pie`&&!!e.isDoughnut,displayName:k(`Doughnut`),chartSubtype:`doughnut`,chartType:`pie`,subtypeDefinition:{isDoughnut:!0},category:`pie`,preview:`o-spreadsheet-ChartPreview.DOUGHNUT_CHART`}).add(`gauge`,{displayName:k(`Gauge`),chartSubtype:`gauge`,chartType:`gauge`,category:`misc`,preview:`o-spreadsheet-ChartPreview.GAUGE_CHART`}).add(`scorecard`,{displayName:k(`Scorecard`),chartSubtype:`scorecard`,chartType:`scorecard`,category:`misc`,preview:`o-spreadsheet-ChartPreview.SCORECARD_CHART`}).add(`waterfall`,{displayName:k(`Waterfall`),chartSubtype:`waterfall`,chartType:`waterfall`,category:`misc`,preview:`o-spreadsheet-ChartPreview.WATERFALL_CHART`}).add(`pyramid`,{displayName:k(`Population Pyramid`),chartSubtype:`pyramid`,chartType:`pyramid`,category:`misc`,preview:`o-spreadsheet-ChartPreview.POPULATION_PYRAMID_CHART`}).add(`radar`,{matcher:e=>e.type===`radar`&&!e.fillArea,displayName:k(`Radar`),chartSubtype:`radar`,chartType:`radar`,subtypeDefinition:{fillArea:!1},category:`misc`,preview:`o-spreadsheet-ChartPreview.RADAR_CHART`}).add(`filled_radar`,{matcher:e=>e.type===`radar`&&!!e.fillArea,displayName:k(`Filled Radar`),chartType:`radar`,chartSubtype:`filled_radar`,subtypeDefinition:{fillArea:!0},category:`misc`,preview:`o-spreadsheet-ChartPreview.FILLED_RADAR_CHART`}).add(`geo`,{displayName:k(`Geo Chart`),chartSubtype:`geo`,chartType:`geo`,category:`misc`,preview:`o-spreadsheet-ChartPreview.GEO_CHART`}).add(`funnel`,{displayName:k(`Funnel`),chartSubtype:`funnel`,chartType:`funnel`,category:`misc`,preview:`o-spreadsheet-ChartPreview.FUNNEL_CHART`}).add(`sunburst`,{matcher:e=>e.type===`sunburst`,displayName:k(`Sunburst`),chartSubtype:`sunburst`,chartType:`sunburst`,category:`hierarchical`,preview:`o-spreadsheet-ChartPreview.SUNBURST_CHART`}).add(`treemap`,{matcher:e=>e.type===`treemap`,displayName:k(`Tree Map`),chartType:`treemap`,chartSubtype:`treemap`,category:`hierarchical`,preview:`o-spreadsheet-ChartPreview.TREE_MAP_CHART`}).add(`calendar`,{displayName:k(`Calendar`),chartSubtype:`calendar`,chartType:`calendar`,category:`misc`,preview:`o-spreadsheet-ChartPreview.CALENDAR_CHART`});var vZ=class extends OG{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(E(t))}executeQueuedChanges(e){for(let t in this.queuedBordersToAdd){let n=this.queuedBordersToAdd[t],r=JSON.parse(t),i=Qt(n,[]);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,target:i,border:r})}this.queuedBordersToAdd={}}},yZ=class extends DG{copy(e){}},bZ=class extends yZ{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!==`carousel`)return;let r={...n},i=this.getters.getCarousel(e.figureId),a={};for(let e of i.items)if(e.type===`chart`){let n=this.getters.getChart(e.chartId);if(!n)throw Error(`No chart for the given id: ${e.chartId}`);a[e.chartId]=n.copyInSheetId(t)}return{figureId:e.figureId,copiedFigure:r,copiedCarousel:i,copiedCharts:a,copiedSheetId:t}}getPasteTarget(e){return{zones:[],figureId:new Gl().smallUuid(),sheetId:e}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=e.sheetId,{width:o,height:s}=t.copiedFigure,c=this.getters.getMaxAnchorOffset(a,s,o),{left:l,top:u}=r[0],d={x:0,y:0};l>c.col&&(l=c.col,d.x=c.offset.x),u>c.row&&(u=c.row,d.y=c.offset.y),this.dispatch(`CREATE_CAROUSEL`,{figureId:i,sheetId:a,definition:{items:[]},col:l,row:u,offset:d,size:{height:s,width:o}});let f=new Gl,p=b(t.copiedCarousel.items);for(let e of p){if(e.type!==`chart`)continue;let n=t.copiedCharts[e.chartId],r=f.smallUuid(),o=n.copyInSheetId(a).getDefinition();this.dispatch(`CREATE_CHART`,{figureId:i,chartId:r,sheetId:a,definition:o}),e.chartId=r}this.dispatch(`UPDATE_CAROUSEL`,{sheetId:a,figureId:i,definition:{...t.copiedCarousel,items:p}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.copiedSheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},xZ=class extends yZ{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.getChartFromFigureId(e.figureId);if(!i)throw Error(`No chart for the given id: ${e.figureId}`);let a=i.copyInSheetId(t);return{figureId:e.figureId,copiedFigure:r,copiedChart:a}}getPasteTarget(e,t,n,r){return{zones:[],figureId:new Gl().smallUuid(),sheetId:e}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=e.sheetId,{width:o,height:s}=t.copiedFigure,c=t.copiedChart.copyInSheetId(a),l=this.getters.getMaxAnchorOffset(a,s,o),{left:u,top:d}=r[0],f={x:0,y:0};u>l.col&&(u=l.col,f.x=l.offset.x),d>l.row&&(d=l.row,f.y=l.offset.y),this.dispatch(`CREATE_CHART`,{figureId:i,chartId:new Gl().smallUuid(),sheetId:a,definition:c.getDefinition(),col:u,row:d,offset:f,size:{height:s,width:o}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.copiedChart.sheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},SZ=class extends OG{uuidGenerator=new Gl;queuedChanges={};copy(e){if(!e.zones.length)return;let{rowsIndexes:t,columnsIndexes:n}=e,r=e.sheetId,i=[];for(let e of t){let t=[];for(let i of n){let n=Array.from(this.getters.getRulesByCell(r,i,e));t.push({position:{col:i,row:e,sheetId:r},rules:n})}i.push(t)}return{cfRules:i}}paste(e,t,n){if(this.queuedChanges={},n.pasteOption===`asValue`)return;let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t):this.pasteFromCopy(i,r,t.cfRules,n),this.executeQueuedChanges()}pasteFromCut(e,t,n){let r=t[0];this.pasteZone(e,r.left,r.top,n.cfRules,{isCutOperation:!0})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){let o={col:t+r,row:n+a,sheetId:e};this.pasteCf(s,o,i?.isCutOperation)}}pasteCf(e,t,n){if(e?.rules&&e.rules.length>0){let r=E(e.position),i=E(t);for(let a of e.rules){let o=[];if(n&&o.push(r),e.position.sheetId===t.sheetId)this.adaptCFRules(e.position.sheetId,a,[i],o);else{this.adaptCFRules(e.position.sheetId,a,[],o);let n=this.getCFToCopyTo(t.sheetId,a);this.adaptCFRules(t.sheetId,n,[i],[])}}}}adaptCFRules(e,t,n,r){this.queuedChanges[e]||(this.queuedChanges[e]=[]);let i=this.queuedChanges[e].find(e=>e.cf.id===t.id);i?(i.toAdd.push(...n),i.toRemove.push(...r)):this.queuedChanges[e].push({toAdd:n,toRemove:r,cf:t})}executeQueuedChanges(){for(let e in this.queuedChanges)for(let{toAdd:t,toRemove:n,cf:r}of this.queuedChanges[e]){let i=this.getters.getAdaptedCfRanges(e,r,t,n);if(i){if(i.length===0){this.dispatch(`REMOVE_CONDITIONAL_FORMAT`,{id:r.id,sheetId:e});continue}this.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{id:r.id,rule:r.rule,stopIfTrue:r.stopIfTrue},ranges:i,sheetId:e})}}}getCFToCopyTo(e,t){let n=this.getters.getConditionalFormats(e).find(e=>e.stopIfTrue===t.stopIfTrue&&w(e.rule,t.rule)),r=this.queuedChanges[e];return!n&&r&&(n=r.find(e=>e.cf.stopIfTrue===t.stopIfTrue&&w(e.cf.rule,t.rule))?.cf),n||{...t,id:this.uuidGenerator.smallUuid(),ranges:[]}}},CZ=class extends OG{uuidGenerator=new Gl;queuedChanges={};copy(e){let{rowsIndexes:t,columnsIndexes:n}=e,r=e.sheetId,i=[];for(let e of t){let t=[];for(let i of n){let n={sheetId:r,col:i,row:e},a=this.getters.getValidationRuleForCell(n);t.push({position:n,rule:a})}i.push(t)}return{dvRules:i}}paste(e,t,n){if(this.queuedChanges={},n.pasteOption)return;let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t):this.pasteFromCopy(i,r,t.dvRules),this.executeQueuedChanges()}pasteFromCut(e,t,n){let r=t[0];this.pasteZone(e,r.left,r.top,n.dvRules,{isCutOperation:!0})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){let o={col:t+r,row:n+a,sheetId:e};this.pasteDataValidation(s,o,i?.isCutOperation)}}pasteDataValidation(e,t,n){if(e){let r=E(t),i=E(e.position),a=e.rule;if(!a){let e=this.getters.getValidationRuleForCell(t);e&&this.adaptDataValidationRule(t.sheetId,e,[],[r]);return}let o=[];if(n&&o.push(i),e.position.sheetId===t.sheetId){let n=this.getDataValidationRuleToCopyTo(t.sheetId,a,!1);this.adaptDataValidationRule(e.position.sheetId,n,[r],o)}else{let n=this.getters.getValidationRuleForCell(e.position);n&&this.adaptDataValidationRule(e.position.sheetId,n,[],o);let i=this.getDataValidationRuleToCopyTo(t.sheetId,a);this.adaptDataValidationRule(t.sheetId,i,[r],[])}}}getDataValidationRuleToCopyTo(e,t,n=!0){let r=this.getters.getDataValidationRules(e).find(e=>w(t.criterion,e.criterion)&&t.isBlocking===e.isBlocking),i=this.queuedChanges[e];return!r&&i&&(r=i.find(e=>w(t.criterion,e.rule.criterion)&&t.isBlocking===e.rule.isBlocking)?.rule),r||{...t,id:n?this.uuidGenerator.smallUuid():t.id,ranges:[]}}adaptDataValidationRule(e,t,n,r){this.queuedChanges[e]||(this.queuedChanges[e]=[]);let i=this.queuedChanges[e].find(e=>e.rule.id===t.id);i?(i.toAdd.push(...n),i.toRemove.push(...r)):this.queuedChanges[e].push({toAdd:n,toRemove:r,rule:t})}executeQueuedChanges(){for(let e in this.queuedChanges)for(let{toAdd:t,toRemove:n,rule:r}of this.queuedChanges[e]){let i=Qt([...Qt(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})}}},wZ=class extends yZ{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);let r={...n};if(n.tag!==`image`)return;let i=b(this.getters.getImage(e.figureId));return{figureId:e.figureId,copiedFigure:r,copiedImage:i,sheetId:t}}getPasteTarget(e,t,n,r){return{sheetId:e,zones:[],figureId:new Gl().smallUuid()}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=this.getters.getActiveSheetId(),{width:o,height:s}=t.copiedFigure,c=b(t.copiedImage),l=this.getters.getMaxAnchorOffset(a,s,o),{left:u,top:d}=r[0],f={x:0,y:0};u>l.col&&(u=l.col,f.x=l.offset.x),d>l.row&&(d=l.row,f.y=l.offset.y),this.dispatch(`CREATE_IMAGE`,{figureId:i,sheetId:a,col:u,row:d,offset:f,size:{height:s,width:o},definition:c}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.sheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},TZ=class extends OG{copy(e){let t=this.getters.getActiveSheetId(),{rowsIndexes:n,columnsIndexes:r}=e,i=[];for(let e of n){let n=[];for(let i of r){let r={col:i,row:e,sheetId:t};n.push(this.getters.getMerge(r))}i.push(n)}return{merges:i,sheetId:t}}paste(e,t,n){if(n.isCutOperation){let e=t.merges.flat().filter(C);this.dispatch(`REMOVE_MERGE`,{sheetId:t.sheetId,target:e})}this.pasteFromCopy(e.sheetId,e.zones,t.merges,n)}pasteZone(e,t,n,r){for(let[i,a]of r.entries())for(let[r,o]of a.entries()){let a={col:t+r,row:n+i,sheetId:e};this.pasteMerge(o,a)}}pasteMerge(e,t){if(!e||this.getters.isInMerge(t))return;let{sheetId:n,col:r,row:i}=t;this.dispatch(`ADD_MERGE`,{sheetId:n,force:!0,target:[{left:r,top:i,right:r+e.right-e.left,bottom:i+e.bottom-e.top}]})}},EZ=class extends OG{copy(e){return{zones:e.clippedZones,sheetId:e.sheetId}}paste(e,t,n){if(n.isCutOperation){let n=e.zones[0];this.dispatch(`MOVE_RANGES`,{target:t.zones,sheetId:t.sheetId,sheetName:this.getters.getSheetName(t.sheetId),targetSheetId:e.sheetId,col:n.left,row:n.top})}}},DZ=class extends OG{isPasteAllowed(e,t,n,r){if(!(`cells`in n))return`Success`;let{xSplit:i,ySplit:a}=this.getters.getPaneDivisions(e);return Un(rA(t,n.cells),i,a)?`FrozenPaneOverlap`:`Success`}},OZ=class extends OG{copy(e){let t=e.sheetId;if(e.zones.length===0)return;let n=[],r=0;for(let i of Ze(e.columnsIndexes)){let a=0;for(let o of Ze(e.rowsIndexes)){let e={left:i[0],right:i[i.length-1],top:o[0],bottom:o[o.length-1]};n.push(...this.getters.getZoneStyles(t,e).map(t=>({zone:{left:t.zone.left-e.left+r,right:t.zone.right&&t.zone.right-e.left+r,top:t.zone.top-e.top+a,bottom:t.zone.bottom&&t.zone.bottom-e.top+a},style:t.style}))),a+=o.length}r+=i.length}return{styles:n,width:e.columnsIndexes.length,height:e.rowsIndexes.length}}paste(e,t,n){let r=e.sheetId;if(n.pasteOption===`asValue`)return;let i=e.zones;if(n.isCutOperation){let{left:e,top:n}=i[0];this.pasteStyleZone(r,e,n,t.styles)}else for(let e of i)for(let n of nA(e,t.width,t.height))this.pasteStyleZone(r,n.left,n.top,t.styles)}pasteStyleZone(e,t,n,r){for(let i of r){let r={left:i.zone.left+t,right:i.zone.right&&i.zone.right+t||i.zone.left+t,top:i.zone.top+n,bottom:i.zone.bottom&&i.zone.bottom+n||i.zone.top+n};this.dispatch(`SET_FORMATTING`,{sheetId:e,target:[r],style:i.style})}}},kZ=class extends OG{copy(e,t,n=`copyPaste`){let r=e.sheetId,{rowsIndexes:i,columnsIndexes:a,zones:o}=e,s=new Set,c=[];for(let e of i){let l=[];c.push(l);for(let c of a){let a={col:c,row:e,sheetId:r},u=this.getters.getTable(a);if(!u){l.push({});continue}let d=this.getters.getCoreTable(a),f=d?.range.zone,p;if(!s.has(u.id)&&d&&f&&o.some(e=>Dn(f,e))){s.add(u.id);let{numberOfRows:e}=On(f);for(let n=f.top;n<=f.bottom;n++)!t&&!i.includes(n)&&e--;let n=d.range,r=this.getters.extendRange(d.range,`ROW`,n.zone.top+e-1-n.zone.bottom);p={range:this.getters.getRangeData(r),config:d.config,type:d.type}}n!==`shiftCells`&&l.push({table:p,style:this.getTableStyleToCopy(a),isWholeTableCopied:s.has(u.id)})}}return{tableCells:c,sheetId:e.sheetId}}getTableStyleToCopy(e){let t=this.getters.getCellTableStyle(e),n=this.getters.getCellStyle(e),r=this.getters.getCellTableBorder(e),i=this.getters.getCellBorder(e);return{style:{...t,...bt(n)},border:{...r,...bt(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=On(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}))}};BB.figureHandlers.add(`chart`,xZ).add(`image`,wZ).add(`carousel`,bZ),BB.cellHandlers.add(`dataValidation`,CZ).add(`cell`,kG).add(`sheet`,DZ).add(`merge`,TZ).add(`border`,vZ).add(`table`,kZ).add(`conditionalFormat`,SZ).add(`references`,EZ).add(`style`,OZ);let AZ={},jZ={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:26,HEADER_WIDTH:48,DESKTOP_BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:96,DEFAULT_CELL_HEIGHT:23,SCROLLBAR_WIDTH:15},MZ={autoCompleteProviders:ak,autofillModifiersRegistry:jG,autofillRulesRegistry:MG,cellMenuRegistry:SR,colMenuRegistry:Bz,errorTypes:da,linkMenuRegistry:Qk,functionRegistry:yO,featurePluginRegistry:fq,iconsOnCellRegistry:uG,statefulUIPluginRegistry:pq,coreViewsPluginRegistry:mq,corePluginRegistry:dq,rowMenuRegistry:qz,sidePanelRegistry:nW,figureRegistry:Mv,chartSidePanelComponentRegistry:xH,chartComponentRegistry:sv,chartRegistry:f_,chartSubtypeRegistry:K_,topbarMenuRegistry:Gq,topbarComponentRegistry:dJ,clickableCellRegistry:xq,otRegistry:ZG,inverseCommandRegistry:wq,urlRegistry:Js,cellPopoverRegistry:Fv,numberFormatMenuRegistry:Bq,repeatLocalCommandTransformRegistry:HK,repeatCommandTransformRegistry:VK,clipboardHandlersRegistries:BB,pivotRegistry:ZL,pivotTimeAdapterRegistry:Um,pivotSidePanelRegistry:IU,pivotNormalizationValueRegistry:xh,supportedPivotPositionalFormulaRegistry:cW,pivotToFunctionValueRegistry:Sh,migrationStepRegistry:nP,chartJsExtensionRegistry:ql},NZ={arg:G,isEvaluationError:M,toBoolean:F,toJsDate:I,toNumber:N,toString:P,toNormalizedPivotValue:_h,toFunctionPivotValue:yh,toXC:T,toZone:un,toUnboundedZone:ln,toCartesian:Zt,numberToLetters:Ht,lettersToNumber:Ut,UuidGenerator:Gl,formatValue:z,createCurrencyFormat:ls,ColorGenerator:ei,computeTextWidth:Dl,createEmptyWorkbookData:SP,createEmptySheet:xP,createEmptyExcelSheet:CP,rgbaToHex:jr,colorToRGBA:Mr,positionToZone:E,isDefined:C,isMatrix:xa,lazy:mt,genericRepeat:uJ,createAction:h,createActions:p,transformRangeData:$n,deepEquals:w,overlap:wn,union:bn,isInside:En,deepCopy:b,expandZoneOnInsertion:gn,reduceZoneOnDeletion:yn,unquote:Je,getMaxObjectId:lh,getFunctionsFromTokens:CU,getFirstPivotFunction:EU,getNumberOfPivotFunctions:OU,parseDimension:fh,isDateOrDatetimeField:ph,makeFieldProposal:kU,insertTokenAfterArgSeparator:jU,insertTokenAfterLeftParenthesis:MU,mergeContiguousZones:Xn,getPivotHighlights:GH,pivotTimeAdapter:Wm,UNDO_REDO_PIVOT_COMMANDS:wG,createPivotFormula:gh,areDomainArgsFieldsValid:hh,splitReference:Pc,sanitizeSheetName:Xe,getUniqueText:zt,isNumber:$i,isDateTime:xi,createCustomFields:Oh,schemeToColorScale:Mm,isDateTimeFormat:ns,jsDateToNumber:Fi,numberToJsDate:Ni,DateTime:O,parseFormat:Eo,isFormula:Bt},PZ={isMarkdownLink:nt,parseMarkdownLink:at,markdownLink:it,openLink:$s,urlRepresentation:Qs},FZ={Checkbox:Fk,Section:q,RoundColorPicker:bk,ChartDataSeries:TV,ChartErrorSection:EV,ChartLabelRange:DV,ChartTitle:jV,ChartPanel:TH,ChartFigure:Av,ChartJsComponent:kf,ClickableCellSortIcon:lW,ZoomableChartJsComponent:$_,Grid:sW,GridOverlay:KB,ScorecardChart:Cp,GaugeChartComponent:av,LineConfigPanel:iH,BarConfigPanel:kV,PieChartDesignPanel:sH,GenericChartConfigPanel:OV,ChartWithAxisDesignPanel:VV,GenericZoomableChartDesignPanel:HV,LineChartDesignPanel:aH,GaugeChartConfigPanel:QV,GaugeChartDesignPanel:$V,ScorecardChartConfigPanel:fH,ScorecardChartDesignPanel:pH,GeoChartDesignPanel:nH,RadarChartDesignPanel:cH,WaterfallChartDesignPanel:bH,ComboChartDesignPanel:YV,FunnelChartDesignPanel:ZV,SunburstChartDesignPanel:mH,TreeMapChartDesignPanel:yH,ChartTypePicker:CH,FigureComponent:Nv,MenuPopover:Dv,Popover:Cv,SelectionInput:kk,ValidationMessages:IB,AddDimensionButton:XH,PivotDimensionGranularity:QH,PivotDimensionOrder:$H,PivotDimension:ZH,PivotLayoutConfigurator:yU,PivotHTMLRenderer:dW,PivotDeferUpdate:qH,PivotTitleSection:bU,CogWheelMenu:SV,TextInput:gV,SidePanelCollapsible:Vv,RadioSelection:NV,GeoChartRegionSelectSection:eH,ChartDashboardMenu:Ov,FullScreenFigure:uW,NumberInput:LV,TopBar:YJ,Composer:PO},IZ={useDragAndDropListItems:Sk,useHighlights:OH,useHighlightsOnHover:DH},LZ={useStoreProvider:ar,DependencyContainer:tr,CellPopoverStore:Bk,ComposerFocusStore:_r,CellComposerStore:CB,FindAndReplaceStore:LH,HighlightStore:sk,DelayedHoveredCellStore:Pv,HoveredTableStore:UB,ModelStore:ur,NotificationStore:ck,RendererStore:mr,SelectionInputStore:Ok,SpreadsheetStore:hr,useStore:D,useLocalStore:or,SidePanelStore:iW,PivotSidePanelStore:PU,PivotMeasureDisplayPanelStore:UH,ClientFocusStore:Yz,GridRenderer:eV};function RZ(e,t){return yO.add(e,t),{addFunction:(e,t)=>RZ(e,t)}}let zZ={DEFAULT_LOCALE:R,HIGHLIGHT_COLOR:ee,PIVOT_TABLE_CONFIG:Le,ChartTerms:Yp,FIGURE_ID_SPLITTER:`??`,GRID_ICON_EDGE_LENGTH:17,GRID_ICON_MARGIN:2},BZ={...F_,...l_};e.AbstractCellClipboardHandler=OG,e.AbstractChart=Af,e.AbstractFigureClipboardHandler=yZ,e.CellErrorType=A,e.ClientDisconnectedError=MK,e.CommandResult=Ks,e.CorePlugin=fW,e.CoreViewPlugin=RW,e.DEFAULT_LOCALE=R,e.DEFAULT_LOCALES=uo,e.DispatchResult=Ws,e.EvaluationError=j,e.LocalTransportService=fJ,e.Model=$X,e.PivotRuntimeDefinition=LL,e.Registry=B,e.Revision=jK,e.SPREADSHEET_DIMENSIONS=jZ,e.Spreadsheet=QJ,e.SpreadsheetPivotTable=zL,e.UIPlugin=cb,e.__info__=AZ,e.addFunction=RZ,e.addRenderingLayer=pr,e.astToFormula=yB,e.categories=bO,e.chartHelpers=BZ,e.components=FZ,e.constants=zZ,e.convertAstNodes=JO,e.coreTypes=Vs,e.createAutocompleteArgumentsProvider=hq,e.findCellInNewZone=Ln,e.functionCache=cU,e.getCaretDownSvg=ZA,e.getCaretUpSvg=QA,e.helpers=NZ,e.hooks=IZ,e.invalidateCFEvaluationCommands=Ls,e.invalidateChartEvaluationCommands=Fs,e.invalidateDependenciesCommands=Is,e.invalidateEvaluationCommands=Ps,e.iterateAstNodes=YO,e.links=PZ,e.load=sP,e.parse=KO,e.parseTokens=qO,e.readonlyAllowedCommands=Bs,e.registries=MZ,e.setDefaultSheetViewSize=Fe,e.setTranslationMethod=ca,e.stores=LZ,e.tokenColors=He,e.tokenize=bu,AZ.version=`19.1.21`,AZ.date=`2026-05-27T05:56:49.891Z`,AZ.hash=`99ebe93`})(this.o_spreadsheet=this.o_spreadsheet||{},owl);
|