@odoo/o-spreadsheet 18.0.80 → 18.0.82
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.
|
@@ -11,7 +11,7 @@ Did you forget to inject your store instance?
|
|
|
11
11
|
|
|
12
12
|
const stores = useStoreProvider();
|
|
13
13
|
stores.inject(MyMetaStore, storeInstance);
|
|
14
|
-
`)}}return t}var cd=class{get;disposeCallbacks=[];constructor(e){this.get=e}onDispose(e){this.disposeCallbacks.push(e)}dispose(){this.disposeCallbacks.forEach(e=>e())}};function ld(){let e=(0,t.useEnv)();if(e.__spreadsheet_stores__ instanceof ad)return e.__spreadsheet_stores__;let n=new ad;return(0,t.useSubEnv)({__spreadsheet_stores__:n,getStore:e=>fd(n.get(e),()=>n.trigger(`store-updated`))}),n}function V(e){let n=pd((0,t.useEnv)());return dd(n,n.get(e))}function ud(e,...n){let r=pd((0,t.useEnv)()),i=r.instantiate(e,...n);return(0,t.onWillUnmount)(()=>i.dispose()),dd(r,i)}function dd(e,n){let r=(0,t.useComponent)();return fd(n,()=>{(0,t.status)(r)===`mounted`&&e.trigger(`store-updated`)})}function fd(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 pd(e){let t=e.__spreadsheet_stores__;if(!(t instanceof ad))throw Error(`No store provider found. Did you forget to call useStoreProvider()?`);return t}let md=sd(`Model`);var hd=class{mutators=[`register`,`unRegister`,`drawLayer`];renderers={};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){let n=this.renderers[t];if(n)for(let r of n)e.ctx.save(),r.drawLayer(e,t),e.ctx.restore();return`noStateChange`}},gd=class extends cd{model=this.get(md);getters=this.model.getters;renderer=this.get(hd);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){}};let _d={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 vd=class extends gd{mutators=[`focusComposer`,`focusActiveComposer`];activeComposer=_d;_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)}};function yd(e,t,n,r){let i=!1,a=[];for(let r in n){let o=n[r];if(o.labelCell){let e=Sd(o.labelCell,t);o.labelCell!==e&&(i=!0,o={...o,labelCell:e})}let s=Sd(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=Sd(o,t);s!==o&&(i=!0,o=s);let c=a.filter(S);return{isStale:i,dataSets:c,labelRange:o}}function bd(e,t,n){return n.map(n=>({dataRange:Gs(e,t,n.dataRange),labelCell:n.labelCell?Gs(e,t,n.labelCell):void 0}))}function xd(e,t,n){return n?Gs(e,t,n):void 0}function Sd(e,t){if(!e)return;let n=t(e);switch(n.changeType){case`NONE`:return e;case`REMOVE`:return;default:return n.range}}function Cd(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({...wd(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})}}else i.push({...wd(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})}return i}function wd(e,t,n,r){if(n.left!==n.right&&n.top!==n.bottom)throw Error(`Zone should be a single column or row: ${nr(n)}`);if(r){let i=nr(n),a=nr(r);return{labelCell:e.getRangeFromSheetXC(t,a),dataRange:e.getRangeFromSheetXC(t,i)}}else return{labelCell:void 0,dataRange:e.getRangeFromSheetXC(t,nr(n))}}function Td(e,t){let n=t.labelCell?.zone,r=t.dataRange.zone;if(n){let{numberOfRows:e,numberOfCols:t}=mr(r);e===1?r={...r,left:r.left+1}:t===1&&(r={...r,top:r.top+1})}let i=t.dataRange.clone({zone:r}),a={};return t.customLabel?a={text:t.customLabel}:t.labelCell&&(a={reference:e.getRangeString(t.labelCell,`forceSheetReference`,{useBoundedReference:!0})}),{label:a,range:e.getRangeString(i,`forceSheetReference`,{useBoundedReference:!0}),backgroundColor:t.backgroundColor,rightYAxis:t.rightYAxis}}function Ed(e,t,n){if(!t)return;let r={...t.zone};n&&t.zone.bottom>t.zone.top&&(r.top+=1);let i=t.clone({zone:r});return e.getRangeString(i,`forceSheetReference`,{useBoundedReference:!0})}function Dd(e,t){let n;if(e.labelRange){let r=nd(Qn(e.labelRange),t);n=r?nr(r):void 0}let r=e.dataSets.map(e=>Qn(e.dataRange)).map(e=>nd(e,t)).filter(S).map(e=>({dataRange:nr(e)}));return{...e,labelRange:n,dataSets:r}}function Od(e){return e&&on(e)<.3?`#FFFFFF`:`#000000`}function kd(e){return e.dataSets&&(e.dataSets.find(e=>!Is.test(e.dataRange))!==void 0||e.dataSets.map(e=>Qn(e.dataRange)).some(e=>e.top!==e.bottom&&Tr(e)))?`InvalidDataSet`:`Success`}function Ad(e){return e.labelRange&&!Is.test(e.labelRange||``)?`InvalidLabelRange`:`Success`}function jd(e,t,n){if(!n||!e)return!1;if(!t)return!0;let r=Dr(t.dataRange.zone);return!(Dr(e.zone)<r)}function Md(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 Nd(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`},align:r===`left`?`start`:r===`right`?`end`:`center`}}}function Pd(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 Fd({displayTitle:e,displayLegend:t}){let n=25;return e?n=0:t&&(n=10),{left:20,right:20,top:n,bottom:10}}function Id(e,t){let n=[],r=[],i=[];if(t.hidden)return;for(let e=0;e<t.data.length;e++)typeof t.data[e]==`number`&&(n.push(t.data[e]),r.push(e+1)),i.push(e+1);let a=x(.5,i.length+.55,.2),o=Rd(e,n,r,a);if(o.length)return Ld(t,e,o,a)}function Ld(e,t,n,r){let i=ln(e.backgroundColor);i.a=1;let a=t.color||gn(cn(i),.5);return{type:`line`,xAxisID:`x1`,yAxisID:e.yAxisID,label:e.label?T(`Trend line for %s`,e.label):``,data:n.map((e,t)=>({x:r[t],y:e})),order:-1,showLine:!0,pointRadius:0,backgroundColor:a,borderColor:a,borderDash:[5,5],borderWidth:void 0,fill:!1,pointBackgroundColor:a}}function Rd(e,t,n,r){if(t.length<2||n.length<2||r.length===0)return[];let{normalizedLabels:i,normalizedNewLabels:a}=zd(n,r,e);try{switch(e.type){case`polynomial`:{let n=e.order;if(!n)return Array.from({length:r.length},()=>NaN);if(n===1)return Ul([t],[i],[a],!0)[0];let o=Rl(t,i,n,!0).flat();return a.map(e=>Bl(o,e,n))}case`exponential`:{let e=[],n=[];for(let r=0;r<t.length;r++)t[r]>0&&(e.push(Math.log(t[r])),n.push(i[r]));return n.length?Vl(Ul([e],[n],[a],!0))[0]:Array.from({length:r.length},()=>NaN)}case`logarithmic`:return Ul([t],Hl([i]),Hl([a]),!0)[0];default:return[]}}catch{return Array.from({length:r.length},()=>NaN)}}function zd(e,t,n){let r=[],i=[];if(n.type===`logarithmic`){let n=Math.max(...e.map(Math.abs));r=e.map(e=>e/n),i=t.map(e=>e/n)}else{let n=Math.max(...e),a=n-Math.min(...e);r=e.map(e=>(e-n)/a),i=t.map(e=>(e-n)/a)}return{normalizedLabels:r,normalizedNewLabels:i}}function Bd(e){return t=>{if(t=Number(t),isNaN(t))return t;let{locale:n,format:r}=e;return B(t,{locale:n,format:!r&&Math.abs(t)>=1e3?`#,##`:r})}}function Vd(e,t){return new wn(t,e.dataSets.map(e=>e.backgroundColor))}let Hd=[{value:`left`,label:T(`Left`)},{value:`right`,label:T(`Right`)}],Ud={id:`chartShowValuesPlugin`,afterDatasetsDraw(e,t,n){if(!n.showValues||!e._metasets?.[0]?.data)return;let r=e.ctx;switch(r.save(),r.textAlign=`center`,r.textBaseline=`middle`,r.miterLimit=1,e.config.type){case`pie`:case`doughnut`:qd(e,n,r);break;case`bar`:case`line`:n.horizontal?Kd(e,n,r):Gd(e,n,r);break}r.restore()}};function Wd(e,t,n,r){r.lineWidth=3,r.strokeText(e,t,n),r.lineWidth=1,r.fillText(e,t,n)}function Gd(e,t,n){let r={};for(let i of e._metasets){if(i.xAxisID===`x1`)return;for(let a=0;a<i._parsed.length;a++){let o=i._parsed[a].y,s=i.data[a],c=s.x,l=0;l=e.config.type===`line`?s.y-10:o<0?s.y-s.height/2:s.y+s.height/2,r[c]||(r[c]=[]);for(let e of r[c]||[])Math.abs(e-l)<13&&(l=e-13);r[c].push(l),n.fillStyle=s.options.backgroundColor,n.strokeStyle=t.background||`#ffffff`,Wd(t.callback(Number(o),i,a),c,l,n)}}}function Kd(e,t,n){let r={};for(let i of e._metasets){if(i.xAxisID===`x1`)return;for(let e=0;e<i._parsed.length;e++){let a=i._parsed[e].x,o=t.callback(a,i,e),s=i.data[e],c=s.y,l=a<0?s.x+s.width/2:s.x-s.width/2;r[c]||(r[c]=[]);let u=cc(n,o,{fontSize:12},`px`);for(let e of r[c])Math.abs(e-l)<u&&(l=e+u+3);r[c].push(l),n.fillStyle=s.options.backgroundColor,n.strokeStyle=t.background||`#ffffff`,Wd(o,l,c,n)}}}function qd(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=cc(n,m,{fontSize:12},`px`),g=l-c;if(h>=g||g<12)continue;let _=s-o,v=2*d*Math.tan(_/2);_<Math.PI/2&&(h>=v||v<12)||(n.fillStyle=Od(t.background),n.strokeStyle=t.background||`#ffffff`,Wd(m,f,p,n))}}let Jd={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=Xd(r,e);if(!n)break;let a=Yd(t),o=Yd(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 Yd(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 Xd(e,t){return e.find((e,n)=>n>t&&e.height!==0)}var Zd=class{xmlString;constructor(e){this.xmlString=e}toString(){return this.xmlString}};let Qd=[`areaChart`,`area3DChart`,`lineChart`,`line3DChart`,`stockChart`,`radarChart`,`scatterChart`,`pieChart`,`pie3DChart`,`doughnutChart`,`barChart`,`bar3DChart`,`ofPieChart`,`surfaceChart`,`surface3DChart`,`bubbleChart`,`comboChart`],$d=`000000`,ef={arrows:`3Arrows`,smiley:`3Symbols`,dots:`3TrafficLights1`},tf={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`},nf=`http://schemas.openxmlformats.org/drawingml/2006/main`,rf=`http://schemas.openxmlformats.org/drawingml/2006/chart`,af={workbook:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.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`},of={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`},sf=`http://schemas.openxmlformats.org/officeDocument/2006/relationships`,cf=.75,lf=.143,uf=8.43,df=12.75,ff={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}]},pf=`ACOT,ACOTH,AGGREGATE,ARABIC,BASE,BETA.DIST,BETA.INV,BINOM.DIST,BINOM.DIST.RANGE,BINOM.INV,BITAND,BITLSHIFT,BITOR,BITRSHIFT,BITXOR,BYCOL,BYROW,CEILING.MATH,CEILING.PRECISE,CHISQ.DIST,CHISQ.DIST.RT,CHISQ.INV,CHISQ.INV.RT,CHISQ.TEST,CHOOSECOLS,CHOOSEROWS,COMBINA,CONCAT,CONFIDENCE.NORM,CONFIDENCE.T,COT,COTH,COVARIANCE.P,COVARIANCE.S,CSC,CSCH,DAYS,DECIMAL,DROP,ERF.PRECISE,ERFC.PRECISE,EXPAND,EXPON.DIST,F.DIST,F.DIST.RT,F.INV,F.INV.RT,F.TEST,FIELDVALUE,FILTERXML,FLOOR.MATH,FLOOR.PRECISE,FORECAST.ETS,FORECAST.ETS.CONFINT,FORECAST.ETS.SEASONALITY,FORECAST.ETS.STAT,FORECAST.LINEAR,FORMULATEXT,GAMMA,GAMMA.DIST,GAMMA.INV,GAMMALN.PRECISE,GAUSS,HSTACK,HYPGEOM.DIST,IFNA,IFS,IMCOSH,IMCOT,IMCSC,IMCSCH,IMSEC,IMSECH,IMSINH,IMTAN,ISFORMULA,ISOMITTED,ISOWEEKNUM,LAMBDA,LET,LOGNORM.DIST,LOGNORM.INV,MAKEARRAY,MAP,MAXIFS,MINIFS,MODE.MULT,MODE.SNGL,MUNIT,NEGBINOM.DIST,NORM.DIST,NORM.INV,NORM.S.DIST,NORM.S.INV,NUMBERVALUE,PDURATION,PERCENTILE.EXC,PERCENTILE.INC,PERCENTRANK.EXC,PERCENTRANK.INC,PERMUTATIONA,PHI,POISSON.DIST,PQSOURCE,PYTHON_STR,PYTHON_TYPE,PYTHON_TYPENAME,QUARTILE.EXC,QUARTILE.INC,QUERYSTRING,RANDARRAY,RANK.AVG,RANK.EQ,REDUCE,RRI,SCAN,SEC,SECH,SEQUENCE,SHEET,SHEETS,SKEW.P,SORTBY,STDEV.P,STDEV.S,SWITCH,T.DIST,T.DIST.2T,T.DIST.RT,T.INV,T.INV.2T,T.TEST,TAKE,TEXTAFTER,TEXTBEFORE,TEXTJOIN,TEXTSPLIT,TOCOL,TOROW,UNICHAR,UNICODE,UNIQUE,VAR.P,VAR.S,VSTACK,WEBSERVICE,WEIBULL.DIST,WRAPCOLS,WRAPROWS,XLOOKUP,XOR,Z.TEST`.split(`,`),mf=new h,hf={},gf=0;function H(e,...t){let n=`__sheet__${gf++}`;return vf(n,String.raw(e,...t)),yf(n),n}function _f(e){let t=e.split(/(\{|\}|;)/).map(e=>e.trim()),n=[],r=[],i=[];function a(e,t){let r=[];for(let i of n[e]){let o=t&&t+` `+i||i;o.includes(`&`)&&(o=i.replace(/&/g,t||``)),e<n.length-1&&(o=a(e+1,o)),r.push(o)}return r.join(`, `)}function o(){i.length&&(r.push(a(0)+` {`),r.push(...i),r.push(`}`),i=[])}for(;t.length;){let e=t.shift();e===`}`?(o(),n.pop()):(t[0]===`{`&&(o(),n.push(e.split(/\s*,\s*/)),t.shift()),t[0]===`;`&&i.push(` `+e+`;`))}return r.join(`
|
|
14
|
+
`)}}return t}var cd=class{get;disposeCallbacks=[];constructor(e){this.get=e}onDispose(e){this.disposeCallbacks.push(e)}dispose(){this.disposeCallbacks.forEach(e=>e())}};function ld(){let e=(0,t.useEnv)();if(e.__spreadsheet_stores__ instanceof ad)return e.__spreadsheet_stores__;let n=new ad;return(0,t.useSubEnv)({__spreadsheet_stores__:n,getStore:e=>fd(n.get(e),()=>n.trigger(`store-updated`))}),n}function V(e){let n=pd((0,t.useEnv)());return dd(n,n.get(e))}function ud(e,...n){let r=pd((0,t.useEnv)()),i=r.instantiate(e,...n);return(0,t.onWillUnmount)(()=>i.dispose()),dd(r,i)}function dd(e,n){let r=(0,t.useComponent)();return fd(n,()=>{(0,t.status)(r)===`mounted`&&e.trigger(`store-updated`)})}function fd(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 pd(e){let t=e.__spreadsheet_stores__;if(!(t instanceof ad))throw Error(`No store provider found. Did you forget to call useStoreProvider()?`);return t}let md=sd(`Model`);var hd=class{mutators=[`register`,`unRegister`,`drawLayer`];renderers={};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){let n=this.renderers[t];if(n)for(let r of n)e.ctx.save(),r.drawLayer(e,t),e.ctx.restore();return`noStateChange`}},gd=class extends cd{model=this.get(md);getters=this.model.getters;renderer=this.get(hd);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){}};let _d={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 vd=class extends gd{mutators=[`focusComposer`,`focusActiveComposer`];activeComposer=_d;_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)}};function yd(e,t,n,r){let i=!1,a=[];for(let r in n){let o=n[r];if(o.labelCell){let e=Sd(o.labelCell,t);o.labelCell!==e&&(i=!0,o={...o,labelCell:e})}let s=Sd(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=Sd(o,t);s!==o&&(i=!0,o=s);let c=a.filter(S);return{isStale:i,dataSets:c,labelRange:o}}function bd(e,t,n){return n.map(n=>({dataRange:Gs(e,t,n.dataRange),labelCell:n.labelCell?Gs(e,t,n.labelCell):void 0}))}function xd(e,t,n){return n?Gs(e,t,n):void 0}function Sd(e,t){if(!e)return;let n=t(e);switch(n.changeType){case`NONE`:return e;case`REMOVE`:return;default:return n.range}}function Cd(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({...wd(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})}}else i.push({...wd(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})}return i}function wd(e,t,n,r){if(n.left!==n.right&&n.top!==n.bottom)throw Error(`Zone should be a single column or row: ${nr(n)}`);if(r){let i=nr(n),a=nr(r);return{labelCell:e.getRangeFromSheetXC(t,a),dataRange:e.getRangeFromSheetXC(t,i)}}else return{labelCell:void 0,dataRange:e.getRangeFromSheetXC(t,nr(n))}}function Td(e,t){let n=t.labelCell?.zone,r=t.dataRange.zone;if(n){let{numberOfRows:e,numberOfCols:t}=mr(r);e===1?r={...r,left:r.left+1}:t===1&&(r={...r,top:r.top+1})}let i=t.dataRange.clone({zone:r}),a={};return t.customLabel?a={text:t.customLabel}:t.labelCell&&(a={reference:e.getRangeString(t.labelCell,`forceSheetReference`,{useBoundedReference:!0})}),{label:a,range:e.getRangeString(i,`forceSheetReference`,{useBoundedReference:!0}),backgroundColor:t.backgroundColor,rightYAxis:t.rightYAxis}}function Ed(e,t,n){if(!t)return;let r={...t.zone};n&&t.zone.bottom>t.zone.top&&(r.top+=1);let i=t.clone({zone:r});return e.getRangeString(i,`forceSheetReference`,{useBoundedReference:!0})}function Dd(e,t){let n;if(e.labelRange){let r=nd(Qn(e.labelRange),t);n=r?nr(r):void 0}let r=e.dataSets.map(e=>Qn(e.dataRange)).map(e=>nd(e,t)).filter(S).map(e=>({dataRange:nr(e)}));return{...e,labelRange:n,dataSets:r}}function Od(e){return e&&on(e)<.3?`#FFFFFF`:`#000000`}function kd(e){return e.dataSets&&(e.dataSets.find(e=>!Is.test(e.dataRange))!==void 0||e.dataSets.map(e=>Qn(e.dataRange)).some(e=>e.top!==e.bottom&&Tr(e)))?`InvalidDataSet`:`Success`}function Ad(e){return e.labelRange&&!Is.test(e.labelRange||``)?`InvalidLabelRange`:`Success`}function jd(e,t,n){if(!n||!e)return!1;if(!t)return!0;let r=Dr(t.dataRange.zone);return!(Dr(e.zone)<r)}function Md(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 Nd(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`},align:r===`left`?`start`:r===`right`?`end`:`center`}}}function Pd(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 Fd({displayTitle:e,displayLegend:t}){let n=25;return e?n=0:t&&(n=10),{left:20,right:20,top:n,bottom:10}}function Id(e,t){let n=[],r=[],i=[];if(t.hidden)return;for(let e=0;e<t.data.length;e++)typeof t.data[e]==`number`&&(n.push(t.data[e]),r.push(e+1)),i.push(e+1);let a=x(.5,i.length+.55,.2),o=Rd(e,n,r,a);if(o.length)return Ld(t,e,o,a)}function Ld(e,t,n,r){let i=ln(e.backgroundColor);i.a=1;let a=t.color||gn(cn(i),.5);return{type:`line`,xAxisID:`x1`,yAxisID:e.yAxisID,label:e.label?T(`Trend line for %s`,e.label):``,data:n.map((e,t)=>({x:r[t],y:e})),order:-1,showLine:!0,pointRadius:0,backgroundColor:a,borderColor:a,borderDash:[5,5],borderWidth:void 0,fill:!1,pointBackgroundColor:a}}function Rd(e,t,n,r){if(t.length<2||n.length<2||r.length===0)return[];let{normalizedLabels:i,normalizedNewLabels:a}=zd(n,r,e);try{switch(e.type){case`polynomial`:{let n=e.order;if(!n)return Array.from({length:r.length},()=>NaN);if(n===1)return Ul([t],[i],[a],!0)[0];let o=Rl(t,i,n,!0).flat();return a.map(e=>Bl(o,e,n))}case`exponential`:{let e=[],n=[];for(let r=0;r<t.length;r++)t[r]>0&&(e.push(Math.log(t[r])),n.push(i[r]));return n.length?Vl(Ul([e],[n],[a],!0))[0]:Array.from({length:r.length},()=>NaN)}case`logarithmic`:return Ul([t],Hl([i]),Hl([a]),!0)[0];default:return[]}}catch{return Array.from({length:r.length},()=>NaN)}}function zd(e,t,n){let r=[],i=[];if(n.type===`logarithmic`){let n=Math.max(...e.map(Math.abs));r=e.map(e=>e/n),i=t.map(e=>e/n)}else{let n=Math.max(...e),a=n-Math.min(...e);r=e.map(e=>(e-n)/a),i=t.map(e=>(e-n)/a)}return{normalizedLabels:r,normalizedNewLabels:i}}function Bd(e){return t=>{if(t=Number(t),isNaN(t))return t;let{locale:n,format:r}=e;return B(t,{locale:n,format:!r&&Math.abs(t)>=1e3?`#,##`:r})}}function Vd(e,t){return new wn(t,e.dataSets.map(e=>e.backgroundColor))}let Hd=[{value:`left`,label:T(`Left`)},{value:`right`,label:T(`Right`)}],Ud={id:`chartShowValuesPlugin`,afterDatasetsDraw(e,t,n){if(!n.showValues||!e._metasets?.[0]?.data)return;let r=e.ctx;switch(r.save(),r.textAlign=`center`,r.textBaseline=`middle`,r.miterLimit=1,e.config.type){case`pie`:case`doughnut`:qd(e,n,r);break;case`combo`:case`bar`:case`line`:n.horizontal?Kd(e,n,r):Gd(e,n,r);break}r.restore()}};function Wd(e,t,n,r){r.lineWidth=3,r.strokeText(e,t,n),r.lineWidth=1,r.fillText(e,t,n)}function Gd(e,t,n){let r={};for(let i of e._metasets){if(i.xAxisID===`x1`)return;for(let e=0;e<i._parsed.length;e++){let a=i._parsed[e].y,o=i.data[e],s=o.x,c=0;c=i.type===`line`?o.y-10:a<0?o.y-o.height/2:o.y+o.height/2,r[s]||(r[s]=[]);for(let e of r[s]||[])Math.abs(e-c)<13&&(c=e-13);r[s].push(c),n.fillStyle=o.options.backgroundColor,n.strokeStyle=t.background||`#ffffff`,Wd(t.callback(Number(a),i,e),s,c,n)}}}function Kd(e,t,n){let r={};for(let i of e._metasets){if(i.xAxisID===`x1`)return;for(let e=0;e<i._parsed.length;e++){let a=i._parsed[e].x,o=t.callback(a,i,e),s=i.data[e],c=s.y,l=a<0?s.x+s.width/2:s.x-s.width/2;r[c]||(r[c]=[]);let u=cc(n,o,{fontSize:12},`px`);for(let e of r[c])Math.abs(e-l)<u&&(l=e+u+3);r[c].push(l),n.fillStyle=s.options.backgroundColor,n.strokeStyle=t.background||`#ffffff`,Wd(o,l,c,n)}}}function qd(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=cc(n,m,{fontSize:12},`px`),g=l-c;if(h>=g||g<12)continue;let _=s-o,v=2*d*Math.tan(_/2);_<Math.PI/2&&(h>=v||v<12)||(n.fillStyle=Od(t.background),n.strokeStyle=t.background||`#ffffff`,Wd(m,f,p,n))}}let Jd={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=Xd(r,e);if(!n)break;let a=Yd(t),o=Yd(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 Yd(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 Xd(e,t){return e.find((e,n)=>n>t&&e.height!==0)}var Zd=class{xmlString;constructor(e){this.xmlString=e}toString(){return this.xmlString}};let Qd=[`areaChart`,`area3DChart`,`lineChart`,`line3DChart`,`stockChart`,`radarChart`,`scatterChart`,`pieChart`,`pie3DChart`,`doughnutChart`,`barChart`,`bar3DChart`,`ofPieChart`,`surfaceChart`,`surface3DChart`,`bubbleChart`,`comboChart`],$d=`000000`,ef={arrows:`3Arrows`,smiley:`3Symbols`,dots:`3TrafficLights1`},tf={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`},nf=`http://schemas.openxmlformats.org/drawingml/2006/main`,rf=`http://schemas.openxmlformats.org/drawingml/2006/chart`,af={workbook:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.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`},of={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`},sf=`http://schemas.openxmlformats.org/officeDocument/2006/relationships`,cf=.75,lf=.143,uf=8.43,df=12.75,ff={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}]},pf=`ACOT,ACOTH,AGGREGATE,ARABIC,BASE,BETA.DIST,BETA.INV,BINOM.DIST,BINOM.DIST.RANGE,BINOM.INV,BITAND,BITLSHIFT,BITOR,BITRSHIFT,BITXOR,BYCOL,BYROW,CEILING.MATH,CEILING.PRECISE,CHISQ.DIST,CHISQ.DIST.RT,CHISQ.INV,CHISQ.INV.RT,CHISQ.TEST,CHOOSECOLS,CHOOSEROWS,COMBINA,CONCAT,CONFIDENCE.NORM,CONFIDENCE.T,COT,COTH,COVARIANCE.P,COVARIANCE.S,CSC,CSCH,DAYS,DECIMAL,DROP,ERF.PRECISE,ERFC.PRECISE,EXPAND,EXPON.DIST,F.DIST,F.DIST.RT,F.INV,F.INV.RT,F.TEST,FIELDVALUE,FILTERXML,FLOOR.MATH,FLOOR.PRECISE,FORECAST.ETS,FORECAST.ETS.CONFINT,FORECAST.ETS.SEASONALITY,FORECAST.ETS.STAT,FORECAST.LINEAR,FORMULATEXT,GAMMA,GAMMA.DIST,GAMMA.INV,GAMMALN.PRECISE,GAUSS,HSTACK,HYPGEOM.DIST,IFNA,IFS,IMCOSH,IMCOT,IMCSC,IMCSCH,IMSEC,IMSECH,IMSINH,IMTAN,ISFORMULA,ISOMITTED,ISOWEEKNUM,LAMBDA,LET,LOGNORM.DIST,LOGNORM.INV,MAKEARRAY,MAP,MAXIFS,MINIFS,MODE.MULT,MODE.SNGL,MUNIT,NEGBINOM.DIST,NORM.DIST,NORM.INV,NORM.S.DIST,NORM.S.INV,NUMBERVALUE,PDURATION,PERCENTILE.EXC,PERCENTILE.INC,PERCENTRANK.EXC,PERCENTRANK.INC,PERMUTATIONA,PHI,POISSON.DIST,PQSOURCE,PYTHON_STR,PYTHON_TYPE,PYTHON_TYPENAME,QUARTILE.EXC,QUARTILE.INC,QUERYSTRING,RANDARRAY,RANK.AVG,RANK.EQ,REDUCE,RRI,SCAN,SEC,SECH,SEQUENCE,SHEET,SHEETS,SKEW.P,SORTBY,STDEV.P,STDEV.S,SWITCH,T.DIST,T.DIST.2T,T.DIST.RT,T.INV,T.INV.2T,T.TEST,TAKE,TEXTAFTER,TEXTBEFORE,TEXTJOIN,TEXTSPLIT,TOCOL,TOROW,UNICHAR,UNICODE,UNIQUE,VAR.P,VAR.S,VSTACK,WEBSERVICE,WEIBULL.DIST,WRAPCOLS,WRAPROWS,XLOOKUP,XOR,Z.TEST`.split(`,`),mf=new h,hf={},gf=0;function H(e,...t){let n=`__sheet__${gf++}`;return vf(n,String.raw(e,...t)),yf(n),n}function _f(e){let t=e.split(/(\{|\}|;)/).map(e=>e.trim()),n=[],r=[],i=[];function a(e,t){let r=[];for(let i of n[e]){let o=t&&t+` `+i||i;o.includes(`&`)&&(o=i.replace(/&/g,t||``)),e<n.length-1&&(o=a(e+1,o)),r.push(o)}return r.join(`, `)}function o(){i.length&&(r.push(a(0)+` {`),r.push(...i),r.push(`}`),i=[])}for(;t.length;){let e=t.shift();e===`}`?(o(),n.pop()):(t[0]===`{`&&(o(),n.push(e.split(/\s*,\s*/)),t.shift()),t[0]===`;`&&i.push(` `+e+`;`))}return r.join(`
|
|
15
15
|
`)}function vf(e,t){let n=document.createElement(`style`);n.textContent=_f(t),hf[e]=n}function yf(e){let t=hf[e];t.setAttribute(`component`,e),document.head.appendChild(t)}function bf({strikethrough:e,underline:t}){return!e&&!t?`none`:`${e?`line-through`:``} ${t?`underline`:``}`}function xf(e){let t=Sf(e);return e&&e.fillColor&&(t.background=e.fillColor),t}function Sf(e){let t={};if(!e)return t;if(e.bold&&(t[`font-weight`]=`bold`),e.italic&&(t[`font-style`]=`italic`),e.strikethrough||e.underline){let n=e.strikethrough?`line-through`:``;n=e.underline?n+` underline`:n,t[`text-decoration`]=n}return e.textColor&&(t.color=e.textColor),t}function U(e){let t=``;for(let n in e)e[n]&&(t+=`${n}:${e[n]}; `);return t}function Cf(e){let t=window.getComputedStyle(e);return{top:parseInt(t.marginTop,10)||0,bottom:parseInt(t.marginBottom,10)||0,left:parseInt(t.marginLeft,10)||0,right:parseInt(t.marginRight,10)||0}}H`
|
|
16
16
|
.o-spreadsheet {
|
|
17
17
|
.o-icon {
|
|
@@ -43,7 +43,7 @@ stores.inject(MyMetaStore, storeInstance);
|
|
|
43
43
|
<Default Extension="${e}" ContentType="${t}" />
|
|
44
44
|
`}function q(e){return new Zd(e.join(`
|
|
45
45
|
`))}function J(e,...t){let n=[e[0]];for(let r=0;r<t.length;r++){let i=t[r]instanceof Zd?t[r]:th(t[r]);n.push(i+e[r+1])}return new Zd(Tt(n))}function sh(e){return e.replace(/NAMESPACE.*NAMESPACE(.*)/,`$1`)}function ch(e){return e.replaceAll(/(<\/?)([a-zA-Z0-9]+):([a-zA-Z0-9]+)/g,`$1NAMESPACE$2NAMESPACE$3`)}function lh(e){return e.replaceAll(/([a-zA-Z0-9]+):([a-zA-Z0-9]+)/g,`NAMESPACE$1NAMESPACE$2`)}var uh=class{value;constructor(e){this.value=e}asString(){return kf(String(this.value))}asBool(){return this.value===`true`?!0:this.value===`false`?!1:!!Number(this.value)}asNum(){return Number(this.value)}},dh=class{rootFile;xlsxFileStructure;warningManager;relationships;currentFile=void 0;constructor(e,t,n){this.rootFile=e,this.currentFile=e.file.fileName,this.xlsxFileStructure=t,this.warningManager=n,this.relationships={},e.rels&&this.extractRelationships(e.rels).map(e=>{this.relationships[e.id]=e})}extractRelationships(e){return this.mapOnElements({parent:e.xml,query:`Relationship`},e=>({id:this.extractAttr(e,`Id`,{required:!0}).asString(),target:this.extractAttr(e,`Target`,{required:!0}).asString(),type:this.extractAttr(e,`Type`,{required:!0}).asString()}))}getListOfXMLFiles(){return Object.entries(this.xlsxFileStructure).filter(([e])=>e!==`images`).map(([e,t])=>t).flat().filter(S)}mapOnElements(e,t){let n=[],r=this.currentFile,i;if(i=e.children?this.querySelector(e.parent,e.query)?.children||[]:this.querySelectorAll(e.parent,e.query),i)for(let e of i)try{n.push(t(e))}catch(t){this.catchErrorOnElement(t,e)}return this.currentFile=r,n}catchErrorOnElement(e,t){let n=t?`Error when parsing an element <${t.tagName}> of file ${this.currentFile}, skip this element. \n${e.stack}`:`Error when parsing file ${this.currentFile}.`;this.warningManager.addParsingWarning([n,e.message].join(`
|
|
46
|
-
`))}extractAttr(e,t,n){let r=e.attributes[t];r||this.handleMissingValue(e,`attribute "${t}"`,n);let i=r?.value?r.value:n?.default;return i===void 0?void 0:new uh(i)}extractTextContent(e,t){if(t?.default!==void 0&&typeof t.default!=`string`)throw Error(`extractTextContent default value should be a string`);let n=e?.attributes[`xml:space`]?.value===`preserve`,r=e?.textContent;return(!e||r===null)&&this.handleMissingValue(e,`text content`,t),r&&=n?r:r.trim(),r?kf(r):t?.default}extractChildAttr(e,t,n,r){let i;i=typeof t==`number`?e.children[t]:this.querySelector(e,t),i||this.handleMissingValue(e,typeof t==`number`?`child at index ${t}`:`child <${t}>`,r);let a=i?this.extractAttr(i,n,r)?.asString():r?.default;return a===void 0?void 0:new uh(a)}extractChildTextContent(e,t,n){if(n?.default!==void 0&&typeof n.default!=`string`)throw Error(`extractTextContent default value should be a string`);let r=this.querySelector(e,t);return r||this.handleMissingValue(e,`child <${t}>`,n),r?this.extractTextContent(r,n):n?.default}handleMissingValue(e,t,n){if(n?.required)if(n?.default!==void 0)this.warningManager.addParsingWarning(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, replacing it by the default value ${n.default}`);else throw Error(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, and no default value was set`)}extractColor(e,t,n){if(!e)return n?{rgb:n}:void 0;let r=this.extractAttr(e,`theme`)?.asString(),i;if(r!==void 0){if(!t||!t.clrScheme)throw Error(`Color referencing a theme but no theme was provided`);i=this.getThemeColor(r,t.clrScheme)}else i=this.extractAttr(e,`rgb`)?.asString(),i=i===`FF000000`?void 0:i;return{rgb:i||n,auto:this.extractAttr(e,`auto`)?.asBool(),indexed:this.extractAttr(e,`indexed`)?.asNum(),tint:this.extractAttr(e,`tint`)?.asNum()}}getTargetXmlFile(e){if(!e)throw Error(`Undefined target file`);let t=this.processRelationshipTargetName(e.target),n=this.getListOfXMLFiles().find(e=>e.file.fileName.endsWith(t));if(!n||!n.file)throw Error(`Cannot find target file`);return n}getTargetImageFile(e){if(!e)throw Error(`Undefined target file`);let t=this.processRelationshipTargetName(e.target),n=this.xlsxFileStructure.images.find(e=>e.fileName.endsWith(t));if(!n)throw Error(`Cannot find target file`);return n}querySelector(e,t){let n=lh(t);return e.querySelector(n)}querySelectorAll(e,t){let n=lh(t);return e.querySelectorAll(n)}getThemeColor(e,t){switch(e){case`0`:return`FFFFFF`;case`1`:return`000000`;case`2`:return t[3].value;case`3`:return t[2].value;default:return t[e].value}}processRelationshipTargetName(e){return e.replace(/\.+\//,``)}},fh=class extends dh{getTheme(){return{clrScheme:this.mapOnElements({query:`a:clrScheme`,parent:this.rootFile.file.xml,children:!0},e=>({name:e.tagName,value:this.extractChildAttr(e,0,`val`,{required:!0,default:$d}).asString(),lastClr:this.extractChildAttr(e,0,`lastClr`,{default:$d}).asString()}))}}getSharedStrings(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`si`},e=>this.mapOnElements({parent:e,query:`t`},e=>this.extractTextContent(e)||``).join(``))}},ph=class extends dh{theme;constructor(e,t,n,r){super(e,t,n),this.theme=r}extractConditionalFormattings(){let e=this.mapOnElements({parent:this.rootFile.file.xml,query:`worksheet > conditionalFormatting`},e=>({sqref:this.extractAttr(e,`sqref`,{required:!0}).asString().split(` `),pivot:this.extractAttr(e,`pivot`)?.asBool(),cfRules:this.extractCFRules(e,this.theme)}));return e.push(...this.mapOnElements({parent:this.rootFile.file.xml,query:`extLst x14:conditionalFormatting`},e=>({sqref:this.extractChildTextContent(e,`xm:sqref`,{required:!0}).split(` `),pivot:this.extractAttr(e,`xm:pivot`)?.asBool(),cfRules:this.extractCFRules(e,this.theme)}))),e}extractCFRules(e,t){return this.mapOnElements({parent:e,query:`cfRule, x14:cfRule`},e=>{let n=this.extractAttr(e,`type`,{required:!0}).asString();if(n===`dataBar`)throw Error(`Databars conditional formats are not supported.`);return{type:n,priority:this.extractAttr(e,`priority`,{required:!0}).asNum(),colorScale:this.extractCfColorScale(e,t),formula:this.extractCfFormula(e),iconSet:this.extractCfIconSet(e),dxfId:this.extractAttr(e,`dxfId`)?.asNum(),stopIfTrue:this.extractAttr(e,`stopIfTrue`)?.asBool(),aboveAverage:this.extractAttr(e,`aboveAverage`)?.asBool(),percent:this.extractAttr(e,`percent`)?.asBool(),bottom:this.extractAttr(e,`bottom`)?.asBool(),operator:this.extractAttr(e,`operator`)?.asString(),text:this.extractAttr(e,`text`)?.asString(),timePeriod:this.extractAttr(e,`timePeriod`)?.asString(),rank:this.extractAttr(e,`rank`)?.asNum(),stdDev:this.extractAttr(e,`stdDev`)?.asNum(),equalAverage:this.extractAttr(e,`equalAverage`)?.asBool()}})}extractCfFormula(e){return this.mapOnElements({parent:e,query:`formula`},e=>this.extractTextContent(e,{required:!0}))}extractCfColorScale(e,t){let n=this.querySelector(e,`colorScale`);if(n)return{colors:this.mapOnElements({parent:n,query:`color`},e=>this.extractColor(e,t,`ffffff`)),cfvos:this.extractCFVos(n)}}extractCfIconSet(e){let t=this.querySelector(e,`iconSet, x14:iconSet`);if(t)return{iconSet:this.extractAttr(t,`iconSet`,{default:`3TrafficLights1`}).asString(),showValue:this.extractAttr(t,`showValue`,{default:!0}).asBool(),percent:this.extractAttr(t,`percent`,{default:!0}).asBool(),reverse:this.extractAttr(t,`reverse`)?.asBool(),custom:this.extractAttr(t,`custom`)?.asBool(),cfvos:this.extractCFVos(t),cfIcons:this.extractCfIcons(t)}}extractCfIcons(e){let t=this.mapOnElements({parent:e,query:`cfIcon, x14:cfIcon`},e=>({iconSet:this.extractAttr(e,`iconSet`,{required:!0}).asString(),iconId:this.extractAttr(e,`iconId`,{required:!0}).asNum()}));return t.length===0?void 0:t}extractCFVos(e){return this.mapOnElements({parent:e,query:`cfvo, x14:cfvo`},e=>({type:this.extractAttr(e,`type`,{required:!0}).asString(),gte:this.extractAttr(e,`gte`,{default:!0})?.asBool(),value:e.attributes.val?this.extractAttr(e,`val`)?.asString():this.extractChildTextContent(e,`f, xm:f`)}))}},mh=class extends dh{theme;constructor(e,t,n,r){super(e,t,n),this.theme=r}extractDataValidations(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`worksheet > dataValidations > dataValidation`},e=>({type:this.extractAttr(e,`type`,{required:!0}).asString(),operator:this.extractAttr(e,`operator`,{default:`between`})?.asString(),sqref:this.extractAttr(e,`sqref`,{required:!0}).asString().split(` `),errorStyle:this.extractAttr(e,`errorStyle`)?.asString(),formula1:this.extractDataValidationFormula(e,1)[0],formula2:this.extractDataValidationFormula(e,2)[0],showErrorMessage:this.extractAttr(e,`showErrorMessage`)?.asBool(),errorTitle:this.extractAttr(e,`errorTitle`)?.asString(),error:this.extractAttr(e,`error`)?.asString(),showInputMessage:this.extractAttr(e,`showInputMessage`)?.asBool(),promptTitle:this.extractAttr(e,`promptTitle`)?.asString(),prompt:this.extractAttr(e,`prompt`)?.asString(),allowBlank:this.extractAttr(e,`allowBlank`)?.asBool()}))}extractDataValidationFormula(e,t){return this.mapOnElements({parent:e,query:`formula${t}`},e=>this.extractTextContent(e,{required:!0}))}},hh=class extends dh{extractChart(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`c:chartSpace`},e=>{let t=this.getChartType(e);if(!Yf[t])throw Error(`Unsupported chart type ${t}`);if(Yf[t]===`combo`)return this.extractComboChart(e);let n=this.mapOnElements({parent:e,query:`c:chart > c:title a:t`},e=>e.textContent||``).join(``),r=this.extractChildAttr(e,`c:grouping`,`val`,{default:`clustered`}).asString();return{title:{text:n},type:Yf[t],dataSets:this.extractChartDatasets(this.querySelectorAll(e,`c:${t}`),t),labelRange:this.extractLabelRange(t,e),backgroundColor:this.extractChildAttr(e,`c:chartSpace > c:spPr a:srgbClr`,`val`,{default:`ffffff`}).asString(),legendPosition:Jf[this.extractChildAttr(e,`c:legendPos`,`val`,{default:`none`}).asString()],stacked:r===`stacked`,fontColor:`000000`}})[0]}extractLabelRange(e,t){return e===`scatterChart`?this.extractChildTextContent(t,`c:ser c:strRef c:f`)||this.extractChildTextContent(t,`c:ser c:numRef c:f`):this.extractChildTextContent(t,`c:ser c:cat c:f`)}extractComboChart(e){let t=this.mapOnElements({parent:e,query:`c:title a:t`},e=>e.textContent||``).join(``),n=this.extractChildAttr(e,`c:grouping`,`val`,{default:`clustered`}).asString();return{title:{text:t},type:`combo`,dataSets:[...this.extractChartDatasets(this.querySelectorAll(e,`c:barChart`),`comboChart`),...this.extractChartDatasets(this.querySelectorAll(e,`c:lineChart`),`comboChart`)],labelRange:this.extractChildTextContent(e,`c:ser c:cat c:f`),backgroundColor:this.extractChildAttr(e,`c:chartSpace > c:spPr a:srgbClr`,`val`,{default:`ffffff`}).asString(),legendPosition:Jf[this.extractChildAttr(e,`c:legendPos`,`val`,{default:`none`}).asString()],stacked:n===`stacked`,fontColor:`000000`}}extractChartDatasets(e,t){return Array.from(e).map(e=>t===`scatterChart`?this.extractScatterChartDatasets(e):this.mapOnElements({parent:e,query:`c:ser`},e=>{let t={},n=this.extractChildTextContent(e,`c:tx c:f`);if(n)t={reference:n};else{let n=this.extractChildTextContent(e,`c:tx c:v`);n&&(t={text:n})}let r=this.extractChildAttr(e,`c:spPr a:solidFill a:srgbClr`,`val`);return{label:t,range:this.extractChildTextContent(e,`c:val c:f`,{required:!0}),backgroundColor:r?`${en(r.asString())}`:void 0}})).flat()}extractScatterChartDatasets(e){return this.mapOnElements({parent:e,query:`c:ser`},e=>{let t={},n=this.extractChildTextContent(e,`c:tx c:f`);if(n)t={reference:n};else{let n=this.extractChildTextContent(e,`c:tx c:v`);n&&(t={text:n})}return{label:t,range:this.extractChildTextContent(e,`c:yVal c:f`,{required:!0})}})}getChartType(e){let t=this.querySelector(e,`c:plotArea`);if(!t)throw Error(`Missing plot area in the chart definition.`);let n;for(let e of t.children){let t=sh(e.tagName);Qd.some(e=>e===t)&&(n?n!==t&&(n=`comboChart`):n=t)}if(n)return n;throw Error(`Unknown chart type`)}};let gh=`oneCellAnchor`,_h=`twoCellAnchor`;var vh=class extends dh{extractFigures(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`xdr:wsDr`,children:!0},e=>{let t=sh(e.tagName),n=this.extractFigureAnchorsByType(e,t),r=this.querySelector(e,`c:chart`),i=this.querySelector(e,`a:blip`);if(!r&&!i)throw Error(`Only chart and image figures are currently supported.`);return{anchors:n,data:r?this.extractChart(r):this.extractImage(e),figureSize:t===gh?this.extractFigureSizeFromSizeTag(e,`xdr:ext`):void 0}})}extractFigureAnchorsByType(e,t){switch(t){case gh:return[this.extractFigureAnchor(`xdr:from`,e)];case _h:return[this.extractFigureAnchor(`xdr:from`,e),this.extractFigureAnchor(`xdr:to`,e)];default:throw Error(`${t} is not supported for xlsx drawings. `)}}extractFigureSizeFromSizeTag(e,t){let n=this.querySelector(e,t);if(!n)throw Error(`Missing size element '${t}'`);return{cx:this.extractAttr(n,`cx`,{required:!0}).asNum(),cy:this.extractAttr(n,`cy`,{required:!0}).asNum()}}extractFigureAnchor(e,t){let n=this.querySelector(t,e);if(!n)throw Error(`Missing anchor element ${e}`);return{col:Number(this.extractChildTextContent(n,`xdr:col`,{required:!0})),colOffset:Number(this.extractChildTextContent(n,`xdr:colOff`,{required:!0})),row:Number(this.extractChildTextContent(n,`xdr:row`,{required:!0})),rowOffset:Number(this.extractChildTextContent(n,`xdr:rowOff`,{required:!0}))}}extractChart(e){let t=this.extractAttr(e,`r:id`,{required:!0}).asString(),n=new hh(this.getTargetXmlFile(this.relationships[t]),this.xlsxFileStructure,this.warningManager).extractChart();if(!n)throw Error(`Unable to extract chart definition`);return n}extractImage(e){let t=this.querySelector(e,`a:blip`),n=this.extractAttr(t,`r:embed`,{required:!0}).asString(),r=this.getTargetImageFile(this.relationships[n]);if(!r)throw Error(`Unable to extract image`);let i=r.fileName.split(`.`).at(-1),a=sh(e.tagName),o=a===_h?this.querySelector(e,`a:xfrm`):e,s=a===_h?`a:ext`:`xdr:ext`,c=this.extractFigureSizeFromSizeTag(o,s);return{imageSrc:r.imageSrc,mimetype:i?tp[i]:void 0,size:c}}},yh=class extends dh{getPivotTable(){return this.mapOnElements({query:`:root`,parent:this.rootFile.file.xml},e=>({name:this.extractAttr(e,`name`,{required:!0}).asString(),rowGrandTotals:this.extractAttr(e,`rowGrandTotals`,{default:!0}).asBool(),location:this.extractPivotLocation(e),style:this.extractPivotStyleInfo(e)}))[0]}extractPivotLocation(e){return this.mapOnElements({query:`location`,parent:e},e=>({ref:this.extractAttr(e,`ref`,{required:!0}).asString(),firstHeaderRow:this.extractAttr(e,`firstHeaderRow`,{required:!0}).asNum(),firstDataRow:this.extractAttr(e,`firstDataRow`,{required:!0}).asNum(),firstDataCol:this.extractAttr(e,`firstDataCol`,{required:!0}).asNum()}))[0]}extractPivotStyleInfo(e){return this.mapOnElements({query:`pivotTableStyleInfo`,parent:e},e=>({name:this.extractAttr(e,`name`,{required:!0}).asString(),showRowHeaders:this.extractAttr(e,`showRowHeaders`,{required:!0}).asBool(),showColHeaders:this.extractAttr(e,`showColHeaders`,{required:!0}).asBool(),showRowStripes:this.extractAttr(e,`showRowStripes`,{required:!0}).asBool(),showColStripes:this.extractAttr(e,`showColStripes`,{required:!0}).asBool(),showLastColumn:this.extractAttr(e,`showLastColumn`)?.asBool()}))[0]}},bh=class extends dh{getTable(){return this.mapOnElements({query:`table`,parent:this.rootFile.file.xml},e=>({displayName:this.extractAttr(e,`displayName`,{required:!0}).asString(),name:this.extractAttr(e,`name`)?.asString(),id:this.extractAttr(e,`id`,{required:!0}).asString(),ref:this.extractAttr(e,`ref`,{required:!0}).asString(),headerRowCount:this.extractAttr(e,`headerRowCount`,{default:1}).asNum(),totalsRowCount:this.extractAttr(e,`totalsRowCount`,{default:0}).asNum(),cols:this.extractTableCols(e),style:this.extractTableStyleInfo(e),autoFilter:this.extractTableAutoFilter(e)}))[0]}extractTableCols(e){return this.mapOnElements({query:`tableColumn`,parent:e},e=>({id:this.extractAttr(e,`id`,{required:!0}).asString(),name:this.extractAttr(e,`name`,{required:!0}).asString(),colFormula:this.extractChildTextContent(e,`calculatedColumnFormula`)}))}extractTableStyleInfo(e){return this.mapOnElements({query:`tableStyleInfo`,parent:e},e=>({name:this.extractAttr(e,`name`)?.asString(),showFirstColumn:this.extractAttr(e,`showFirstColumn`)?.asBool(),showLastColumn:this.extractAttr(e,`showLastColumn`)?.asBool(),showRowStripes:this.extractAttr(e,`showRowStripes`)?.asBool(),showColumnStripes:this.extractAttr(e,`showColumnStripes`)?.asBool()}))[0]}extractTableAutoFilter(e){return this.mapOnElements({query:`autoFilter`,parent:e},e=>({columns:this.extractFilterColumns(e),zone:this.extractAttr(e,`ref`,{required:!0}).asString()}))[0]}extractFilterColumns(e){return this.mapOnElements({query:`tableColumn`,parent:e},t=>({colId:this.extractAttr(e,`colId`,{required:!0}).asNum(),hiddenButton:this.extractAttr(e,`hiddenButton`,{default:!1}).asBool(),filters:this.extractSimpleFilter(t)}))}extractSimpleFilter(e){return this.mapOnElements({query:`filter`,parent:e},e=>({val:this.extractAttr(e,`val`,{required:!0}).asString()}))}},xh=class extends dh{theme;constructor(e,t,n,r){super(e,t,n),this.theme=r}getSheet(){return this.mapOnElements({query:`worksheet`,parent:this.rootFile.file.xml},e=>{let t=this.getSheetWorkbookInfo();return{sheetName:this.extractSheetName(),sheetViews:this.extractSheetViews(e),sheetFormat:this.extractSheetFormat(e),sheetProperties:this.extractSheetProperties(e),cols:this.extractCols(e),rows:this.extractRows(e),sharedFormulas:this.extractSharedFormulas(e),merges:this.extractMerges(e),cfs:this.extractConditionalFormats(),dataValidations:this.extractDataValidations(),figures:this.extractFigures(e),hyperlinks:this.extractHyperLinks(e),tables:this.extractTables(e),pivotTables:this.extractPivotTables(),isVisible:t.state===`visible`}})[0]}extractSheetViews(e){return this.mapOnElements({parent:e,query:`sheetView`},e=>{let t=this.querySelector(e,`pane`);return{tabSelected:this.extractAttr(e,`tabSelected`,{default:!1}).asBool(),showFormulas:this.extractAttr(e,`showFormulas`,{default:!1}).asBool(),showGridLines:this.extractAttr(e,`showGridLines`,{default:!0}).asBool(),showRowColHeaders:this.extractAttr(e,`showRowColHeaders`,{default:!0}).asBool(),pane:{xSplit:t?this.extractAttr(t,`xSplit`,{default:0}).asNum():0,ySplit:t?this.extractAttr(t,`ySplit`,{default:0}).asNum():0}}})}extractSheetName(){let e=Df(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find(t=>t.target===e).id;for(let e of this.querySelectorAll(this.xlsxFileStructure.workbook.file.xml,`sheet`))if(e.attributes[`r:id`].value===t)return e.attributes.name.value;throw Error(`Missing sheet name`)}getSheetWorkbookInfo(){let e=Df(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find(t=>t.target===e).id,n=this.mapOnElements({parent:this.xlsxFileStructure.workbook.file.xml,query:`sheet`},e=>({relationshipId:this.extractAttr(e,`r:id`,{required:!0}).asString(),sheetId:this.extractAttr(e,`sheetId`,{required:!0}).asString(),sheetName:this.extractAttr(e,`name`,{required:!0}).asString(),state:this.extractAttr(e,`state`,{default:`visible`}).asString()})).find(e=>e.relationshipId===t);if(!n)throw Error(`Cannot find corresponding workbook sheet`);return n}extractConditionalFormats(){return new ph(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractConditionalFormattings()}extractDataValidations(){return new mh(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractDataValidations()}extractFigures(e){return this.mapOnElements({parent:e,query:`drawing`},e=>{let t=this.extractAttr(e,`r:id`,{required:!0}).asString();return new vh(this.getTargetXmlFile(this.relationships[t]),this.xlsxFileStructure,this.warningManager).extractFigures()})[0]||[]}extractTables(e){return this.mapOnElements({query:`tablePart`,parent:e},e=>{let t=this.extractAttr(e,`r:id`,{required:!0}).asString();return new bh(this.getTargetXmlFile(this.relationships[t]),this.xlsxFileStructure,this.warningManager).getTable()})}extractPivotTables(){try{return Object.values(this.relationships).filter(e=>e.type.endsWith(`pivotTable`)).map(e=>new yh(this.getTargetXmlFile(e),this.xlsxFileStructure,this.warningManager).getPivotTable())}catch(e){return this.catchErrorOnElement(e),[]}}extractMerges(e){return this.mapOnElements({parent:e,query:`mergeCell`},e=>this.extractAttr(e,`ref`,{required:!0}).asString())}extractSheetFormat(e){let t=this.querySelector(e,`sheetFormatPr`);if(t)return{defaultColWidth:this.extractAttr(t,`defaultColWidth`,{default:`8.43`}).asNum(),defaultRowHeight:this.extractAttr(t,`defaultRowHeight`,{default:`12.75`}).asNum()}}extractSheetProperties(e){let t=this.querySelector(e,`sheetPr`);if(t)return{outlinePr:this.extractSheetOutlineProperties(t),tabColor:this.extractColor(this.querySelector(t,`tabColor`),this.theme)}}extractSheetOutlineProperties(e){let t=this.querySelector(e,`outlinePr`);if(t)return{summaryBelow:this.extractAttr(t,`summaryBelow`,{default:!0}).asBool(),summaryRight:this.extractAttr(t,`summaryRight`,{default:!0}).asBool()}}extractCols(e){return this.mapOnElements({parent:e,query:`cols col`},e=>({width:this.extractAttr(e,`width`)?.asNum(),customWidth:this.extractAttr(e,`customWidth`)?.asBool(),bestFit:this.extractAttr(e,`bestFit`)?.asBool(),hidden:this.extractAttr(e,`hidden`)?.asBool(),min:this.extractAttr(e,`min`,{required:!0}).asNum(),max:this.extractAttr(e,`max`,{required:!0}).asNum(),styleIndex:this.extractAttr(e,`style`)?.asNum(),outlineLevel:this.extractAttr(e,`outlineLevel`)?.asNum(),collapsed:this.extractAttr(e,`collapsed`)?.asBool()}))}extractRows(e){let t=new Set;return this.mapOnElements({parent:e,query:`sheetData row`},e=>({index:this.extractAttr(e,`r`,{required:!0}).asNum(),cells:this.extractCells(e,t),height:this.extractAttr(e,`ht`)?.asNum(),customHeight:this.extractAttr(e,`customHeight`)?.asBool(),hidden:this.extractAttr(e,`hidden`)?.asBool(),styleIndex:this.extractAttr(e,`s`)?.asNum(),outlineLevel:this.extractAttr(e,`outlineLevel`)?.asNum(),collapsed:this.extractAttr(e,`collapsed`)?.asBool()}))}extractCells(e,t){return this.mapOnElements({parent:e,query:`c`},e=>{let n=this.extractAttr(e,`r`,{required:!0}).asString(),r=this.extractCellFormula(e);if(r?.ref&&r.sharedIndex===void 0){let e=$n(r.ref);for(let{col:r,row:i}of vr(e)){let e=w(r,i);e!==n&&t.add(e)}}let i=t.has(n);return{xc:n,styleIndex:this.extractAttr(e,`s`)?.asNum(),type:zf[this.extractAttr(e,`t`,{default:`n`}).asString()],value:i?void 0:this.extractChildTextContent(e,`v`)??void 0,formula:i?void 0:r}})}extractCellFormula(e){let t=this.querySelector(e,`f`);if(!t)return;let n=this.extractTextContent(t),r=this.extractAttr(t,`si`)?.asNum(),i=this.extractAttr(t,`ref`)?.asString();if(!((n===void 0||n.trim()===``)&&r===void 0))return{content:n,sharedIndex:r,ref:i}}extractHyperLinks(e){return this.mapOnElements({parent:e,query:`hyperlink`},e=>{let t=this.extractAttr(e,`r:id`)?.asString();return{xc:this.extractAttr(e,`ref`,{required:!0})?.asString(),location:this.extractAttr(e,`location`)?.asString(),display:this.extractAttr(e,`display`)?.asString(),relTarget:t?this.relationships[t].target:void 0}})}extractSharedFormulas(e){let t=this.querySelectorAll(e,`f[si][ref]`),n={};for(let e of t){let t=this.extractAttr(e,`si`,{required:!0}).asNum();n[t]=this.extractTextContent(e,{required:!0})}let r=[];for(let e=0;e<Object.keys(n).length;e++)n[e]?r.push(n[e]):(this.warningManager.addParsingWarning(`Missing shared formula ${e}, replacing it by empty formula`),r.push(``));return r}},Sh=class extends dh{theme;constructor(e,t,n){super(e.styles,e,t),this.theme=n}getNumFormats(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`numFmt`},e=>this.extractNumFormats(e))}extractNumFormats(e){return{id:this.extractAttr(e,`numFmtId`,{required:!0}).asNum(),format:this.extractAttr(e,`formatCode`,{required:!0,default:``}).asString()}}getFonts(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`font`},e=>this.extractFont(e))}extractFont(e){let t=this.extractChildAttr(e,`name`,`val`,{default:`Arial`}).asString(),n=this.extractChildAttr(e,`sz`,`val`,{default:Re.toString()}).asNum(),r=this.extractColor(this.querySelector(e,`color`),this.theme),i=this.querySelector(e,`i`)||void 0,a=i&&i.attributes.val?.value!==`0`,o=this.querySelector(e,`b`)||void 0,s=o&&o.attributes.val?.value!==`0`,c=this.querySelector(e,`strike`)||void 0,l=c&&c.attributes.val?.value!==`0`,u=this.querySelector(e,`u`)||void 0;return{name:t,size:n,color:r,italic:a,bold:s,underline:u&&u.attributes.val?.value!==`none`,strike:l}}getFills(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`fill`},e=>this.extractFill(e))}extractFill(e){let t=e.children[0];return t.tagName===`patternFill`?{patternType:t.attributes.patternType?.value,bgColor:this.extractColor(this.querySelector(t,`bgColor`),this.theme),fgColor:this.extractColor(this.querySelector(t,`fgColor`),this.theme)}:{patternType:`solid`,fgColor:this.extractColor(this.querySelectorAll(t,`color`)[1],this.theme)}}getBorders(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`border`},e=>this.extractBorder(e))}extractBorder(e){let t={left:this.extractSingleBorder(e,`left`,this.theme),right:this.extractSingleBorder(e,`right`,this.theme),top:this.extractSingleBorder(e,`top`,this.theme),bottom:this.extractSingleBorder(e,`bottom`,this.theme),diagonal:this.extractSingleBorder(e,`diagonal`,this.theme)};return t.diagonal&&(t.diagonalUp=this.extractAttr(e,`diagonalUp`)?.asBool(),t.diagonalDown=this.extractAttr(e,`diagonalDown`)?.asBool()),t}extractSingleBorder(e,t,n){let r=this.querySelector(e,t);if(!(!r||!r.attributes.style))return{style:this.extractAttr(r,`style`,{required:!0,default:`thin`}).asString(),color:this.extractColor(r.children[0],n,`000000`)}}extractAlignment(e){return{horizontal:this.extractAttr(e,`horizontal`,{default:`general`}).asString(),vertical:this.extractAttr(e,`vertical`,{default:`bottom`}).asString(),textRotation:this.extractAttr(e,`textRotation`)?.asNum(),wrapText:this.extractAttr(e,`wrapText`)?.asBool(),indent:this.extractAttr(e,`indent`)?.asNum(),relativeIndent:this.extractAttr(e,`relativeIndent`)?.asNum(),justifyLastLine:this.extractAttr(e,`justifyLastLine`)?.asBool(),shrinkToFit:this.extractAttr(e,`shrinkToFit`)?.asBool(),readingOrder:this.extractAttr(e,`readingOrder`)?.asNum()}}getDxfs(){return this.mapOnElements({query:`dxf`,parent:this.rootFile.file.xml},e=>{let t=this.querySelector(e,`font`),n=this.querySelector(e,`fill`),r=this.querySelector(e,`border`),i=this.querySelector(e,`numFmt`),a=this.querySelector(e,`alignment`);return{font:t?this.extractFont(t):void 0,fill:n?this.extractFill(n):void 0,numFmt:i?this.extractNumFormats(i):void 0,alignment:a?this.extractAlignment(a):void 0,border:r?this.extractBorder(r):void 0}})}getStyles(){return this.mapOnElements({query:`cellXfs xf`,parent:this.rootFile.file.xml},e=>{let t=this.querySelector(e,`alignment`);return{fontId:this.extractAttr(e,`fontId`,{required:!0,default:0}).asNum(),fillId:this.extractAttr(e,`fillId`,{required:!0,default:0}).asNum(),borderId:this.extractAttr(e,`borderId`,{required:!0,default:0}).asNum(),numFmtId:this.extractAttr(e,`numFmtId`,{required:!0,default:0}).asNum(),alignment:t?this.extractAlignment(t):void 0}})}},Ch=class extends dh{getExternalBook(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`externalBook`},e=>({rId:this.extractAttr(e,`r:id`,{required:!0}).asString(),sheetNames:this.mapOnElements({parent:e,query:`sheetName`},e=>this.extractAttr(e,`val`,{required:!0}).asString()),datasets:this.extractExternalSheetData(e)}))[0]}extractExternalSheetData(e){return this.mapOnElements({parent:e,query:`sheetData`},e=>{let t=this.mapOnElements({parent:e,query:`cell`},e=>({xc:this.extractAttr(e,`r`,{required:!0}).asString(),value:this.extractChildTextContent(e,`v`,{required:!0})})),n={};for(let e of t)n[e.xc]=e.value;return{sheetId:this.extractAttr(e,`sheetId`,{required:!0}).asNum(),data:n}})}};function wh(e,t){return Th(Eh(e,t),t)}function Th(e,t){let n=[];for(let r of e){let e=Dh(r,t);n.push({file:{fileName:r,xml:t[r]},rels:e?{fileName:e,xml:t[e]}:void 0})}return n}function Eh(e,t){let n=t[`[Content_Types].xml`].querySelectorAll(`Override[ContentType="${e}"]`),r=[];for(let e of n){let t=e?.attributes.PartName.value;r.push(t.substring(1))}return r}function Dh(e,t){if(e===`[Content_Types].xml`)return`_rels/.rels`;let n=``,r=e.split(`/`);for(let e=0;e<r.length-1;e++)n+=r[e]+`/`;return n+=`_rels/`,n+=r[r.length-1]+`.rels`,t[n]||(n=void 0),n}var Oh=class{warningManager;xmls;images;constructor(e){this.warningManager=new Mf,this.xmls={},this.images=[];for(let t of Object.keys(e))if(t.endsWith(`.xml`)||t.endsWith(`.rels`)){let n=ch(e[t]);this.xmls[t]=nh(new Zd(n))}else t.includes(`media/image`)&&this.images.push({fileName:t,imageSrc:e[t].imageSrc})}convertXlsx(){let e=this.getXlsxData();return this.convertImportedData(e)}getXlsxData(){let e=this.buildXlsxFileStructure(),t=e.theme?new fh(e.theme,e,this.warningManager).getTheme():void 0,n=e.sharedStrings?new fh(e.sharedStrings,e,this.warningManager).getSharedStrings():[],r=e.sheets.sort((e,t)=>e.file.fileName.localeCompare(t.file.fileName,void 0,{numeric:!0})).map(n=>new xh(n,e,this.warningManager,t).getSheet()),i=e.externalLinks.map(t=>new Ch(t,e,this.warningManager).getExternalBook()),a=new Sh(e,this.warningManager,t);return{fonts:a.getFonts(),fills:a.getFills(),borders:a.getBorders(),dxfs:a.getDxfs(),numFmts:a.getNumFormats(),styles:a.getStyles(),sheets:r,sharedStrings:n,externalBooks:i}}buildXlsxFileStructure(){let e={sheets:wh(af.sheet,this.xmls),workbook:wh(af.workbook,this.xmls)[0],styles:wh(af.styles,this.xmls)[0],sharedStrings:wh(af.sharedStrings,this.xmls)[0],theme:wh(af.themes,this.xmls)[0],charts:wh(af.chart,this.xmls),figures:wh(af.drawing,this.xmls),tables:wh(af.table,this.xmls),pivots:wh(af.pivot,this.xmls),externalLinks:wh(af.externalLink,this.xmls),images:this.images};if(!e.workbook.rels)throw Error(T(`Cannot find workbook relations file`));return e}convertImportedData(e){let t={version:21,sheets:_m(e,this.warningManager),styles:hp(e,this.warningManager),formats:_p(e,this.warningManager),borders:pp(e,this.warningManager),revisionId:Ve};return Km(t,e),Object.keys(e.styles).map(t=>{e.styles[t]=jt(e.styles[t])}),t}};let kh=(e,t=()=>!0)=>[{goTo:e,guard:t}],Ah=(e,t=()=>!0)=>({goTo:e,guard:t}),jh={0:{REFERENCE:kh(2),NUMBER:kh(4),SYMBOL:[Ah(3,e=>Ls(e.value)),Ah(4,e=>Rs(e.value))]},3:{SPACE:kh(3),OPERATOR:kh(5,e=>e.value===`:`)},4:{SPACE:kh(4),OPERATOR:kh(6,e=>e.value===`:`)},2:{SPACE:kh(2),OPERATOR:kh(1,e=>e.value===`:`)},1:{SPACE:kh(1),NUMBER:kh(7),REFERENCE:kh(7,e=>Vs(e.value)),SYMBOL:kh(7,e=>zs(e.value)||Bs(e.value))},5:{SPACE:kh(5),SYMBOL:kh(7,e=>zs(e.value)),REFERENCE:kh(7,e=>Vs(e.value))},6:{SPACE:kh(6),NUMBER:kh(7),REFERENCE:kh(7,e=>Vs(e.value)),SYMBOL:kh(7,e=>Bs(e.value))},7:{}};function Mh(e){let t=0,n=jh[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=jh[o],r+=i.value;break}}return null}function Nh(e,t=O){let n=zc(e,t),r=[];for(;n.length;)r.push(Mh(n)||n.shift());return r}function Ph(e){let t=Nh(e),n=[];return{text:``.concat(...t.map(e=>{if(e.type===`REFERENCE`&&As.test(e.value)){let t=e.value.trim();return n.includes(t)||n.push(t),`|${n.indexOf(t)}|`}else return e.value})),dependencies:n}}let Fh={am_ET:7,ar_001:6,ar_SY:6,az_AZ:1,eu_ES:1,be_BY:1,bn_IN:1,bs_BA:1,bg_BG:1,ca_ES:1,zh_CN:7,zh_HK:7,zh_TW:7,hr_HR:1,cs_CZ:1,da_DK:1,nl_BE:1,nl_NL:1,en_AU:7,en_CA:7,en_GB:1,en_IN:7,en_NZ:7,et_EE:1,fi_FI:1,fr_BE:1,fr_CA:7,fr_CH:1,fr_FR:1,gl_ES:1,ka_GE:1,de_DE:1,de_CH:1,el_GR:1,gu_IN:7,he_IL:7,hi_IN:7,hu_HU:1,id_ID:7,it_IT:1,ja_JP:7,kab_DZ:6,km_KH:7,ko_KP:1,ko_KR:7,lo_LA:7,lv_LV:1,lt_LT:1,lb_LU:1,mk_MK:1,ml_IN:1,mn_MN:7,ms_MY:1,nb_NO:1,fa_IR:6,pl_PL:1,pt_AO:1,pt_BR:7,pt_PT:1,ro_RO:1,ru_RU:1,sr_RS:7,"sr@latin":7,sk_SK:1,sl_SI:1,es_AR:7,es_BO:1,es_CL:1,es_CO:7,es_CR:1,es_DO:1,es_EC:1,es_GT:7,es_MX:7,es_PA:7,es_PE:7,es_PY:7,es_UY:1,es_VE:7,sw:1,sv_SE:1,th_TH:7,tl_PH:1,tr_TR:1,uk_UA:1,vi_VN:1,sq_AL:1,te_IN:7,en_US:7,my_MM:7,es_ES:1,es_419:1},Ih=new h;Ih.add(`migration_1`,{versionFrom:`1`,migrate(e){return e.sheets&&e.sheets[0]&&(e.activeSheet=e.sheets[0].name),e}}).add(`migration_2`,{versionFrom:`2`,migrate(e){if(e.sheets&&e.sheets.length)for(let t of e.sheets)t.id=t.id||t.name;return e}}).add(`migration_3`,{versionFrom:`3`,migrate(e){return e.sheets&&e.activeSheet&&(e.activeSheet=e.sheets.find(t=>t.name===e.activeSheet).id),e}}).add(`migration_4`,{versionFrom:`4`,migrate(e){for(let t of e.sheets||[])t.figures=t.figures||[];return e}}).add(`migration_5`,{versionFrom:`5`,migrate(e){for(let t of e.sheets||[])for(let e in t.cells||[]){let n=t.cells[e];n.content&&n.content.startsWith(`=`)&&(n.formula=Ph(n.content))}return e}}).add(`migration_6`,{versionFrom:`6`,migrate(e){for(let t of e.sheets||[])for(let e in t.figures||[]){let{dataSets:n,...r}=t.figures[e].data,i=[];for(let e of n)if(e.labelCell){let t=$n(e.dataRange),n=e.labelCell+`:`+w(t.right,t.bottom);i.push(n)}else i.push(e.dataRange);r.dataSetsHaveTitle=!!n[0].labelCell,r.dataSets=i,t.figures[e].data=r}return e}}).add(`migration_7`,{versionFrom:`7`,migrate(e){let t=[];for(let n of e.sheets||[]){if(!n.name)continue;let e=n.name,r=st(e,`_`),i=1,a=r;for(;t.includes(a);)a=`${r}${i}`,i++;n.name=a,t.push(a);let o=t=>{if(t===void 0)return t;let n=t.replace(e,a),r=t;for(;r!==n;)r=n,n=r.replace(e,a);return r};for(let e in n.cells){let t=n.cells[e];t.formula&&(t.formula.dependencies=t.formula.dependencies.map(o))}for(let e of n.figures||[])if(e.type===`chart`){let t=e.data.dataSets.map(o),n=o(e.data.labelRange);e.data={...e.data,dataSets:t,labelRange:n}}for(let e of n.conditionalFormats||[]){e.ranges=e.ranges.map(o);for(let t of[`minimum`,`maximum`,`midpoint`,`upperInflectionPoint`,`lowerInflectionPoint`])e.rule[t]?.type===`formula`&&(e.rule[t].value=o(e.rule[t].value))}}return e}}).add(`migration_8`,{versionFrom:`8`,migrate(e){for(let t of e.sheets||[])for(let e of t.figures||[])e.data.background=oe,e.data.verticalAxisPosition=`left`,e.data.legendPosition=`top`,e.data.stacked=!1;return e}}).add(`migration_9`,{versionFrom:`9`,migrate(e){for(let t of e.sheets||[])for(let e in t.cells||[]){let n=t.cells[e];if(n.formula){let{text:e,dependencies:t}=n.formula;for(let[n,r]of Object.entries(t)){let t=`\\|${n}\\|`;e=e.replace(new RegExp(t,`g`),r)}n.content=e,delete n.formula}}return e}}).add(`migration_10`,{versionFrom:`10`,migrate(e){let t={};for(let n of e.sheets||[])for(let e in n.cells||[]){let r=n.cells[e];r.format&&=Fr(r.format,t)}return e.formats=t,e}}).add(`migration_11`,{versionFrom:`11`,migrate(e){for(let t of e.sheets||[])t.isVisible=!0;return e}}).add(`migration_12`,{versionFrom:`12`,migrate(e){return Lh(e)}}).add(`migration_12_5`,{versionFrom:`12.5`,migrate(e){for(let t in e.borders){let n=e.borders[t];for(let e in n)Array.isArray(n[e])&&(n[e]={style:n[e][0],color:n[e][1]})}return e}}).add(`migration_13`,{versionFrom:`13`,migrate(e){return e.settings||={},e.settings.locale||(e.settings.locale=O),e}}).add(`migration_14`,{versionFrom:`14`,migrate(e){return Lh(e)}}).add(`migration_14_5`,{versionFrom:`14.5`,migrate(e){for(let t of e.sheets||[])t.tables=t.tables||t.filterTables||[],delete t.filterTables;return e}}).add(`migration_15`,{versionFrom:`15`,migrate(e){return e.pivots||={},e.pivotNextId||=ku(e.pivots)+1,e}}).add(`migration_16`,{versionFrom:`16`,migrate(e){for(let t of e.sheets||[])for(let e in t.figures||[]){let n=t.figures[e];`title`in n.data&&typeof n.data.title==`string`&&(n.data.title={text:n.data.title});let r=n.data.type;if(![`line`,`bar`,`pie`,`scatter`,`waterfall`,`combo`].includes(r))continue;let{dataSets:i,...a}=t.figures[e].data;a.dataSets=i.map(e=>({dataRange:e})),t.figures[e].data=a}return e}}).add(`migration_17`,{versionFrom:`17`,migrate(e){return e}}).add(`migration_18`,{versionFrom:`18`,migrate(e){for(let t of Object.values(e.pivots||{}))t.measures=t.measures.map(e=>({id:e.name,fieldName:e.name,aggregator:e.aggregator})),t.columns=t.columns.map(e=>({fieldName:e.name,order:e.order,granularity:e.granularity})),t.rows=t.rows.map(e=>({fieldName:e.name,order:e.order,granularity:e.granularity}));return e}}).add(`migration_19`,{versionFrom:`19`,migrate(e){let t=e.settings?.locale;return t&&(t.weekStart=Fh[t.code]||1),e}}).add(`migration_20`,{versionFrom:`20`,migrate(e){for(let t of e.sheets||[]){t.styles={},t.formats={},t.borders={};for(let e in t.cells)t.styles[e]=t.cells[e].style,t.formats[e]=t.cells[e].format,t.borders[e]=t.cells[e].border,delete t.cells[e].style,delete t.cells[e].format,delete t.cells[e].border}return e}}).add(`migration_21`,{versionFrom:`21`,migrate(e){for(let t of e.sheets||[])for(let e of t.figures||[]){if(e.tag!==`chart`||e.data.type!==`gauge`)continue;let t=e.data;t?.sectionRule?.lowerInflectionPoint&&(t.sectionRule.lowerInflectionPoint.operator=`<=`),t?.sectionRule?.upperInflectionPoint&&(t.sectionRule.upperInflectionPoint.operator=`<=`)}return e}});function Lh(e){for(let t of e.sheets||[]){let e=[];for(let n of t.filterTables||[]){let t=$n(n.range),r=e.findIndex(e=>dr(e,t));r===-1?e.push(t):e[r]=t}t.filterTables=e.map(e=>({range:nr(e)}))}return e}let Rh=`Sheet1`;function zh(e,t){if(!e)return Zh();console.debug(`### Loading data ###`);let n=performance.now();if(e[`[Content_Types].xml`]){let n=new Oh(e);if(e=n.convertXlsx(),t)for(let e of n.warningManager.warnings.sort())console.warn(e)}return`version`in e&&e.version<22&&(console.debug(`Migrating data from version`,e.version),e=Vh(e)),e=Hh(e),console.debug(`Data loaded in`,performance.now()-n,`ms`),console.debug(`###`),e}function Bh(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<Math.max(n.length,r.length);e++){let t=n[e]||0,i=r[e]||0;if(t>i)return 1;if(t<i)return-1}return 0}function Vh(e){let t=performance.now(),n=Ih.getAll().sort((e,t)=>Bh(e.versionFrom,t.versionFrom)),r=n.findIndex(t=>t.versionFrom===e.version.toString());for(let t=r;t<n.length;t++)e=n[t].migrate(e);return console.debug(`Data migrated in`,performance.now()-t,`ms`),e}function Hh(e){return e=Uh(e),e=Wh(e),e}function Uh(e){if(e.uniqueFigureIds)return e;let t=new Set,n=new Tc;for(let r of e.sheets||[])for(let e of r.figures||[])t.has(e.id)&&(e.id+=n.uuidv4()),t.add(e.id);return e.uniqueFigureIds=!0,e}function Wh(e){let t=Object.assign(Zh(),e,{version:22});return t.sheets=t.sheets?t.sheets.map((e,t)=>Object.assign(Xh(`Sheet${t+1}`,`Sheet${t+1}`),e)):[],t.sheets.length===0&&t.sheets.push(Xh(Rh,`Sheet1`)),tl(t.settings.locale)||(t.settings.locale=O),t}function Gh(e,t){return t=Kh(e,t),t=qh(t,`SORT_CELLS`),t=qh(t,`SET_DECIMAL`),t=Jh(e,t),t=Yh(e,t),t}function Kh(e,t){if(Object.keys(e).length!==0)return t;let n=[],r=[],i=e=>{if(e.type===`CREATE_SHEET`)n.push(e.sheetId);else if(`sheetId`in e&&!n.includes(e.sheetId))return{...e,sheetId:Rh};return e};for(let e of t)e.type===`REMOTE_REVISION`?r.push({...e,commands:e.commands.map(i)}):r.push(e);return r}function qh(e,t){let n=[];for(let r of e)r.type===`REMOTE_REVISION`?n.push({...r,commands:r.commands.filter(e=>e.type!==t)}):n.push(r);return n}function Jh(e,t){let n=[],r={};for(let t of e.sheets||[])t.figures?.forEach(e=>{e.tag===`chart`&&(r[e.id]=e.data)});for(let e of t)if(e.type===`REMOTE_REVISION`){let t=[];for(let n of e.commands){let e=n;switch(n.type){case`CREATE_CHART`:r[n.id]=n.definition;break;case`UPDATE_CHART`:if(!r[n.id]){console.log(`Fix chart definition: chart with id ${n.id} not found.`);continue}let t={...r[n.id],...n.definition};e={...n,definition:t},r[n.id]=t;break}t.push(e)}n.push({...e,commands:t})}else n.push(e);return n}function Yh(e,t){let n={};for(let t of e.sheets||[])n[t.id]=t.name;let r=[];for(let e of t)if(e.type===`REMOTE_REVISION`){let t=[];for(let r of e.commands){switch(r.type){case`DUPLICATE_SHEET`:r.sheetNameTo=r.sheetNameTo??tc(n[r.sheetId],Object.values(n));break;case`CREATE_SHEET`:case`RENAME_SHEET`:n[r.sheetId]=r.name||ec(Object.values(n));break}t.push(r)}r.push({...e,commands:t})}else r.push(e);return t}function Xh(e,t){return{id:e,name:t,colNumber:26,rowNumber:100,cells:{},styles:{},formats:{},borders:{},cols:{},rows:{},merges:[],conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],isVisible:!0}}function Zh(e=`Sheet1`){return{version:22,sheets:[Xh(Rh,e)],styles:{},formats:{},borders:{},revisionId:Ve,uniqueFigureIds:!0,settings:{locale:O},pivots:{},pivotNextId:1,customTableStyles:{}}}function Qh(e,t){return{...Xh(e,t),charts:[],images:[]}}function $h(){return{...Zh(),sheets:[Qh(Rh,`Sheet1`)]}}let eg={wrongPasteSelection:T(`This operation is not allowed with multiple selections.`),willRemoveExistingMerge:T(`This operation is not possible due to a merge. Please remove the merges first than try again.`),wrongFigurePasteOption:T(`Cannot do a special paste of a figure.`),frozenPaneOverlap:T(`This operation is not allowed due to an overlapping frozen pane.`)};function tg(e,t){t.isSuccessful||(t.reasons.includes(`WrongPasteSelection`)?e.raiseError(eg.wrongPasteSelection):t.reasons.includes(`WillRemoveExistingMerge`)?e.raiseError(eg.willRemoveExistingMerge):t.reasons.includes(`WrongFigurePasteOption`)?e.raiseError(eg.wrongFigurePasteOption):t.reasons.includes(`FrozenPaneOverlap`)&&e.raiseError(eg.frozenPaneOverlap))}function ng(e,t,n){tg(e,e.model.dispatch(`PASTE`,{target:t,pasteOption:n}))}function rg(e,t,n,r){n.data&&n.data.version!==22&&e.notifyUser({type:`warning`,text:T(`You copied content from a different version of the application. Only text content will be pasted.`),sticky:!1}),tg(e,e.model.dispatch(`PASTE_FROM_OS_CLIPBOARD`,{target:t,clipboardContent:n,pasteOption:r}))}let ig={Errors:{InvalidRange:T(`The range is invalid`),FirstArgMissing:T(`The argument is missing. Please provide a value`),SecondArgMissing:T(`The second argument is missing. Please provide a value`),MinNaN:T(`The minpoint must be a number`),MidNaN:T(`The midpoint must be a number`),MaxNaN:T(`The maxpoint must be a number`),ValueUpperInflectionNaN:T(`The first value must be a number`),ValueLowerInflectionNaN:T(`The second value must be a number`),MinBiggerThanMax:T(`Minimum must be smaller then Maximum`),MinBiggerThanMid:T(`Minimum must be smaller then Midpoint`),MidBiggerThanMax:T(`Midpoint must be smaller then Maximum`),LowerBiggerThanUpper:T(`Lower inflection point must be smaller than upper inflection point`),MinInvalidFormula:T(`Invalid Minpoint formula`),MaxInvalidFormula:T(`Invalid Maxpoint formula`),MidInvalidFormula:T(`Invalid Midpoint formula`),ValueUpperInvalidFormula:T(`Invalid upper inflection point formula`),ValueLowerInvalidFormula:T(`Invalid lower inflection point formula`),EmptyRange:T(`A range needs to be defined`),ValueCellIsInvalidFormula:T(`At least one of the provided values is an invalid formula`),Unexpected:T(`The rule is invalid for an unknown reason`)},ColorScale:T(`Color scale`),IconSet:T(`Icon set`),DataBar:T(`Data bar`)},ag={IsEmpty:T(`Is empty`),IsNotEmpty:T(`Is not empty`),ContainsText:T(`Contains`),NotContains:T(`Does not contain`),BeginsWith:T(`Starts with`),EndsWith:T(`Ends with`),Equal:T(`Is equal to`),NotEqual:T(`Is not equal to`),GreaterThan:T(`Is greater than`),GreaterThanOrEqual:T(`Is greater than or equal to`),LessThan:T(`Is less than`),LessThanOrEqual:T(`Is less than or equal to`),Between:T(`Is between`),NotBetween:T(`Is not between`)},og={Series:T(`Series`),BackgroundColor:T(`Background color`),StackedBarChart:T(`Stacked bar chart`),StackedLineChart:T(`Stacked line chart`),StackedAreaChart:T(`Stacked area chart`),StackedColumnChart:T(`Stacked column chart`),CumulativeData:T(`Cumulative data`),TreatLabelsAsText:T(`Treat labels as text`),AggregatedChart:T(`Aggregate`),Errors:{Unexpected:T(`The chart definition is invalid for an unknown reason`),InvalidDataSet:T(`The dataset is invalid`),InvalidLabelRange:T(`Labels are invalid`),InvalidScorecardKeyValue:T(`The key value is invalid`),InvalidScorecardBaseline:T(`The baseline value is invalid`),InvalidGaugeDataRange:T(`The data range is invalid`),EmptyGaugeRangeMin:T(`A minimum range limit value is needed`),GaugeRangeMinNaN:T(`The minimum range limit value must be a number`),EmptyGaugeRangeMax:T(`A maximum range limit value is needed`),GaugeRangeMaxNaN:T(`The maximum range limit value must be a number`),GaugeRangeMinBiggerThanRangeMax:T(`Minimum range limit must be smaller than maximum range limit`),GaugeLowerInflectionPointNaN:T(`The lower inflection point value must be a number`),GaugeUpperInflectionPointNaN:T(`The upper inflection point value must be a number`)}},sg={Custom:T(`Custom`)},cg=T(`Merged cells are preventing this operation. Unmerge those cells and try again.`),lg=T(`The header row of a table can't be moved.`),ug={Errors:{Unexpected:T(`Cannot split the selection for an unknown reason`),NoSplitSeparatorInSelection:T(`There is no match for the selected separator in the selection`),MoreThanOneColumnSelected:T(`Only a selection from a single column can be split`),SplitWillOverwriteContent:T(`Splitting will overwrite existing content`)}},dg={Errors:{Unexpected:T(`Cannot remove duplicates for an unknown reason`),MoreThanOneRangeSelected:T(`Please select only one range of cells`),EmptyTarget:T(`Please select a range of cells containing values.`),NoColumnsProvided:T(`Please select at latest one column to analyze.`),WillRemoveExistingMerge:eg.willRemoveExistingMerge}},fg={DateIs:{today:T(`today`),yesterday:T(`yesterday`),tomorrow:T(`tomorrow`),lastWeek:T(`in the past week`),lastMonth:T(`in the past month`),lastYear:T(`in the past year`)},DateIsBefore:{today:T(`today`),yesterday:T(`yesterday`),tomorrow:T(`tomorrow`),lastWeek:T(`one week ago`),lastMonth:T(`one month ago`),lastYear:T(`one year ago`)},CriterionError:{notEmptyValue:T(`The value must not be empty`),numberValue:T(`The value must be a number`),dateValue:T(`The value must be a date`),validRange:T(`The value must be a valid range`)}},pg={Errors:{Unexpected:T(`The table zone is invalid for an unknown reason`),TableOverlap:T(`You cannot create overlapping tables.`),NonContinuousTargets:T(`A table can only be created on a continuous selection.`),InvalidRange:T(`The range is invalid`),TargetOutOfSheet:T(`The range is out of the sheet`)},Checkboxes:{hasFilters:T(`Filter button`),headerRow:T(`Header row(s)`),bandedRows:T(`Banded rows`),firstColumn:T(`First column`),lastColumn:T(`Last column`),bandedColumns:T(`Banded columns`),automaticAutofill:T(`Automatically autofill formulas`),totalRow:T(`Total row`),isDynamic:T(`Auto-adjust to formula result`)},Tooltips:{filterWithoutHeader:T(`Cannot have filters without a header row`),isDynamic:T(`For tables based on array formulas only`)}},mg={labels:{no_calculations:T(`No calculations`),"%_of_grand_total":T(`% of grand total`),"%_of_col_total":T(`% of column total`),"%_of_row_total":T(`% of row total`),"%_of":T(`% of`),"%_of_parent_row_total":T(`% of parent row total`),"%_of_parent_col_total":T(`% of parent column total`),"%_of_parent_total":T(`% of parent total`),difference_from:T(`Difference from`),"%_difference_from":T(`% difference from`),running_total:T(`Running total`),"%_running_total":T(`% Running total`),rank_asc:T(`Rank smallest to largest`),rank_desc:T(`Rank largest to smallest`),index:T(`Index`)},descriptions:{"%_of_grand_total":()=>T(`Displayed as % of grand total`),"%_of_col_total":()=>T(`Displayed as % of column total`),"%_of_row_total":()=>T(`Displayed as % of row total`),"%_of":e=>T(`Displayed as % of "%s"`,e),"%_of_parent_row_total":e=>T(`Displayed as % of parent row total of "%s"`,e),"%_of_parent_col_total":()=>T(`Displayed as % of parent column total`),"%_of_parent_total":e=>T(`Displayed as % of parent "%s" total`,e),difference_from:e=>T(`Displayed as difference from "%s"`,e),"%_difference_from":e=>T(`Displayed as % difference from "%s"`,e),running_total:e=>T(`Displayed as running total based on "%s"`,e),"%_running_total":e=>T(`Displayed as % running total based on "%s"`,e),rank_asc:e=>T(`Displayed as rank from smallest to largest based on "%s"`,e),rank_desc:e=>T(`Displayed as rank largest to smallest based on "%s"`,e),index:()=>T(`Displayed as index`)},documentation:{no_calculations:T(`Displays the value that is entered in the field.`),"%_of_grand_total":T(`Displays values as a percentage of the grand total of all the values or data points in the report.`),"%_of_col_total":T(`Displays all the values in each column or series as a percentage of the total for the column or series.`),"%_of_row_total":T(`Displays the value in each row or category as a percentage of the total for the row or category.`),"%_of":T(`Displays values as a percentage of the value of the Base item in the Base field.`),"%_of_parent_row_total":T(`Calculates values as follows:
|
|
46
|
+
`))}extractAttr(e,t,n){let r=e.attributes[t];r||this.handleMissingValue(e,`attribute "${t}"`,n);let i=r?.value?r.value:n?.default;return i===void 0?void 0:new uh(i)}extractTextContent(e,t){if(t?.default!==void 0&&typeof t.default!=`string`)throw Error(`extractTextContent default value should be a string`);let n=e?.attributes[`xml:space`]?.value===`preserve`,r=e?.textContent;return(!e||r===null)&&this.handleMissingValue(e,`text content`,t),r&&=n?r:r.trim(),r?kf(r):t?.default}extractChildAttr(e,t,n,r){let i;i=typeof t==`number`?e.children[t]:this.querySelector(e,t),i||this.handleMissingValue(e,typeof t==`number`?`child at index ${t}`:`child <${t}>`,r);let a=i?this.extractAttr(i,n,r)?.asString():r?.default;return a===void 0?void 0:new uh(a)}extractChildTextContent(e,t,n){if(n?.default!==void 0&&typeof n.default!=`string`)throw Error(`extractTextContent default value should be a string`);let r=this.querySelector(e,t);return r||this.handleMissingValue(e,`child <${t}>`,n),r?this.extractTextContent(r,n):n?.default}handleMissingValue(e,t,n){if(n?.required)if(n?.default!==void 0)this.warningManager.addParsingWarning(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, replacing it by the default value ${n.default}`);else throw Error(`Missing required ${t} in element <${e.tagName}> of ${this.currentFile}, and no default value was set`)}extractColor(e,t,n){if(!e)return n?{rgb:n}:void 0;let r=this.extractAttr(e,`theme`)?.asString(),i;if(r!==void 0){if(!t||!t.clrScheme)throw Error(`Color referencing a theme but no theme was provided`);i=this.getThemeColor(r,t.clrScheme)}else i=this.extractAttr(e,`rgb`)?.asString(),i=i===`FF000000`?void 0:i;return{rgb:i||n,auto:this.extractAttr(e,`auto`)?.asBool(),indexed:this.extractAttr(e,`indexed`)?.asNum(),tint:this.extractAttr(e,`tint`)?.asNum()}}getTargetXmlFile(e){if(!e)throw Error(`Undefined target file`);let t=this.processRelationshipTargetName(e.target),n=this.getListOfXMLFiles().find(e=>e.file.fileName.endsWith(t));if(!n||!n.file)throw Error(`Cannot find target file`);return n}getTargetImageFile(e){if(!e)throw Error(`Undefined target file`);let t=this.processRelationshipTargetName(e.target),n=this.xlsxFileStructure.images.find(e=>e.fileName.endsWith(t));if(!n)throw Error(`Cannot find target file`);return n}querySelector(e,t){let n=lh(t);return e.querySelector(n)}querySelectorAll(e,t){let n=lh(t);return e.querySelectorAll(n)}getThemeColor(e,t){switch(e){case`0`:return`FFFFFF`;case`1`:return`000000`;case`2`:return t[3].value;case`3`:return t[2].value;default:return t[e].value}}processRelationshipTargetName(e){return e.replace(/\.+\//,``)}},fh=class extends dh{getTheme(){return{clrScheme:this.mapOnElements({query:`a:clrScheme`,parent:this.rootFile.file.xml,children:!0},e=>({name:e.tagName,value:this.extractChildAttr(e,0,`val`,{required:!0,default:$d}).asString(),lastClr:this.extractChildAttr(e,0,`lastClr`,{default:$d}).asString()}))}}getSharedStrings(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`si`},e=>this.mapOnElements({parent:e,query:`t`},e=>this.extractTextContent(e)||``).join(``))}},ph=class extends dh{theme;constructor(e,t,n,r){super(e,t,n),this.theme=r}extractConditionalFormattings(){let e=this.mapOnElements({parent:this.rootFile.file.xml,query:`worksheet > conditionalFormatting`},e=>({sqref:this.extractAttr(e,`sqref`,{required:!0}).asString().split(` `),pivot:this.extractAttr(e,`pivot`)?.asBool(),cfRules:this.extractCFRules(e,this.theme)}));return e.push(...this.mapOnElements({parent:this.rootFile.file.xml,query:`extLst x14:conditionalFormatting`},e=>({sqref:this.extractChildTextContent(e,`xm:sqref`,{required:!0}).split(` `),pivot:this.extractAttr(e,`xm:pivot`)?.asBool(),cfRules:this.extractCFRules(e,this.theme)}))),e}extractCFRules(e,t){return this.mapOnElements({parent:e,query:`cfRule, x14:cfRule`},e=>{let n=this.extractAttr(e,`type`,{required:!0}).asString();if(n===`dataBar`)throw Error(`Databars conditional formats are not supported.`);return{type:n,priority:this.extractAttr(e,`priority`,{required:!0}).asNum(),colorScale:this.extractCfColorScale(e,t),formula:this.extractCfFormula(e),iconSet:this.extractCfIconSet(e),dxfId:this.extractAttr(e,`dxfId`)?.asNum(),stopIfTrue:this.extractAttr(e,`stopIfTrue`)?.asBool(),aboveAverage:this.extractAttr(e,`aboveAverage`)?.asBool(),percent:this.extractAttr(e,`percent`)?.asBool(),bottom:this.extractAttr(e,`bottom`)?.asBool(),operator:this.extractAttr(e,`operator`)?.asString(),text:this.extractAttr(e,`text`)?.asString(),timePeriod:this.extractAttr(e,`timePeriod`)?.asString(),rank:this.extractAttr(e,`rank`)?.asNum(),stdDev:this.extractAttr(e,`stdDev`)?.asNum(),equalAverage:this.extractAttr(e,`equalAverage`)?.asBool()}})}extractCfFormula(e){return this.mapOnElements({parent:e,query:`formula`},e=>this.extractTextContent(e,{required:!0}))}extractCfColorScale(e,t){let n=this.querySelector(e,`colorScale`);if(n)return{colors:this.mapOnElements({parent:n,query:`color`},e=>this.extractColor(e,t,`ffffff`)),cfvos:this.extractCFVos(n)}}extractCfIconSet(e){let t=this.querySelector(e,`iconSet, x14:iconSet`);if(t)return{iconSet:this.extractAttr(t,`iconSet`,{default:`3TrafficLights1`}).asString(),showValue:this.extractAttr(t,`showValue`,{default:!0}).asBool(),percent:this.extractAttr(t,`percent`,{default:!0}).asBool(),reverse:this.extractAttr(t,`reverse`)?.asBool(),custom:this.extractAttr(t,`custom`)?.asBool(),cfvos:this.extractCFVos(t),cfIcons:this.extractCfIcons(t)}}extractCfIcons(e){let t=this.mapOnElements({parent:e,query:`cfIcon, x14:cfIcon`},e=>({iconSet:this.extractAttr(e,`iconSet`,{required:!0}).asString(),iconId:this.extractAttr(e,`iconId`,{required:!0}).asNum()}));return t.length===0?void 0:t}extractCFVos(e){return this.mapOnElements({parent:e,query:`cfvo, x14:cfvo`},e=>({type:this.extractAttr(e,`type`,{required:!0}).asString(),gte:this.extractAttr(e,`gte`,{default:!0})?.asBool(),value:e.attributes.val?this.extractAttr(e,`val`)?.asString():this.extractChildTextContent(e,`f, xm:f`)}))}},mh=class extends dh{theme;constructor(e,t,n,r){super(e,t,n),this.theme=r}extractDataValidations(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`worksheet > dataValidations > dataValidation`},e=>({type:this.extractAttr(e,`type`,{required:!0}).asString(),operator:this.extractAttr(e,`operator`,{default:`between`})?.asString(),sqref:this.extractAttr(e,`sqref`,{required:!0}).asString().split(` `),errorStyle:this.extractAttr(e,`errorStyle`)?.asString(),formula1:this.extractDataValidationFormula(e,1)[0],formula2:this.extractDataValidationFormula(e,2)[0],showErrorMessage:this.extractAttr(e,`showErrorMessage`)?.asBool(),errorTitle:this.extractAttr(e,`errorTitle`)?.asString(),error:this.extractAttr(e,`error`)?.asString(),showInputMessage:this.extractAttr(e,`showInputMessage`)?.asBool(),promptTitle:this.extractAttr(e,`promptTitle`)?.asString(),prompt:this.extractAttr(e,`prompt`)?.asString(),allowBlank:this.extractAttr(e,`allowBlank`)?.asBool()}))}extractDataValidationFormula(e,t){return this.mapOnElements({parent:e,query:`formula${t}`},e=>this.extractTextContent(e,{required:!0}))}},hh=class extends dh{extractChart(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`c:chartSpace`},e=>{let t=this.getChartType(e);if(!Yf[t])throw Error(`Unsupported chart type ${t}`);if(Yf[t]===`combo`)return this.extractComboChart(e);let n=this.mapOnElements({parent:e,query:`c:chart > c:title a:t`},e=>e.textContent||``).join(``),r=this.extractChildAttr(e,`c:grouping`,`val`,{default:`clustered`}).asString();return{title:{text:n},type:Yf[t],dataSets:this.extractChartDatasets(this.querySelectorAll(e,`c:${t}`),t),labelRange:this.extractLabelRange(t,e),backgroundColor:this.extractChildAttr(e,`c:chartSpace > c:spPr a:srgbClr`,`val`,{default:`ffffff`}).asString(),legendPosition:Jf[this.extractChildAttr(e,`c:legendPos`,`val`,{default:`none`}).asString()],stacked:r===`stacked`,fontColor:`000000`}})[0]}extractLabelRange(e,t){return e===`scatterChart`?this.extractChildTextContent(t,`c:ser c:strRef c:f`)||this.extractChildTextContent(t,`c:ser c:numRef c:f`):this.extractChildTextContent(t,`c:ser c:cat c:f`)}extractComboChart(e){let t=this.mapOnElements({parent:e,query:`c:title a:t`},e=>e.textContent||``).join(``),n=this.extractChildAttr(e,`c:grouping`,`val`,{default:`clustered`}).asString();return{title:{text:t},type:`combo`,dataSets:[...this.extractChartDatasets(this.querySelectorAll(e,`c:barChart`),`comboChart`),...this.extractChartDatasets(this.querySelectorAll(e,`c:lineChart`),`comboChart`)],labelRange:this.extractChildTextContent(e,`c:ser c:cat c:f`),backgroundColor:this.extractChildAttr(e,`c:chartSpace > c:spPr a:srgbClr`,`val`,{default:`ffffff`}).asString(),legendPosition:Jf[this.extractChildAttr(e,`c:legendPos`,`val`,{default:`none`}).asString()],stacked:n===`stacked`,fontColor:`000000`}}extractChartDatasets(e,t){return Array.from(e).map(e=>t===`scatterChart`?this.extractScatterChartDatasets(e):this.mapOnElements({parent:e,query:`c:ser`},e=>{let t={},n=this.extractChildTextContent(e,`c:tx c:f`);if(n)t={reference:n};else{let n=this.extractChildTextContent(e,`c:tx c:v`);n&&(t={text:n})}let r=this.extractChildAttr(e,`c:spPr a:solidFill a:srgbClr`,`val`);return{label:t,range:this.extractChildTextContent(e,`c:val c:f`,{required:!0}),backgroundColor:r?`${en(r.asString())}`:void 0}})).flat()}extractScatterChartDatasets(e){return this.mapOnElements({parent:e,query:`c:ser`},e=>{let t={},n=this.extractChildTextContent(e,`c:tx c:f`);if(n)t={reference:n};else{let n=this.extractChildTextContent(e,`c:tx c:v`);n&&(t={text:n})}return{label:t,range:this.extractChildTextContent(e,`c:yVal c:f`,{required:!0})}})}getChartType(e){let t=this.querySelector(e,`c:plotArea`);if(!t)throw Error(`Missing plot area in the chart definition.`);let n;for(let e of t.children){let t=sh(e.tagName);Qd.some(e=>e===t)&&(n?n!==t&&(n=`comboChart`):n=t)}if(n)return n;throw Error(`Unknown chart type`)}};let gh=`oneCellAnchor`,_h=`twoCellAnchor`;var vh=class extends dh{extractFigures(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`xdr:wsDr`,children:!0},e=>{let t=sh(e.tagName),n=this.extractFigureAnchorsByType(e,t),r=this.querySelector(e,`c:chart`),i=this.querySelector(e,`a:blip`);if(!r&&!i)throw Error(`Only chart and image figures are currently supported.`);return{anchors:n,data:r?this.extractChart(r):this.extractImage(e),figureSize:t===gh?this.extractFigureSizeFromSizeTag(e,`xdr:ext`):void 0}})}extractFigureAnchorsByType(e,t){switch(t){case gh:return[this.extractFigureAnchor(`xdr:from`,e)];case _h:return[this.extractFigureAnchor(`xdr:from`,e),this.extractFigureAnchor(`xdr:to`,e)];default:throw Error(`${t} is not supported for xlsx drawings. `)}}extractFigureSizeFromSizeTag(e,t){let n=this.querySelector(e,t);if(!n)throw Error(`Missing size element '${t}'`);return{cx:this.extractAttr(n,`cx`,{required:!0}).asNum(),cy:this.extractAttr(n,`cy`,{required:!0}).asNum()}}extractFigureAnchor(e,t){let n=this.querySelector(t,e);if(!n)throw Error(`Missing anchor element ${e}`);return{col:Number(this.extractChildTextContent(n,`xdr:col`,{required:!0})),colOffset:Number(this.extractChildTextContent(n,`xdr:colOff`,{required:!0})),row:Number(this.extractChildTextContent(n,`xdr:row`,{required:!0})),rowOffset:Number(this.extractChildTextContent(n,`xdr:rowOff`,{required:!0}))}}extractChart(e){let t=this.extractAttr(e,`r:id`,{required:!0}).asString(),n=new hh(this.getTargetXmlFile(this.relationships[t]),this.xlsxFileStructure,this.warningManager).extractChart();if(!n)throw Error(`Unable to extract chart definition`);return n}extractImage(e){let t=this.querySelector(e,`a:blip`),n=this.extractAttr(t,`r:embed`,{required:!0}).asString(),r=this.getTargetImageFile(this.relationships[n]);if(!r)throw Error(`Unable to extract image`);let i=r.fileName.split(`.`).at(-1),a=sh(e.tagName),o=a===_h?this.querySelector(e,`a:xfrm`):e,s=a===_h?`a:ext`:`xdr:ext`,c=this.extractFigureSizeFromSizeTag(o,s);return{imageSrc:r.imageSrc,mimetype:i?tp[i]:void 0,size:c}}},yh=class extends dh{getPivotTable(){return this.mapOnElements({query:`:root`,parent:this.rootFile.file.xml},e=>({name:this.extractAttr(e,`name`,{required:!0}).asString(),rowGrandTotals:this.extractAttr(e,`rowGrandTotals`,{default:!0}).asBool(),location:this.extractPivotLocation(e),style:this.extractPivotStyleInfo(e)}))[0]}extractPivotLocation(e){return this.mapOnElements({query:`location`,parent:e},e=>({ref:this.extractAttr(e,`ref`,{required:!0}).asString(),firstHeaderRow:this.extractAttr(e,`firstHeaderRow`,{required:!0}).asNum(),firstDataRow:this.extractAttr(e,`firstDataRow`,{required:!0}).asNum(),firstDataCol:this.extractAttr(e,`firstDataCol`,{required:!0}).asNum()}))[0]}extractPivotStyleInfo(e){return this.mapOnElements({query:`pivotTableStyleInfo`,parent:e},e=>({name:this.extractAttr(e,`name`,{required:!0}).asString(),showRowHeaders:this.extractAttr(e,`showRowHeaders`,{required:!0}).asBool(),showColHeaders:this.extractAttr(e,`showColHeaders`,{required:!0}).asBool(),showRowStripes:this.extractAttr(e,`showRowStripes`,{required:!0}).asBool(),showColStripes:this.extractAttr(e,`showColStripes`,{required:!0}).asBool(),showLastColumn:this.extractAttr(e,`showLastColumn`)?.asBool()}))[0]}},bh=class extends dh{getTable(){return this.mapOnElements({query:`table`,parent:this.rootFile.file.xml},e=>({displayName:this.extractAttr(e,`displayName`,{required:!0}).asString(),name:this.extractAttr(e,`name`)?.asString(),id:this.extractAttr(e,`id`,{required:!0}).asString(),ref:this.extractAttr(e,`ref`,{required:!0}).asString(),headerRowCount:this.extractAttr(e,`headerRowCount`,{default:1}).asNum(),totalsRowCount:this.extractAttr(e,`totalsRowCount`,{default:0}).asNum(),cols:this.extractTableCols(e),style:this.extractTableStyleInfo(e),autoFilter:this.extractTableAutoFilter(e)}))[0]}extractTableCols(e){return this.mapOnElements({query:`tableColumn`,parent:e},e=>({id:this.extractAttr(e,`id`,{required:!0}).asString(),name:this.extractAttr(e,`name`,{required:!0}).asString(),colFormula:this.extractChildTextContent(e,`calculatedColumnFormula`)}))}extractTableStyleInfo(e){return this.mapOnElements({query:`tableStyleInfo`,parent:e},e=>({name:this.extractAttr(e,`name`)?.asString(),showFirstColumn:this.extractAttr(e,`showFirstColumn`)?.asBool(),showLastColumn:this.extractAttr(e,`showLastColumn`)?.asBool(),showRowStripes:this.extractAttr(e,`showRowStripes`)?.asBool(),showColumnStripes:this.extractAttr(e,`showColumnStripes`)?.asBool()}))[0]}extractTableAutoFilter(e){return this.mapOnElements({query:`autoFilter`,parent:e},e=>({columns:this.extractFilterColumns(e),zone:this.extractAttr(e,`ref`,{required:!0}).asString()}))[0]}extractFilterColumns(e){return this.mapOnElements({query:`tableColumn`,parent:e},t=>({colId:this.extractAttr(e,`colId`,{required:!0}).asNum(),hiddenButton:this.extractAttr(e,`hiddenButton`,{default:!1}).asBool(),filters:this.extractSimpleFilter(t)}))}extractSimpleFilter(e){return this.mapOnElements({query:`filter`,parent:e},e=>({val:this.extractAttr(e,`val`,{required:!0}).asString()}))}},xh=class extends dh{theme;constructor(e,t,n,r){super(e,t,n),this.theme=r}getSheet(){return this.mapOnElements({query:`worksheet`,parent:this.rootFile.file.xml},e=>{let t=this.getSheetWorkbookInfo();return{sheetName:this.extractSheetName(),sheetViews:this.extractSheetViews(e),sheetFormat:this.extractSheetFormat(e),sheetProperties:this.extractSheetProperties(e),cols:this.extractCols(e),rows:this.extractRows(e),sharedFormulas:this.extractSharedFormulas(e),merges:this.extractMerges(e),cfs:this.extractConditionalFormats(),dataValidations:this.extractDataValidations(),figures:this.extractFigures(e),hyperlinks:this.extractHyperLinks(e),tables:this.extractTables(e),pivotTables:this.extractPivotTables(),isVisible:t.state===`visible`}})[0]}extractSheetViews(e){return this.mapOnElements({parent:e,query:`sheetView`},e=>{let t=this.querySelector(e,`pane`);return{tabSelected:this.extractAttr(e,`tabSelected`,{default:!1}).asBool(),showFormulas:this.extractAttr(e,`showFormulas`,{default:!1}).asBool(),showGridLines:this.extractAttr(e,`showGridLines`,{default:!0}).asBool(),showRowColHeaders:this.extractAttr(e,`showRowColHeaders`,{default:!0}).asBool(),pane:{xSplit:t?this.extractAttr(t,`xSplit`,{default:0}).asNum():0,ySplit:t?this.extractAttr(t,`ySplit`,{default:0}).asNum():0}}})}extractSheetName(){let e=Df(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find(t=>t.target===e).id;for(let e of this.querySelectorAll(this.xlsxFileStructure.workbook.file.xml,`sheet`))if(e.attributes[`r:id`].value===t)return e.attributes.name.value;throw Error(`Missing sheet name`)}getSheetWorkbookInfo(){let e=Df(this.xlsxFileStructure.workbook.file.fileName,this.rootFile.file.fileName),t=this.extractRelationships(this.xlsxFileStructure.workbook.rels).find(t=>t.target===e).id,n=this.mapOnElements({parent:this.xlsxFileStructure.workbook.file.xml,query:`sheet`},e=>({relationshipId:this.extractAttr(e,`r:id`,{required:!0}).asString(),sheetId:this.extractAttr(e,`sheetId`,{required:!0}).asString(),sheetName:this.extractAttr(e,`name`,{required:!0}).asString(),state:this.extractAttr(e,`state`,{default:`visible`}).asString()})).find(e=>e.relationshipId===t);if(!n)throw Error(`Cannot find corresponding workbook sheet`);return n}extractConditionalFormats(){return new ph(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractConditionalFormattings()}extractDataValidations(){return new mh(this.rootFile,this.xlsxFileStructure,this.warningManager,this.theme).extractDataValidations()}extractFigures(e){return this.mapOnElements({parent:e,query:`drawing`},e=>{let t=this.extractAttr(e,`r:id`,{required:!0}).asString();return new vh(this.getTargetXmlFile(this.relationships[t]),this.xlsxFileStructure,this.warningManager).extractFigures()})[0]||[]}extractTables(e){return this.mapOnElements({query:`tablePart`,parent:e},e=>{let t=this.extractAttr(e,`r:id`,{required:!0}).asString();return new bh(this.getTargetXmlFile(this.relationships[t]),this.xlsxFileStructure,this.warningManager).getTable()})}extractPivotTables(){try{return Object.values(this.relationships).filter(e=>e.type.endsWith(`pivotTable`)).map(e=>new yh(this.getTargetXmlFile(e),this.xlsxFileStructure,this.warningManager).getPivotTable())}catch(e){return this.catchErrorOnElement(e),[]}}extractMerges(e){return this.mapOnElements({parent:e,query:`mergeCell`},e=>this.extractAttr(e,`ref`,{required:!0}).asString())}extractSheetFormat(e){let t=this.querySelector(e,`sheetFormatPr`);if(t)return{defaultColWidth:this.extractAttr(t,`defaultColWidth`,{default:`8.43`}).asNum(),defaultRowHeight:this.extractAttr(t,`defaultRowHeight`,{default:`12.75`}).asNum()}}extractSheetProperties(e){let t=this.querySelector(e,`sheetPr`);if(t)return{outlinePr:this.extractSheetOutlineProperties(t),tabColor:this.extractColor(this.querySelector(t,`tabColor`),this.theme)}}extractSheetOutlineProperties(e){let t=this.querySelector(e,`outlinePr`);if(t)return{summaryBelow:this.extractAttr(t,`summaryBelow`,{default:!0}).asBool(),summaryRight:this.extractAttr(t,`summaryRight`,{default:!0}).asBool()}}extractCols(e){return this.mapOnElements({parent:e,query:`cols col`},e=>({width:this.extractAttr(e,`width`)?.asNum(),customWidth:this.extractAttr(e,`customWidth`)?.asBool(),bestFit:this.extractAttr(e,`bestFit`)?.asBool(),hidden:this.extractAttr(e,`hidden`)?.asBool(),min:this.extractAttr(e,`min`,{required:!0}).asNum(),max:this.extractAttr(e,`max`,{required:!0}).asNum(),styleIndex:this.extractAttr(e,`style`)?.asNum(),outlineLevel:this.extractAttr(e,`outlineLevel`)?.asNum(),collapsed:this.extractAttr(e,`collapsed`)?.asBool()}))}extractRows(e){let t=new Set;return this.mapOnElements({parent:e,query:`sheetData row`},e=>({index:this.extractAttr(e,`r`,{required:!0}).asNum(),cells:this.extractCells(e,t),height:this.extractAttr(e,`ht`)?.asNum(),customHeight:this.extractAttr(e,`customHeight`)?.asBool(),hidden:this.extractAttr(e,`hidden`)?.asBool(),styleIndex:this.extractAttr(e,`s`)?.asNum(),outlineLevel:this.extractAttr(e,`outlineLevel`)?.asNum(),collapsed:this.extractAttr(e,`collapsed`)?.asBool()}))}extractCells(e,t){return this.mapOnElements({parent:e,query:`c`},e=>{let n=this.extractAttr(e,`r`,{required:!0}).asString(),r=this.extractCellFormula(e);if(r?.ref&&r.sharedIndex===void 0){let e=$n(r.ref);for(let{col:r,row:i}of vr(e)){let e=w(r,i);e!==n&&t.add(e)}}let i=t.has(n);return{xc:n,styleIndex:this.extractAttr(e,`s`)?.asNum(),type:zf[this.extractAttr(e,`t`,{default:`n`}).asString()],value:i?void 0:this.extractChildTextContent(e,`v`)??void 0,formula:i?void 0:r}})}extractCellFormula(e){let t=this.querySelector(e,`f`);if(!t)return;let n=this.extractTextContent(t),r=this.extractAttr(t,`si`)?.asNum(),i=this.extractAttr(t,`ref`)?.asString();if(!((n===void 0||n.trim()===``)&&r===void 0))return{content:n,sharedIndex:r,ref:i}}extractHyperLinks(e){return this.mapOnElements({parent:e,query:`hyperlink`},e=>{let t=this.extractAttr(e,`r:id`)?.asString();return{xc:this.extractAttr(e,`ref`,{required:!0})?.asString(),location:this.extractAttr(e,`location`)?.asString(),display:this.extractAttr(e,`display`)?.asString(),relTarget:t?this.relationships[t].target:void 0}})}extractSharedFormulas(e){let t=this.querySelectorAll(e,`f[si][ref]`),n={};for(let e of t){let t=this.extractAttr(e,`si`,{required:!0}).asNum();n[t]=this.extractTextContent(e,{required:!0})}let r=[];for(let e=0;e<Object.keys(n).length;e++)n[e]?r.push(n[e]):(this.warningManager.addParsingWarning(`Missing shared formula ${e}, replacing it by empty formula`),r.push(``));return r}},Sh=class extends dh{theme;constructor(e,t,n){super(e.styles,e,t),this.theme=n}getNumFormats(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`numFmt`},e=>this.extractNumFormats(e))}extractNumFormats(e){return{id:this.extractAttr(e,`numFmtId`,{required:!0}).asNum(),format:this.extractAttr(e,`formatCode`,{required:!0,default:``}).asString()}}getFonts(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`font`},e=>this.extractFont(e))}extractFont(e){let t=this.extractChildAttr(e,`name`,`val`,{default:`Arial`}).asString(),n=this.extractChildAttr(e,`sz`,`val`,{default:Re.toString()}).asNum(),r=this.extractColor(this.querySelector(e,`color`),this.theme),i=this.querySelector(e,`i`)||void 0,a=i&&i.attributes.val?.value!==`0`,o=this.querySelector(e,`b`)||void 0,s=o&&o.attributes.val?.value!==`0`,c=this.querySelector(e,`strike`)||void 0,l=c&&c.attributes.val?.value!==`0`,u=this.querySelector(e,`u`)||void 0;return{name:t,size:n,color:r,italic:a,bold:s,underline:u&&u.attributes.val?.value!==`none`,strike:l}}getFills(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`fill`},e=>this.extractFill(e))}extractFill(e){let t=e.children[0];return t.tagName===`patternFill`?{patternType:t.attributes.patternType?.value,bgColor:this.extractColor(this.querySelector(t,`bgColor`),this.theme),fgColor:this.extractColor(this.querySelector(t,`fgColor`),this.theme)}:{patternType:`solid`,fgColor:this.extractColor(this.querySelectorAll(t,`color`)[1],this.theme)}}getBorders(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`border`},e=>this.extractBorder(e))}extractBorder(e){let t={left:this.extractSingleBorder(e,`left`,this.theme),right:this.extractSingleBorder(e,`right`,this.theme),top:this.extractSingleBorder(e,`top`,this.theme),bottom:this.extractSingleBorder(e,`bottom`,this.theme),diagonal:this.extractSingleBorder(e,`diagonal`,this.theme)};return t.diagonal&&(t.diagonalUp=this.extractAttr(e,`diagonalUp`)?.asBool(),t.diagonalDown=this.extractAttr(e,`diagonalDown`)?.asBool()),t}extractSingleBorder(e,t,n){let r=this.querySelector(e,t);if(!(!r||!r.attributes.style))return{style:this.extractAttr(r,`style`,{required:!0,default:`thin`}).asString(),color:this.extractColor(r.children[0],n,`000000`)}}extractAlignment(e){return{horizontal:this.extractAttr(e,`horizontal`,{default:`general`}).asString(),vertical:this.extractAttr(e,`vertical`,{default:`bottom`}).asString(),textRotation:this.extractAttr(e,`textRotation`)?.asNum(),wrapText:this.extractAttr(e,`wrapText`)?.asBool(),indent:this.extractAttr(e,`indent`)?.asNum(),relativeIndent:this.extractAttr(e,`relativeIndent`)?.asNum(),justifyLastLine:this.extractAttr(e,`justifyLastLine`)?.asBool(),shrinkToFit:this.extractAttr(e,`shrinkToFit`)?.asBool(),readingOrder:this.extractAttr(e,`readingOrder`)?.asNum()}}getDxfs(){return this.mapOnElements({query:`dxf`,parent:this.rootFile.file.xml},e=>{let t=this.querySelector(e,`font`),n=this.querySelector(e,`fill`),r=this.querySelector(e,`border`),i=this.querySelector(e,`numFmt`),a=this.querySelector(e,`alignment`);return{font:t?this.extractFont(t):void 0,fill:n?this.extractFill(n):void 0,numFmt:i?this.extractNumFormats(i):void 0,alignment:a?this.extractAlignment(a):void 0,border:r?this.extractBorder(r):void 0}})}getStyles(){return this.mapOnElements({query:`cellXfs xf`,parent:this.rootFile.file.xml},e=>{let t=this.querySelector(e,`alignment`);return{fontId:this.extractAttr(e,`fontId`,{required:!0,default:0}).asNum(),fillId:this.extractAttr(e,`fillId`,{required:!0,default:0}).asNum(),borderId:this.extractAttr(e,`borderId`,{required:!0,default:0}).asNum(),numFmtId:this.extractAttr(e,`numFmtId`,{required:!0,default:0}).asNum(),alignment:t?this.extractAlignment(t):void 0}})}},Ch=class extends dh{getExternalBook(){return this.mapOnElements({parent:this.rootFile.file.xml,query:`externalBook`},e=>({rId:this.extractAttr(e,`r:id`,{required:!0}).asString(),sheetNames:this.mapOnElements({parent:e,query:`sheetName`},e=>this.extractAttr(e,`val`,{required:!0}).asString()),datasets:this.extractExternalSheetData(e)}))[0]}extractExternalSheetData(e){return this.mapOnElements({parent:e,query:`sheetData`},e=>{let t=this.mapOnElements({parent:e,query:`cell`},e=>({xc:this.extractAttr(e,`r`,{required:!0}).asString(),value:this.extractChildTextContent(e,`v`,{required:!0})})),n={};for(let e of t)n[e.xc]=e.value;return{sheetId:this.extractAttr(e,`sheetId`,{required:!0}).asNum(),data:n}})}};function wh(e,t){return Th(Eh(e,t),t)}function Th(e,t){let n=[];for(let r of e){let e=Dh(r,t);n.push({file:{fileName:r,xml:t[r]},rels:e?{fileName:e,xml:t[e]}:void 0})}return n}function Eh(e,t){let n=t[`[Content_Types].xml`].querySelectorAll(`Override[ContentType="${e}"]`),r=[];for(let e of n){let t=e?.attributes.PartName.value;r.push(t.substring(1))}return r}function Dh(e,t){if(e===`[Content_Types].xml`)return`_rels/.rels`;let n=``,r=e.split(`/`);for(let e=0;e<r.length-1;e++)n+=r[e]+`/`;return n+=`_rels/`,n+=r[r.length-1]+`.rels`,t[n]||(n=void 0),n}var Oh=class{warningManager;xmls;images;constructor(e){this.warningManager=new Mf,this.xmls={},this.images=[];for(let t of Object.keys(e))if(t.endsWith(`.xml`)||t.endsWith(`.rels`)){let n=ch(e[t]);this.xmls[t]=nh(new Zd(n))}else t.includes(`media/image`)&&this.images.push({fileName:t,imageSrc:e[t].imageSrc})}convertXlsx(){let e=this.getXlsxData();return this.convertImportedData(e)}getXlsxData(){let e=this.buildXlsxFileStructure(),t=e.theme?new fh(e.theme,e,this.warningManager).getTheme():void 0,n=e.sharedStrings?new fh(e.sharedStrings,e,this.warningManager).getSharedStrings():[],r=e.sheets.sort((e,t)=>e.file.fileName.localeCompare(t.file.fileName,void 0,{numeric:!0})).map(n=>new xh(n,e,this.warningManager,t).getSheet()),i=e.externalLinks.map(t=>new Ch(t,e,this.warningManager).getExternalBook()),a=new Sh(e,this.warningManager,t);return{fonts:a.getFonts(),fills:a.getFills(),borders:a.getBorders(),dxfs:a.getDxfs(),numFmts:a.getNumFormats(),styles:a.getStyles(),sheets:r,sharedStrings:n,externalBooks:i}}buildXlsxFileStructure(){let e={sheets:wh(af.sheet,this.xmls),workbook:wh(af.workbook,this.xmls)[0],styles:wh(af.styles,this.xmls)[0],sharedStrings:wh(af.sharedStrings,this.xmls)[0],theme:wh(af.themes,this.xmls)[0],charts:wh(af.chart,this.xmls),figures:wh(af.drawing,this.xmls),tables:wh(af.table,this.xmls),pivots:wh(af.pivot,this.xmls),externalLinks:wh(af.externalLink,this.xmls),images:this.images};if(!e.workbook.rels)throw Error(T(`Cannot find workbook relations file`));return e}convertImportedData(e){let t={version:21,sheets:_m(e,this.warningManager),styles:hp(e,this.warningManager),formats:_p(e,this.warningManager),borders:pp(e,this.warningManager),revisionId:Ve};return Km(t,e),Object.keys(e.styles).map(t=>{e.styles[t]=jt(e.styles[t])}),t}};let kh=(e,t=()=>!0)=>[{goTo:e,guard:t}],Ah=(e,t=()=>!0)=>({goTo:e,guard:t}),jh={0:{REFERENCE:kh(2),NUMBER:kh(4),SYMBOL:[Ah(3,e=>Ls(e.value)),Ah(4,e=>Rs(e.value))]},3:{SPACE:kh(3),OPERATOR:kh(5,e=>e.value===`:`)},4:{SPACE:kh(4),OPERATOR:kh(6,e=>e.value===`:`)},2:{SPACE:kh(2),OPERATOR:kh(1,e=>e.value===`:`)},1:{SPACE:kh(1),NUMBER:kh(7),REFERENCE:kh(7,e=>Vs(e.value)),SYMBOL:kh(7,e=>zs(e.value)||Bs(e.value))},5:{SPACE:kh(5),SYMBOL:kh(7,e=>zs(e.value)),REFERENCE:kh(7,e=>Vs(e.value))},6:{SPACE:kh(6),NUMBER:kh(7),REFERENCE:kh(7,e=>Vs(e.value)),SYMBOL:kh(7,e=>Bs(e.value))},7:{}};function Mh(e){let t=0,n=jh[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=jh[o],r+=i.value;break}}return null}function Nh(e,t=O){let n=zc(e,t),r=[];for(;n.length;)r.push(Mh(n)||n.shift());return r}function Ph(e){let t=Nh(e),n=[];return{text:``.concat(...t.map(e=>{if(e.type===`REFERENCE`&&As.test(e.value)){let t=e.value.trim();return n.includes(t)||n.push(t),`|${n.indexOf(t)}|`}else return e.value})),dependencies:n}}let Fh={am_ET:7,ar_001:6,ar_SY:6,az_AZ:1,eu_ES:1,be_BY:1,bn_IN:1,bs_BA:1,bg_BG:1,ca_ES:1,zh_CN:7,zh_HK:7,zh_TW:7,hr_HR:1,cs_CZ:1,da_DK:1,nl_BE:1,nl_NL:1,en_AU:7,en_CA:7,en_GB:1,en_IN:7,en_NZ:7,et_EE:1,fi_FI:1,fr_BE:1,fr_CA:7,fr_CH:1,fr_FR:1,gl_ES:1,ka_GE:1,de_DE:1,de_CH:1,el_GR:1,gu_IN:7,he_IL:7,hi_IN:7,hu_HU:1,id_ID:7,it_IT:1,ja_JP:7,kab_DZ:6,km_KH:7,ko_KP:1,ko_KR:7,lo_LA:7,lv_LV:1,lt_LT:1,lb_LU:1,mk_MK:1,ml_IN:1,mn_MN:7,ms_MY:1,nb_NO:1,fa_IR:6,pl_PL:1,pt_AO:1,pt_BR:7,pt_PT:1,ro_RO:1,ru_RU:1,sr_RS:7,"sr@latin":7,sk_SK:1,sl_SI:1,es_AR:7,es_BO:1,es_CL:1,es_CO:7,es_CR:1,es_DO:1,es_EC:1,es_GT:7,es_MX:7,es_PA:7,es_PE:7,es_PY:7,es_UY:1,es_VE:7,sw:1,sv_SE:1,th_TH:7,tl_PH:1,tr_TR:1,uk_UA:1,vi_VN:1,sq_AL:1,te_IN:7,en_US:7,my_MM:7,es_ES:1,es_419:1},Ih=new h;Ih.add(`migration_1`,{versionFrom:`1`,migrate(e){return e.sheets&&e.sheets[0]&&(e.activeSheet=e.sheets[0].name),e}}).add(`migration_2`,{versionFrom:`2`,migrate(e){if(e.sheets&&e.sheets.length)for(let t of e.sheets)t.id=t.id||t.name;return e}}).add(`migration_3`,{versionFrom:`3`,migrate(e){return e.sheets&&e.activeSheet&&(e.activeSheet=e.sheets.find(t=>t.name===e.activeSheet).id),e}}).add(`migration_4`,{versionFrom:`4`,migrate(e){for(let t of e.sheets||[])t.figures=t.figures||[];return e}}).add(`migration_5`,{versionFrom:`5`,migrate(e){for(let t of e.sheets||[])for(let e in t.cells||[]){let n=t.cells[e];n.content&&n.content.startsWith(`=`)&&(n.formula=Ph(n.content))}return e}}).add(`migration_6`,{versionFrom:`6`,migrate(e){for(let t of e.sheets||[])for(let e in t.figures||[]){let{dataSets:n,...r}=t.figures[e].data,i=[];for(let e of n)if(e.labelCell){let t=$n(e.dataRange),n=e.labelCell+`:`+w(t.right,t.bottom);i.push(n)}else i.push(e.dataRange);r.dataSetsHaveTitle=!!n[0].labelCell,r.dataSets=i,t.figures[e].data=r}return e}}).add(`migration_7`,{versionFrom:`7`,migrate(e){let t=[];for(let n of e.sheets||[]){if(!n.name)continue;let e=n.name,r=st(e,`_`),i=1,a=r;for(;t.includes(a);)a=`${r}${i}`,i++;n.name=a,t.push(a);let o=t=>{if(t===void 0)return t;let n=t.replace(e,a),r=t;for(;r!==n;)r=n,n=r.replace(e,a);return r};for(let e in n.cells){let t=n.cells[e];t.formula&&(t.formula.dependencies=t.formula.dependencies.map(o))}for(let e of n.figures||[])if(e.type===`chart`){let t=e.data.dataSets.map(o),n=o(e.data.labelRange);e.data={...e.data,dataSets:t,labelRange:n}}for(let e of n.conditionalFormats||[]){e.ranges=e.ranges.map(o);for(let t of[`minimum`,`maximum`,`midpoint`,`upperInflectionPoint`,`lowerInflectionPoint`])e.rule[t]?.type===`formula`&&(e.rule[t].value=o(e.rule[t].value))}}return e}}).add(`migration_8`,{versionFrom:`8`,migrate(e){for(let t of e.sheets||[])for(let e of t.figures||[])e.data.background=oe,e.data.verticalAxisPosition=`left`,e.data.legendPosition=`top`,e.data.stacked=!1;return e}}).add(`migration_9`,{versionFrom:`9`,migrate(e){for(let t of e.sheets||[])for(let e in t.cells||[]){let n=t.cells[e];if(n.formula){let{text:e,dependencies:t}=n.formula;for(let[n,r]of Object.entries(t)){let t=`\\|${n}\\|`;e=e.replace(new RegExp(t,`g`),r)}n.content=e,delete n.formula}}return e}}).add(`migration_10`,{versionFrom:`10`,migrate(e){let t={};for(let n of e.sheets||[])for(let e in n.cells||[]){let r=n.cells[e];r.format&&=Fr(r.format,t)}return e.formats=t,e}}).add(`migration_11`,{versionFrom:`11`,migrate(e){for(let t of e.sheets||[])t.isVisible=!0;return e}}).add(`migration_12`,{versionFrom:`12`,migrate(e){return Lh(e)}}).add(`migration_12_5`,{versionFrom:`12.5`,migrate(e){for(let t in e.borders){let n=e.borders[t];for(let e in n)Array.isArray(n[e])&&(n[e]={style:n[e][0],color:n[e][1]})}return e}}).add(`migration_13`,{versionFrom:`13`,migrate(e){return e.settings||={},e.settings.locale||(e.settings.locale=O),e}}).add(`migration_14`,{versionFrom:`14`,migrate(e){return Lh(e)}}).add(`migration_14_5`,{versionFrom:`14.5`,migrate(e){for(let t of e.sheets||[])t.tables=t.tables||t.filterTables||[],delete t.filterTables;return e}}).add(`migration_15`,{versionFrom:`15`,migrate(e){return e.pivots||={},e.pivotNextId||=ku(e.pivots)+1,e}}).add(`migration_16`,{versionFrom:`16`,migrate(e){for(let t of e.sheets||[])for(let e in t.figures||[]){let n=t.figures[e];`title`in n.data&&typeof n.data.title==`string`&&(n.data.title={text:n.data.title});let r=n.data.type;if(![`line`,`bar`,`pie`,`scatter`,`waterfall`,`combo`].includes(r))continue;let{dataSets:i,...a}=t.figures[e].data;a.dataSets=i.map(e=>({dataRange:e})),t.figures[e].data=a}return e}}).add(`migration_17`,{versionFrom:`17`,migrate(e){return e}}).add(`migration_18`,{versionFrom:`18`,migrate(e){for(let t of Object.values(e.pivots||{}))t.measures=t.measures.map(e=>({id:e.name,fieldName:e.name,aggregator:e.aggregator})),t.columns=t.columns.map(e=>({fieldName:e.name,order:e.order,granularity:e.granularity})),t.rows=t.rows.map(e=>({fieldName:e.name,order:e.order,granularity:e.granularity}));return e}}).add(`migration_19`,{versionFrom:`19`,migrate(e){let t=e.settings?.locale;return t&&(t.weekStart=Fh[t.code]||1),e}}).add(`migration_20`,{versionFrom:`20`,migrate(e){for(let t of e.sheets||[]){t.styles={},t.formats={},t.borders={};for(let e in t.cells)t.styles[e]=t.cells[e].style,t.formats[e]=t.cells[e].format,t.borders[e]=t.cells[e].border,delete t.cells[e].style,delete t.cells[e].format,delete t.cells[e].border}return e}}).add(`migration_21`,{versionFrom:`21`,migrate(e){for(let t of e.sheets||[])for(let e of t.figures||[]){if(e.tag!==`chart`||e.data.type!==`gauge`)continue;let t=e.data;t?.sectionRule?.lowerInflectionPoint&&(t.sectionRule.lowerInflectionPoint.operator=`<=`),t?.sectionRule?.upperInflectionPoint&&(t.sectionRule.upperInflectionPoint.operator=`<=`)}return e}});function Lh(e){for(let t of e.sheets||[]){let e=[];for(let n of t.filterTables||[]){let t=$n(n.range),r=e.findIndex(e=>dr(e,t));r===-1?e.push(t):e[r]=t}t.filterTables=e.map(e=>({range:nr(e)}))}return e}let Rh=`Sheet1`;function zh(e,t){if(!e)return Zh();console.debug(`### Loading data ###`);let n=performance.now();if(e[`[Content_Types].xml`]){let n=new Oh(e);if(e=n.convertXlsx(),t)for(let e of n.warningManager.warnings.sort())console.warn(e)}return`version`in e&&e.version<22&&(console.debug(`Migrating data from version`,e.version),e=Vh(e)),e=Hh(e),console.debug(`Data loaded in`,performance.now()-n,`ms`),console.debug(`###`),e}function Bh(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<Math.max(n.length,r.length);e++){let t=n[e]||0,i=r[e]||0;if(t>i)return 1;if(t<i)return-1}return 0}function Vh(e){let t=performance.now(),n=Ih.getAll().sort((e,t)=>Bh(e.versionFrom,t.versionFrom)),r=n.findIndex(t=>t.versionFrom===e.version.toString());for(let t=r;t<n.length;t++)e=n[t].migrate(e);return console.debug(`Data migrated in`,performance.now()-t,`ms`),e}function Hh(e){return e=Uh(e),e=Wh(e),e}function Uh(e){if(e.uniqueFigureIds)return e;let t=new Set,n=new Tc;for(let r of e.sheets||[])for(let e of r.figures||[])t.has(e.id)&&(e.id+=n.uuidv4()),t.add(e.id);return e.uniqueFigureIds=!0,e}function Wh(e){let t=Object.assign(Zh(),e,{version:22});return t.sheets=t.sheets?t.sheets.map((e,t)=>Object.assign(Xh(`Sheet${t+1}`,`Sheet${t+1}`),e)):[],t.sheets.length===0&&t.sheets.push(Xh(Rh,`Sheet1`)),tl(t.settings.locale)||(t.settings.locale=O),t}function Gh(e,t){return t=Kh(e,t),t=qh(t,`SORT_CELLS`),t=qh(t,`SET_DECIMAL`),t=Jh(e,t),t=Yh(e,t),t}function Kh(e,t){if(Object.keys(e).length!==0)return t;let n=[],r=[],i=e=>{if(e.type===`CREATE_SHEET`)n.push(e.sheetId);else if(`sheetId`in e&&!n.includes(e.sheetId))return{...e,sheetId:Rh};return e};for(let e of t)e.type===`REMOTE_REVISION`?r.push({...e,commands:e.commands.map(i)}):r.push(e);return r}function qh(e,t){let n=[];for(let r of e)r.type===`REMOTE_REVISION`?n.push({...r,commands:r.commands.filter(e=>e.type!==t)}):n.push(r);return n}function Jh(e,t){let n=[],r={};for(let t of e.sheets||[])t.figures?.forEach(e=>{e.tag===`chart`&&(r[e.id]=e.data)});for(let e of t)if(e.type===`REMOTE_REVISION`){let t=[];for(let n of e.commands){let e=n;switch(n.type){case`CREATE_CHART`:r[n.id]=n.definition;break;case`UPDATE_CHART`:if(!r[n.id]){console.log(`Fix chart definition: chart with id ${n.id} not found.`);continue}let t={...r[n.id],...n.definition};e={...n,definition:t},r[n.id]=t;break}t.push(e)}n.push({...e,commands:t})}else n.push(e);return n}function Yh(e,t){let n={};for(let t of e.sheets||[])n[t.id]=t.name;let r=[];for(let e of t)if(e.type===`REMOTE_REVISION`){let t=[];for(let r of e.commands){switch(r.type){case`DUPLICATE_SHEET`:r.sheetNameTo=r.sheetNameTo??tc(n[r.sheetId],Object.values(n));break;case`CREATE_SHEET`:case`RENAME_SHEET`:n[r.sheetId]=r.name||ec(Object.values(n));break}t.push(r)}r.push({...e,commands:t})}else r.push(e);return t}function Xh(e,t){return{id:e,name:t,colNumber:26,rowNumber:100,cells:{},styles:{},formats:{},borders:{},cols:{},rows:{},merges:[],conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],isVisible:!0}}function Zh(e=`Sheet1`){return{version:22,sheets:[Xh(Rh,e)],styles:{},formats:{},borders:{},revisionId:Ve,uniqueFigureIds:!0,settings:{locale:O},pivots:{},pivotNextId:1,customTableStyles:{}}}function Qh(e,t){return{...Xh(e,t),charts:[],images:[]}}function $h(){return{...Zh(),sheets:[Qh(Rh,`Sheet1`)]}}let eg={wrongPasteSelection:T(`This operation is not allowed with multiple selections.`),willRemoveExistingMerge:T(`Cannot perform this action on merged cells. Unmerge the cells and try again.`),wrongFigurePasteOption:T(`Cannot do a special paste of a figure.`),frozenPaneOverlap:T(`This operation is not allowed due to an overlapping frozen pane.`)};function tg(e,t){t.isSuccessful||(t.reasons.includes(`WrongPasteSelection`)?e.raiseError(eg.wrongPasteSelection):t.reasons.includes(`WillRemoveExistingMerge`)?e.raiseError(eg.willRemoveExistingMerge):t.reasons.includes(`WrongFigurePasteOption`)?e.raiseError(eg.wrongFigurePasteOption):t.reasons.includes(`FrozenPaneOverlap`)&&e.raiseError(eg.frozenPaneOverlap))}function ng(e,t,n){tg(e,e.model.dispatch(`PASTE`,{target:t,pasteOption:n}))}function rg(e,t,n,r){n.data&&n.data.version!==22&&e.notifyUser({type:`warning`,text:T(`You copied content from a different version of the application. Only text content will be pasted.`),sticky:!1}),tg(e,e.model.dispatch(`PASTE_FROM_OS_CLIPBOARD`,{target:t,clipboardContent:n,pasteOption:r}))}let ig={Errors:{InvalidRange:T(`The range is invalid`),FirstArgMissing:T(`The argument is missing. Please provide a value`),SecondArgMissing:T(`The second argument is missing. Please provide a value`),MinNaN:T(`The minpoint must be a number`),MidNaN:T(`The midpoint must be a number`),MaxNaN:T(`The maxpoint must be a number`),ValueUpperInflectionNaN:T(`The first value must be a number`),ValueLowerInflectionNaN:T(`The second value must be a number`),MinBiggerThanMax:T(`Minimum must be smaller then Maximum`),MinBiggerThanMid:T(`Minimum must be smaller then Midpoint`),MidBiggerThanMax:T(`Midpoint must be smaller then Maximum`),LowerBiggerThanUpper:T(`Lower inflection point must be smaller than upper inflection point`),MinInvalidFormula:T(`Invalid Minpoint formula`),MaxInvalidFormula:T(`Invalid Maxpoint formula`),MidInvalidFormula:T(`Invalid Midpoint formula`),ValueUpperInvalidFormula:T(`Invalid upper inflection point formula`),ValueLowerInvalidFormula:T(`Invalid lower inflection point formula`),EmptyRange:T(`A range needs to be defined`),ValueCellIsInvalidFormula:T(`At least one of the provided values is an invalid formula`),Unexpected:T(`The rule is invalid for an unknown reason`)},ColorScale:T(`Color scale`),IconSet:T(`Icon set`),DataBar:T(`Data bar`)},ag={IsEmpty:T(`Is empty`),IsNotEmpty:T(`Is not empty`),ContainsText:T(`Contains`),NotContains:T(`Does not contain`),BeginsWith:T(`Starts with`),EndsWith:T(`Ends with`),Equal:T(`Is equal to`),NotEqual:T(`Is not equal to`),GreaterThan:T(`Is greater than`),GreaterThanOrEqual:T(`Is greater than or equal to`),LessThan:T(`Is less than`),LessThanOrEqual:T(`Is less than or equal to`),Between:T(`Is between`),NotBetween:T(`Is not between`)},og={Series:T(`Series`),BackgroundColor:T(`Background color`),StackedBarChart:T(`Stacked bar chart`),StackedLineChart:T(`Stacked line chart`),StackedAreaChart:T(`Stacked area chart`),StackedColumnChart:T(`Stacked column chart`),CumulativeData:T(`Cumulative data`),TreatLabelsAsText:T(`Treat labels as text`),AggregatedChart:T(`Aggregate`),Errors:{Unexpected:T(`The chart definition is invalid for an unknown reason`),InvalidDataSet:T(`The dataset is invalid`),InvalidLabelRange:T(`Labels are invalid`),InvalidScorecardKeyValue:T(`The key value is invalid`),InvalidScorecardBaseline:T(`The baseline value is invalid`),InvalidGaugeDataRange:T(`The data range is invalid`),EmptyGaugeRangeMin:T(`A minimum range limit value is needed`),GaugeRangeMinNaN:T(`The minimum range limit value must be a number`),EmptyGaugeRangeMax:T(`A maximum range limit value is needed`),GaugeRangeMaxNaN:T(`The maximum range limit value must be a number`),GaugeRangeMinBiggerThanRangeMax:T(`Minimum range limit must be smaller than maximum range limit`),GaugeLowerInflectionPointNaN:T(`The lower inflection point value must be a number`),GaugeUpperInflectionPointNaN:T(`The upper inflection point value must be a number`)}},sg={Custom:T(`Custom`)},cg=T(`Merged cells are preventing this operation. Unmerge those cells and try again.`),lg=T(`The header row of a table can't be moved.`),ug={Errors:{Unexpected:T(`Cannot split the selection for an unknown reason`),NoSplitSeparatorInSelection:T(`There is no match for the selected separator in the selection`),MoreThanOneColumnSelected:T(`Only a selection from a single column can be split`),SplitWillOverwriteContent:T(`Splitting will overwrite existing content`)}},dg={Errors:{Unexpected:T(`Cannot remove duplicates for an unknown reason`),MoreThanOneRangeSelected:T(`Please select only one range of cells`),EmptyTarget:T(`Please select a range of cells containing values.`),NoColumnsProvided:T(`Please select at latest one column to analyze.`),WillRemoveExistingMerge:eg.willRemoveExistingMerge}},fg={DateIs:{today:T(`today`),yesterday:T(`yesterday`),tomorrow:T(`tomorrow`),lastWeek:T(`in the past week`),lastMonth:T(`in the past month`),lastYear:T(`in the past year`)},DateIsBefore:{today:T(`today`),yesterday:T(`yesterday`),tomorrow:T(`tomorrow`),lastWeek:T(`one week ago`),lastMonth:T(`one month ago`),lastYear:T(`one year ago`)},CriterionError:{notEmptyValue:T(`The value must not be empty`),numberValue:T(`The value must be a number`),dateValue:T(`The value must be a date`),validRange:T(`The value must be a valid range`)}},pg={Errors:{Unexpected:T(`The table zone is invalid for an unknown reason`),TableOverlap:T(`You cannot create overlapping tables.`),NonContinuousTargets:T(`A table can only be created on a continuous selection.`),InvalidRange:T(`The range is invalid`),TargetOutOfSheet:T(`The range is out of the sheet`)},Checkboxes:{hasFilters:T(`Filter button`),headerRow:T(`Header row(s)`),bandedRows:T(`Banded rows`),firstColumn:T(`First column`),lastColumn:T(`Last column`),bandedColumns:T(`Banded columns`),automaticAutofill:T(`Automatically autofill formulas`),totalRow:T(`Total row`),isDynamic:T(`Auto-adjust to formula result`)},Tooltips:{filterWithoutHeader:T(`Cannot have filters without a header row`),isDynamic:T(`For tables based on array formulas only`)}},mg={labels:{no_calculations:T(`No calculations`),"%_of_grand_total":T(`% of grand total`),"%_of_col_total":T(`% of column total`),"%_of_row_total":T(`% of row total`),"%_of":T(`% of`),"%_of_parent_row_total":T(`% of parent row total`),"%_of_parent_col_total":T(`% of parent column total`),"%_of_parent_total":T(`% of parent total`),difference_from:T(`Difference from`),"%_difference_from":T(`% difference from`),running_total:T(`Running total`),"%_running_total":T(`% Running total`),rank_asc:T(`Rank smallest to largest`),rank_desc:T(`Rank largest to smallest`),index:T(`Index`)},descriptions:{"%_of_grand_total":()=>T(`Displayed as % of grand total`),"%_of_col_total":()=>T(`Displayed as % of column total`),"%_of_row_total":()=>T(`Displayed as % of row total`),"%_of":e=>T(`Displayed as % of "%s"`,e),"%_of_parent_row_total":e=>T(`Displayed as % of parent row total of "%s"`,e),"%_of_parent_col_total":()=>T(`Displayed as % of parent column total`),"%_of_parent_total":e=>T(`Displayed as % of parent "%s" total`,e),difference_from:e=>T(`Displayed as difference from "%s"`,e),"%_difference_from":e=>T(`Displayed as % difference from "%s"`,e),running_total:e=>T(`Displayed as running total based on "%s"`,e),"%_running_total":e=>T(`Displayed as % running total based on "%s"`,e),rank_asc:e=>T(`Displayed as rank from smallest to largest based on "%s"`,e),rank_desc:e=>T(`Displayed as rank largest to smallest based on "%s"`,e),index:()=>T(`Displayed as index`)},documentation:{no_calculations:T(`Displays the value that is entered in the field.`),"%_of_grand_total":T(`Displays values as a percentage of the grand total of all the values or data points in the report.`),"%_of_col_total":T(`Displays all the values in each column or series as a percentage of the total for the column or series.`),"%_of_row_total":T(`Displays the value in each row or category as a percentage of the total for the row or category.`),"%_of":T(`Displays values as a percentage of the value of the Base item in the Base field.`),"%_of_parent_row_total":T(`Calculates values as follows:
|
|
47
47
|
(value for the item) / (value for the parent item on rows)`),"%_of_parent_col_total":T(`Calculates values as follows:
|
|
48
48
|
(value for the item) / (value for the parent item on columns)`),"%_of_parent_total":T(`Calculates values as follows:
|
|
49
49
|
(value for the item) / (value for the parent item of the selected Base field)`),difference_from:T(`Displays values as the difference from the value of the Base item in the Base field.`),"%_difference_from":T(`Displays values as the percentage difference from the value of the Base item in the Base field.`),running_total:T(`Displays the value for successive items in the Base field as a running total.`),"%_running_total":T(`Calculates the value as a percentage for successive items in the Base field that are displayed as a running total.`),rank_asc:T(`Displays the rank of selected values in a specific field, listing the smallest item in the field as 1, and each larger value with a higher rank value.`),rank_desc:T(`Displays the rank of selected values in a specific field, listing the largest item in the field as 1, and each smaller value with a higher rank value.`),index:T(`Calculates values as follows:
|
|
@@ -167,7 +167,7 @@ stores.inject(MyMetaStore, storeInstance);
|
|
|
167
167
|
`)+`
|
|
168
168
|
`}return(e){return new xE(this.scope,this.code,e)}toString(){return wE(this.code)}},xE=class{scope;returnExpression;code;constructor(e,t,n){this.scope=e,this.returnExpression=n,this.code=wE(t)}toString(){return this.code}assignResultToVariable(){if(this.scope.isAlreadyDeclared(this.returnExpression))return this;let e=this.scope.nextVariableName(),t=new bE(this.scope);return t.append(this.code),t.append(`const ${e} = ${this.returnExpression};`),t.return(e)}},SE=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 CE(e){return e.split(`
|
|
169
169
|
`).map(e=>e.trim()).filter(e=>e!==``)}function wE(e){let t=``,n=0,r=CE(e);for(let e of r)e.startsWith(`}`)&&n--,t+=` `.repeat(n)+e+`
|
|
170
|
-
`,e.endsWith(`{`)&&n++;return t.trim()}let TE=zT.content,EE={"=":`EQ`,"+":`ADD`,"-":`MINUS`,"*":`MULTIPLY`,"/":`DIVIDE`,">=":`GTE`,"<>":`NE`,">":`GT`,"<=":`LTE`,"<":`LT`,"^":`POWER`,"&":`CONCATENATE`},DE={"-":`UMINUS`,"+":`UPLUS`,"%":`UNARY.PERCENT`},OE={};function kE(e){return AE(Nh(e))}function AE(e){try{return jE(e)}catch(t){return{tokens:e,dependencies:[],execute:function(){return t},isBadExpression:!0}}}function jE(e){let{dependencies:t,literalValues:n,symbols:r}=NE(e),i=ME(e);if(!OE[i]){let t=gC([...e]),n=new SE,s=0,c=0,l=0;if(t.type===`BIN_OPERATION`&&t.value===`:`||t.type===`EMPTY`)throw new ra(T(`Invalid formula`));let u=o(t),d=new bE;d.append(u),d.append(`return ${u.returnExpression};`),OE[i]=Function(`deps`,`ref`,`range`,`getSymbolValue`,`ctx`,d.toString());function a(e){let{args:t}=e,n=TE[e.value.toUpperCase()];if(!n)throw new sa(T(`Unknown function: "%s"`,e.value));PE(e);let r=[];for(let e=0;e<t.length;e++){let i=n.getArgToFocus(e+1)-1,a=n.args[i],s=t[e],c=a.type||[],l=c.includes(`META`),u=c.some(e=>FE(e));r.push(o(s,l,u))}return r}function o(e,t=!1,i=!1){let u=new bE(n);if(e.type!==`REFERENCE`&&!(e.type===`BIN_OPERATION`&&e.value===`:`)&&t)throw new ra(T(`Argument must be a reference to a cell or range.`));switch(e.debug&&u.append(`debugger;`),e.type){case`BOOLEAN`:return u.return(`{ value: ${e.value} }`);case`NUMBER`:return u.return(`this.literalValues.numbers[${c++}]`);case`STRING`:return u.return(`this.literalValues.strings[${s++}]`);case`REFERENCE`:return!t&&e.value.includes(`:`)||i?u.return(`range(deps[${l++}])`):u.return(`ref(deps[${l++}], ${t?`true`:`false`})`);case`FUNCALL`:let n=a(e).map(e=>e.assignResultToVariable());u.append(...n);let d=e.value.toUpperCase();return u.return(`ctx['${d}'](${n.map(e=>e.returnExpression)})`);case`UNARY_OPERATION`:{let t=DE[e.value],n=o(e.operand,!1,!1).assignResultToVariable();return u.append(n),u.return(`ctx['${t}'](${n.returnExpression})`)}case`BIN_OPERATION`:{let t=EE[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:OE[i],dependencies:t,literalValues:n,symbols:r,tokens:e,isBadExpression:!1}}function ME(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 NE(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=et(i.value);t.strings.push({value:e});break;case`NUMBER`:{let e=ji(i.value,O);t.numbers.push({value:e});break}case`SYMBOL`:r.push(at(i.value,`'`))}return{dependencies:n,literalValues:t,symbols:r}}function PE(e){let t=e.args.length,n=e.value.toUpperCase(),r=TE[n];if(t<r.minArgRequired)throw new ra(T(`Invalid number of arguments for the %s function. Expected %s minimum, but got %s instead.`,n,r.minArgRequired.toString(),t.toString()));if(t>r.maxArgPossible)throw new ra(T(`Invalid number of arguments for the %s function. Expected %s maximum, but got %s instead.`,n,r.maxArgPossible.toString(),t.toString()));let i=r.nbrArgRepeating;if(i>1){let e=r.args.length-i;if((t-e)%i!==0)throw new ra(T(`Invalid number of arguments for the %s function. Expected all arguments after position %s to be supplied by groups of %s arguments`,n,e.toString(),i.toString()))}}function FE(e){return e.startsWith(`RANGE`)}let IE=zT.content;function LE(e){try{return vC(gC(e)).filter(e=>e.type===`FUNCALL`&&!IE[e.value.toUpperCase()]?.isExported).length===0}catch{return!1}}function RE(e,t){if(!e.some(e=>e.type===`SYMBOL`&&t.includes(e.value.toUpperCase())))return[];let n;try{n=gC(e)}catch{return[]}return zE(n,t)}function zE(e,t){return vC(e).filter(e=>e.type===`FUNCALL`&&t.includes(e.value.toUpperCase())).map(e=>({functionName:e.value.toUpperCase(),args:e.args}))}let BE=[`PIVOT.VALUE`,`PIVOT.HEADER`,`PIVOT`];function VE(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:vE.STRING}],fuzzySearchKey:r}}function HE(e){let t=`"${e.id}"`,n=e.displayName+e.fieldName+t;return{text:t,description:e.displayName,htmlContent:[{value:t,color:vE.STRING}],fuzzySearchKey:n}}function UE(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 WE(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 GE(e){let t=e.functionContext?.args[0];if(!(!t||![`STRING`,`NUMBER`].includes(t.type)))return t.value}function KE(e){return RE(e,BE)[0]}function qE(e){return RE(e,BE)}function JE(e){return RE(e,BE).length}let YE=new h;YE.add(`SPREADSHEET`,!1),l_.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:vE.NUMBER}],fuzzySearchKey:n+t.name}}).filter(S)},selectProposal:WE}),l_.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=GE(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:T(`Count`),htmlContent:[{value:e,color:vE.STRING}],fuzzySearchKey:T(`Count`)+e}}return HE(e)}).filter(S):[]},selectProposal:UE}),l_.add(`pivot_group_fields`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||!XE(e)&&!ZE(e))return;let n=GE(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(S),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=YE.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(S);return h.map(e=>{let[t,n]=e.split(`:`),r=a[t];return r?VE(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:T(`%s (positional)`,t.string)+(t.help?` (${t.help})`:``),htmlContent:[{value:n,color:vE.STRING}],fuzzySearchKey:t.string+n}})).filter(S)},selectProposal:UE});function XE(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.VALUE`&&t.argPosition>=2&&t.argPosition%2==0}function ZE(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.HEADER`&&t.argPosition>=1&&t.argPosition%2==1}l_.add(`pivot_group_values`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||!e||!QE(e)&&!$E(e))return;let n=GE(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(Mo).map((e,t)=>({text:`${t+1}`,fuzzySearchKey:e.toString(),description:e.toString(),htmlContent:[{value:`${t+1}`,color:vE.NUMBER}]})):s.granularity===`quarter_number`?[1,2,3,4].map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:T(`Quarter %s`,e),htmlContent:[{value:`${e}`,color:vE.NUMBER}]})):s.granularity===`day_of_month`?x(1,32).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:vE.NUMBER}]})):s.granularity===`iso_week_number`?x(0,54).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:vE.NUMBER}]})):s.granularity===`day_of_week`?x(1,8).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:vE.NUMBER}]})):s.granularity===`hour_number`?x(0,24).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:vE.NUMBER}]})):s.granularity===`minute_number`?x(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:vE.NUMBER}]})):s.granularity===`second_number`?x(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:vE.NUMBER}]})):i.getPossibleFieldValues(s).map(({value:e,label:t})=>{let n=typeof e==`string`,r=n?`"${e}"`:e.toString(),i=n?vE.STRING:vE.NUMBER,a=t===e?``:t;return{text:r,description:a,htmlContent:[{value:r,color:i}],fuzzySearchKey:r+a}})},selectProposal:UE});function QE(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.VALUE`&&t.argPosition>=2&&t.argPosition%2==1}function $E(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.HEADER`&&t.argPosition>=1&&t.argPosition%2==0}l_.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=ot(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 eD=new h;eD.add(`ALPHANUMERIC_INCREMENT_MODIFIER`,{apply:(e,t)=>{e.current+=e.increment;let n=`${e.prefix}${e.current.toString().padStart(e.numberPostfixLength||0,`0`)}`;return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:n},tooltip:{props:{content:n}}}}}).add(`INCREMENT_MODIFIER`,{apply:(e,t,n)=>{e.current+=e.increment;let r=e.current.toString(),i=n.getLocale(),a=B(e.current,{format:t.cell?.format,locale:i});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:a}}:void 0}}}).add(`DATE_INCREMENT_MODIFIER`,{apply:(e,t,n)=>{let r=R(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=di(r);e.current=i;let a=n.getLocale(),o=B(i,{format:t.cell?.format,locale:a});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:i.toString()},tooltip:i?{props:{content:o}}:void 0}}}).add(`COPY_MODIFIER`,{apply:(e,t,n)=>{let r=t.cell?.content||``,i={locale:n.getLocale(),format:t.cell?.format};return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:t.cell?hs(t.cell,i).formattedValue:``}}:void 0}}}).add(`FORMULA_MODIFIER`,{apply:(e,t,n,r)=>{e.current+=e.increment;let i=0,a=0;switch(r){case`up`:i=0,a=-e.current;break;case`down`:i=0,a=e.current;break;case`left`:i=-e.current,a=0;break;case`right`:i=e.current,a=0;break}let o=t.cell;if(!o||!o.isFormula)return{cellData:{}};let s=t.sheetId,c=n.getTranslatedCellFormula(s,i,a,o.compiledFormula.tokens);return{cellData:{border:t.border,style:o.style,format:o.format,content:c},tooltip:c?{props:{content:c}}:void 0}}});let tD=new h,nD=/(\d+)$/,rD=/^(.*\D+)/,iD=/^(.*\D+)(\d+)$/;function aD(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:hs(a,{locale:O,format:a.format});if(t&&n(t))r.push(t);else{if(i)return r;r=[]}}return r}function oD(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 sD(e){let t=1;return e.length>=2&&(t=oD(e)*e.length),t}function cD(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 lD(e){if(e.length<2)return 1;let t=e.map(e=>R(e,O)),n=cD(uD(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}}tD.add(`simple_value_copy`,{condition:(e,t)=>t.length===1&&!e.isFormula&&!(e.format&&Ko(e.format)),generateRule:()=>({type:`COPY_MODIFIER`}),sequence:10}).add(`increment_alphanumeric_value`,{condition:e=>!e.isFormula&&hs(e,{locale:O}).type===`text`&&iD.test(e.content),generateRule:(e,t,n)=>{let r=parseInt(e.content.match(nD)[0]),i=e.content.match(rD)[0],a=e.content.length-i.length,o=aD(e,t,e=>e.type===`text`&&iD.test(e.value)).filter(e=>i===(e.value??``).toString().match(rD)[0]).map(e=>parseInt((e.value??``).toString().match(nD)[0])),s=sD(o);return[`up`,`left`].includes(n)&&o.length===1&&(s=-s),{type:`ALPHANUMERIC_INCREMENT_MODIFIER`,prefix:i,current:r,increment:s,numberPostfixLength:a}},sequence:15}).add(`copy_text`,{condition:e=>!e.isFormula&&hs(e,{locale:O}).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&&hs(e,{locale:O}).type===`number`&&!!e.format&&Ko(e.format),generateRule:(e,t)=>{let n=lD(aD(e,t,e=>e.type===`number`&&!!e.format&&Ko(e.format)).map(e=>Number(e.value)));if(n===void 0)return{type:`COPY_MODIFIER`};let r=hs(e,{locale:O});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&&hs(e,{locale:O}).type===`number`,generateRule:(e,t,n)=>{let r=aD(e,t,e=>e.type===`number`&&!Ko(e.format||``)).map(e=>Number(e.value)),i=sD(r);[`up`,`left`].includes(n)&&r.length===1&&(i=-i);let a=hs(e,{locale:O});return{type:`INCREMENT_MODIFIER`,increment:i,current:a.type===`number`?a.value:0}},sequence:40});function uD(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=D.fromTimestamp(e[n-1].getTime()),i=yi(r,t),a=_i(r,t)%12;return r.setFullYear(r.getFullYear()+i),r.setMonth(r.getMonth()+a),{years:i,months:a,days:vi(r,t)}}).slice(1)}let dD=new h;var fD=class extends t.Component{static template=`o-spreadsheet-GaugeChartComponent`;canvas=(0,t.useRef)(`chartContainer`);get runtime(){return this.env.model.getters.getChartRuntime(this.props.figure.id)}setup(){(0,t.useEffect)(()=>gg(this.canvas.el,this.runtime),()=>{let e=this.canvas.el.getBoundingClientRect();return[e.width,e.height,this.runtime,this.canvas.el,window.devicePixelRatio]})}};fD.props={figure:Object};function pD(e){return e=en(e).replace(`#`,``),e.length===8?e.slice(6)+e.slice(0,6):e}var mD=class e extends jg{dataSets;labelRange;background;legendPosition;stacked;aggregated;type=`bar`;dataSetsHaveTitle;dataSetDesign;axesDesign;horizontal;showValues;constructor(e,t,n){super(e,t,n),this.dataSets=Cd(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ks(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.axesDesign=e.axesDesign,this.horizontal=e.horizontal,this.showValues=e.showValues}static transformDefinition(e,t){return Dd(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,kd,Ad)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,stacked:e.stacked??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`bar`,labelRange:e.auxiliaryRange||void 0,axesDesign:e.axesDesign,showValues:e.showValues}}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}}copyForSheetId(t){let n=bd(this.sheetId,t,this.dataSets),r=xd(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:`bar`,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,axesDesign:this.axesDesign,horizontal:this.horizontal,showValues:this.showValues}}getDefinitionForExcel(){let e=this.dataSets.map(e=>Td(this.getters,e)).filter(e=>e.range!==``&&e.range!==A.InvalidReference),t=Ed(this.getters,this.labelRange,jd(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),n=this.getDefinition();return{...n,backgroundColor:pD(this.background||`#FFFFFF`),fontColor:pD(Od(this.background)),dataSets:e,labelRange:t,verticalAxis:Pd(n)}}updateRanges(t){let{dataSets:n,labelRange:r,isStale:i}=yd(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function hD(e,t){let n=$g(t,e.dataSets,e.labelRange).formattedValues,r=t_(t,e.dataSets);jd(e.labelRange,e.dataSets[0],e.dataSetsHaveTitle)&&n.shift(),{labels:n,dataSetsValues:r}=Jg(n,r),e.aggregated&&({labels:n,dataSetsValues:r}=Yg(n,r));let i={format:e_(t,e.dataSets),locale:t.getLocale()},a=Od(e.background),o=Zg(e,n,a,{...i,horizontalChart:e.horizontal}),s=a_(a);e.legendPosition===`none`?s.display=!1:s.position=e.legendPosition,o.options.plugins.legend={...o.options.plugins?.legend,...s},o.options.layout={padding:Fd({displayTitle:!!e.title.text,displayLegend:e.legendPosition===`top`})},o.options.indexAxis=e.horizontal?`y`:`x`,o.options.scales={};let c={ticks:{padding:5,color:a}},l={beginAtZero:!0,ticks:{color:a,callback:Bd(i)}},u=e.horizontal?l:c,d=e.horizontal?c:l,{useLeftAxis:f,useRightAxis:p}=Pd(e.getDefinition());o.options.scales.x={...u,title:Nd(e.axesDesign?.x)},f&&(o.options.scales.y={...d,position:`left`,title:Nd(e.axesDesign?.y)}),p&&(o.options.scales.y1={...d,position:`right`,title:Nd(e.axesDesign?.y1)}),e.stacked&&(o.options.scales.x.stacked=!0,f&&(o.options.scales.y.stacked=!0),p&&(o.options.scales.y1.stacked=!0)),o.options.plugins.chartShowValuesPlugin={showValues:e.showValues,background:e.background,horizontal:e.horizontal,callback:Bd(i)};let m=e.getDefinition(),h=Vd(m,r.length),g=[];for(let t in r){let{label:n,data:i,hidden:a}=r[t],s=h.next(),c={label:n,data:i,hidden:a,borderColor:m.background||`#FFFFFF`,borderWidth:+!!m.stacked,backgroundColor:s};o.data.datasets.push(c),m.dataSets?.[t]?.label&&(c.label=m.dataSets[t].label),m.dataSets?.[t]?.yAxisId&&!e.horizontal&&(c.yAxisID=m.dataSets[t].yAxisId);let l=m.dataSets?.[t].trend;if(!l?.display||e.horizontal)continue;let u=Id(l,c);u&&g.push(u)}if(g.length){let e=Math.max(...g.map(e=>e.data.length));o.options.scales.x1={...u,labels:Array(e).fill(``),offset:!1,display:!1},g.forEach(e=>o.data.datasets.push(e)),o.options.plugins.tooltip.callbacks.title=function(e){return e.some(e=>e.dataset.xAxisID!==`x1`)?void 0:``}}return{chartJsConfig:o,background:e.background||`#FFFFFF`}}let gD={second:1e3,minute:1e3*60,hour:1e3*3600,day:1e3*3600*24,month:1e3*3600*24*30,year:1e3*3600*24*365},_D={inSeconds:function(e){return Math.floor(e/gD.second)},inMinutes:function(e){return Math.floor(e/gD.minute)},inHours:function(e){return Math.floor(e/gD.hour)},inDays:function(e){return Math.floor(e/gD.day)},inMonths:function(e){return Math.floor(e/gD.month)},inYears:function(e){return Math.floor(e/gD.year)}},vD=/^((d|dd|m|mm|yyyy|yy|hh|h|ss|a)(-|:|\s|\/))*(d|dd|m|mm|yyyy|yy|hh|h|ss|a)$/i;function yD(e,t,n){let r=bD(t),i=SD(e,r,n),a={};return i&&(a[i]=r),{parser:r,displayFormats:a,unit:i??!1,tooltipFormat:r}}function bD(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 xD(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 SD(e,t,n){let r=e.map(e=>$r(e,n)?.jsDate);if(r.some(e=>e===void 0)||e.length<2)return;let i=r.map(e=>e.getTime()),a=Gt(i)-Kt(i),o=xD(t);return gD.second>=gD[o]&&_D.inSeconds(a)<180?`second`:gD.minute>=gD[o]&&_D.inMinutes(a)<180?`minute`:gD.hour>=gD[o]&&_D.inHours(a)<96?`hour`:gD.day>=gD[o]&&_D.inDays(a)<90?`day`:gD.month>=gD[o]&&_D.inMonths(a)<36?`month`:`year`}function CD(e,t){if(e.length===0||e.every(e=>!e))return{labels:e,dataSetsValues:t};let n=[...e],r=y(t);for(let e=0;e<n.length;e++)if(!n[e]){n[e]=Dt(n,e);for(let t of r)t.data[e]=void 0}return{labels:n,dataSetsValues:r}}function wD(e,t){return OD(e,t)||kD(e,t)}function TD(e,t){return ED(e,t)&&jD()?`time`:DD(e,t)?`linear`:`category`}function ED(e,t){return!e.labelsAsText&&OD(e,t)}function DD(e,t){return!e.labelsAsText&&kD(e,t)}function OD(e,t){if(!e.labelRange||!kD(e,t))return!1;let n=Qg(t,e.labelRange,jd(e.labelRange,e.dataSets[0],e.dataSetsHaveTitle));return!!(n&&vD.test(n))}function kD(e,t){if(!e.labelRange)return!1;let n=t.getRangeValues(e.labelRange);return jd(e.labelRange,e.dataSets[0],e.dataSetsHaveTitle)&&n.shift(),!(n.some(e=>isNaN(Number(e))&&e)||n.every(e=>!e))}let AD=!1;function jD(){let e=o_();if(!e)return!1;let t=new e._adapters._date({})._id===`luxon`;return!t&&!AD&&(AD=!0,console.warn(`'chartjs-adapter-luxon' time adapter is not installed. Time scale axes are disabled.`)),t}function MD(e,t,n,r){let i=[],a=[],o=[],s=t.data.length;if(t.hidden||s<2)return;switch(n){case`category`:for(let e=0;e<s;e++)typeof t.data[e]==`number`&&(i.push(t.data[e]),a.push(e+1)),o.push(e+1);break;case`linear`:for(let e of t.data){let t=Number(e.x);isNaN(t)||(typeof e.y==`number`&&(i.push(e.y),a.push(t)),o.push(t))}break;case`time`:for(let e of t.data){let t=P({value:e.x},r);e.y!==null&&(i.push(e.y),a.push(t)),o.push(t)}break}let c=Math.min(...o),l=Math.max(...o);if(l===c)return;let u=5*o.length,d=(l-c)/u,f=x(c,l+d/2,d),p=Rd(e,i,a,f);if(p.length)return Ld(t,e,p,f)}function ND(e,t){let n=TD(e,t),r=$g(t,e.dataSets,e.labelRange),i=n===`linear`?r.values:r.formattedValues,a=t_(t,e.dataSets),o=jd(e.labelRange,e.dataSets[0],e.dataSetsHaveTitle);o&&i.shift(),{labels:i,dataSetsValues:a}=Jg(i,a),n===`time`&&({labels:i,dataSetsValues:a}=CD(i,a)),e.aggregated&&({labels:i,dataSetsValues:a}=Yg(i,a));let s=t.getLocale(),c=n===`category`,l=e_(t,e.dataSets),u={format:l,locale:s,truncateLabels:c},d=Od(e.background),f=Zg(e,i,d,u),p=a_(d,{labels:{generateLabels(e){let{data:t}=e,n=o_().defaults.plugins.legend.labels.generateLabels(e);for(let[e,r]of n.entries())r.fillStyle=t.datasets[e].borderColor;return n}}});e.legendPosition===`none`?p.display=!1:p.position=e.legendPosition,Object.assign(f.options.plugins.legend||{},p),f.options.layout={padding:Fd({displayTitle:!!e.title.text,displayLegend:e.legendPosition===`top`})};let m={ticks:{padding:5,color:d},title:Nd(e.axesDesign?.x)};f.options.scales={x:m};let h={beginAtZero:!0,ticks:{color:d,callback:Bd(u)}},{useLeftAxis:g,useRightAxis:_}=Pd(e.getDefinition());g&&(f.options.scales.y={...h,position:`left`,title:Nd(e.axesDesign?.y)}),_&&(f.options.scales.y1={...h,position:`right`,title:Nd(e.axesDesign?.y1)}),`stacked`in e&&e.stacked&&(g&&(f.options.scales.y.stacked=!0),_&&(f.options.scales.y1.stacked=!0)),f.options.plugins.chartShowValuesPlugin={showValues:e.showValues,background:e.background,callback:Bd(u)};let v=Qg(t,e.labelRange,o);if(n===`time`){let e={type:`time`,time:yD(i,v,s)};Object.assign(f.options.scales.x,e),f.options.scales.x.ticks.maxTicksLimit=15}else n===`linear`&&(f.options.scales.x.type=`linear`,f.options.scales.x.ticks.callback=e=>B(e,{format:v,locale:s}),f.options.plugins.tooltip.callbacks.label=e=>{let t,n;e.dataset.xAxisID===`x1`?(t=a[e.datasetIndex].data[e.dataIndex].y,n=``):(t=a[e.datasetIndex].data[e.dataIndex],n=r.values[e.dataIndex]),ki(n,s)&&(n=P(n,s));let i=B(n,{locale:s,format:v}),o=B(t,{locale:s,format:l}),c=e.dataset.label;return i?`${c}: (${i}, ${o})`:`${c}: ${o}`});let ee=`fillArea`in e?e.fillArea:!1,te=`stacked`in e?e.stacked:!1,ne=`cumulative`in e?e.cumulative:!1,re=e.getDefinition(),ie=Vd(re,a.length);for(let[e,{label:t,data:r,hidden:o}]of a.entries()){let a=ie.next(),s=ln(a);if(ee&&(s.a=.4),ne){let e=0;r=r.map(t=>isNaN(t)?t:(e+=parseFloat(t),e))}[`linear`,`time`].includes(n)&&(r=r.map((e,t)=>({x:i[t]||void 0,y:e})));let c=cn(s),l={label:t,data:r,hidden:o,tension:0,borderColor:a,backgroundColor:c,pointBackgroundColor:a,fill:ee?n_(e,te):!1};f.data.datasets.push(l)}let ae=0,oe=[];for(let[e,t]of f.data.datasets.entries()){re.dataSets?.[e]?.label&&(t.label=re.dataSets[e].label),re.dataSets?.[e]?.yAxisId&&(t.yAxisID=re.dataSets[e].yAxisId);let r=re.dataSets?.[e].trend;if(!r?.display)continue;let i=MD(r,t,n,s);i&&(ae=Math.max(ae,i.data.length),oe.push(i),a.push(i))}return oe.length&&(f.options.scales.x1={...m,display:!1},(n===`category`||n===`time`)&&(f.options.scales.x1.type=`category`,f.options.scales.x1.labels=x(0,ae).map(e=>e.toString()),f.options.scales.x1.offset=!1),oe.forEach(e=>f.data.datasets.push(e))),f.options.plugins.tooltip.callbacks.title=function(e){return n!==`linear`&&e.some(e=>e.dataset.xAxisID!==`x1`)?void 0:``},{chartJsConfig:f,background:e.background||`#FFFFFF`}}var PD=class e extends jg{dataSets;labelRange;background;legendPosition;aggregated;dataSetsHaveTitle;dataSetDesign;axesDesign;type=`combo`;showValues;constructor(e,t,n){super(e,t,n),this.dataSets=Cd(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ks(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){return Dd(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,kd,Ad)}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}}getDefinitionForExcel(){let e=this.dataSets.map(e=>Td(this.getters,e)).filter(e=>e.range!==``&&e.range!==A.InvalidReference),t=Ed(this.getters,this.labelRange,jd(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),n=this.getDefinition();return{...n,backgroundColor:pD(this.background||`#FFFFFF`),fontColor:pD(Od(this.background)),dataSets:e,labelRange:t,verticalAxis:Pd(n)}}updateRanges(t){let{dataSets:n,labelRange:r,isStale:i}=yd(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}}copyForSheetId(t){let n=bd(this.sheetId,t,this.dataSets),r=xd(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 FD(e,t){let n=e.dataSets.length?e_(t,[e.dataSets[0]]):void 0,r=e_(t,e.dataSets.slice(1)),i=t.getLocale(),a=$g(t,e.dataSets,e.labelRange).formattedValues,o=t_(t,e.dataSets);jd(e.labelRange,e.dataSets[0],e.dataSetsHaveTitle)&&a.shift(),{labels:a,dataSetsValues:o}=Jg(a,o),e.aggregated&&({labels:a,dataSetsValues:o}=Yg(a,o));let s={format:n,locale:i},c=Od(e.background),l=Zg(e,a,c,s),u=a_(c);e.legendPosition===`none`?u.display=!1:u.position=e.legendPosition,l.options.plugins.legend={...l.options.plugins?.legend,...u},l.options.layout={padding:Fd({displayTitle:!!e.title.text,displayLegend:e.legendPosition===`top`})},l.options.scales={x:{ticks:{padding:5,color:c},title:Nd(e.axesDesign?.x)}};let d={beginAtZero:!0,ticks:{color:c,callback:Bd({format:n,locale:i})}},f={beginAtZero:!0,ticks:{color:c,callback:Bd({format:r,locale:i})}},p=e.getDefinition(),{useLeftAxis:m,useRightAxis:h}=Pd(p);m&&(l.options.scales.y={...d,position:`left`,title:Nd(e.axesDesign?.y)}),h&&(l.options.scales.y1={...f,position:`right`,grid:{display:!1},title:Nd(e.axesDesign?.y1)}),l.options.plugins.chartShowValuesPlugin={showValues:e.showValues,background:e.background,callback:Bd({format:n,locale:i})};let g=Vd(p,o.length),_=0,v=[];for(let[e,{label:t,data:n,hidden:r}]of o.entries()){let i=p.dataSets[e],a=g.next(),s=i?.type??`line`,c={label:i?.label??t,data:n,hidden:r,borderColor:a,backgroundColor:a,yAxisID:i?.yAxisId??`y`,type:s,order:s===`bar`?o.length+e:e};l.data.datasets.push(c);let u=p.dataSets?.[e].trend;if(!u?.display)continue;_=Math.max(_,n.length);let d=Id(u,c);d&&v.push(d)}if(v.length){let e=Math.max(...v.map(e=>e.data.length));l.options.scales.x1={labels:Array(Math.round(e)).fill(``),offset:!1,display:!1},v.forEach(e=>l.data.datasets.push(e)),l.options.plugins.tooltip.callbacks.title=function(e){return e.some(e=>e.dataset.xAxisID!==`x1`)?void 0:``}}return{chartJsConfig:l,background:e.background||`#FFFFFF`}}function ID(e){return e.dataRange&&!Is.test(e.dataRange)?`InvalidGaugeDataRange`:`Success`}function LD(e,t){return t(t=>t.sectionRule?e(t.sectionRule.rangeMin,`rangeMin`):`Success`,t=>t.sectionRule?e(t.sectionRule.rangeMax,`rangeMax`):`Success`)}function RD(e,t){return t(t=>t.sectionRule?e(t.sectionRule.lowerInflectionPoint.value,`lowerInflectionPointValue`):`Success`,t=>t.sectionRule?e(t.sectionRule.upperInflectionPoint.value,`upperInflectionPointValue`):`Success`)}function zD(e){return e.sectionRule&&Number(e.sectionRule.rangeMin)>=Number(e.sectionRule.rangeMax)?`GaugeRangeMinBiggerThanRangeMax`:`Success`}function BD(e,t){if(e===``)switch(t){case`rangeMin`:return`EmptyGaugeRangeMin`;case`rangeMax`:return`EmptyGaugeRangeMax`}return`Success`}function VD(e,t){if(isNaN(e))switch(t){case`rangeMin`:return`GaugeRangeMinNaN`;case`rangeMax`:return`GaugeRangeMaxNaN`;case`lowerInflectionPointValue`:return`GaugeLowerInflectionPointNaN`;case`upperInflectionPointValue`:return`GaugeUpperInflectionPointNaN`}return`Success`}var HD=class e extends jg{dataRange;sectionRule;background;type=`gauge`;constructor(e,t,n){super(e,t,n),this.dataRange=Ks(this.getters,this.sheetId,e.dataRange),this.sectionRule=e.sectionRule,this.background=e.background}static validateChartDefinition(e,t){return e.checkValidations(t,ID,e.chainValidations(LD(BD,e.batchValidations),LD(VD,e.batchValidations),zD),e.chainValidations(RD(VD,e.batchValidations)))}static transformDefinition(e,t){let n;return e.dataRange&&(n=nd(Qn(e.dataRange),t)),{...e,dataRange:n?nr(n):void 0}}static getDefinitionFromContextCreation(e){return{background:e.background,title:e.title||{text:``},type:`gauge`,dataRange:e.range?.[0]?.dataRange,sectionRule:{colors:{lowerColor:`#EA6175`,middleColor:`#FFD86D`,upperColor:`#43C5B1`},rangeMin:`0`,rangeMax:`100`,lowerInflectionPoint:{type:`percentage`,value:`15`,operator:`<=`},upperInflectionPoint:{type:`percentage`,value:`40`,operator:`<=`}}}}copyForSheetId(t){let n=xd(this.sheetId,t,this.dataRange);return new e(this.getDefinitionWithSpecificRanges(n,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificRanges(this.dataRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificRanges(this.dataRange)}getDefinitionWithSpecificRanges(e,t){return{background:this.background,sectionRule:this.sectionRule,title:this.title,type:`gauge`,dataRange:e?this.getters.getRangeString(e,t||this.sheetId):void 0}}getDefinitionForExcel(){}getContextCreation(){return{...this,range:this.dataRange?[{dataRange:this.getters.getRangeString(this.dataRange,this.sheetId)}]:void 0}}updateRanges(t){let n=Sd(this.dataRange,t);return this.dataRange===n?this:new e(this.getDefinitionWithSpecificRanges(n),this.sheetId,this.getters)}};function UD(e,t){let n=t.getLocale(),r=e.sectionRule.colors,i,a,o,s=e.dataRange;if(s!==void 0){let e=t.getEvaluatedCell({sheetId:s.sheetId,col:s.zone.left,row:s.zone.top});e.type===`number`&&(i=e.value,a=e.formattedValue,o=e.format)}let c=Number(e.sectionRule.rangeMin),l=Number(e.sectionRule.rangeMax),u=e.sectionRule.lowerInflectionPoint,d=e.sectionRule.upperInflectionPoint,f=WD(u,c,l),p=WD(d,c,l),m=[],h=[];return f!==void 0&&(m.push({value:f,label:B(f,{locale:n,format:o}),operator:u.operator}),h.push(r.lowerColor)),p!==void 0&&p!==f&&(m.push({value:p,label:B(p,{locale:n,format:o}),operator:d.operator}),h.push(r.middleColor)),p!==void 0&&f!==void 0&&f>p&&(m.reverse(),h.reverse()),h.push(r.upperColor),{background:t.getStyleOfSingleCellChart(e.background,s).background,title:{...e.title,text:T(e.title.text??``)},minValue:{value:c,label:B(c,{locale:n,format:o})},maxValue:{value:l,label:B(l,{locale:n,format:o})},gaugeValue:i!==void 0&&a?{value:i,label:a}:void 0,inflectionValues:m,colors:h}}function WD(e,t,n){if(e.value===``||isNaN(Number(e.value)))return;let r=Number(e.value);return b(e.type===`number`?r:t+(n-t)*r/100,t,n)}var GD=class e extends jg{dataSets;labelRange;background;legendPosition;labelsAsText;stacked;aggregated;type=`line`;dataSetsHaveTitle;cumulative;dataSetDesign;axesDesign;fillArea;showValues;constructor(e,t,n){super(e,t,n),this.dataSets=Cd(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ks(this.getters,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.labelsAsText=e.labelsAsText,this.stacked=e.stacked,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.cumulative=e.cumulative,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.fillArea=e.fillArea,this.showValues=e.showValues}static validateChartDefinition(e,t){return e.checkValidations(t,kd,Ad)}static transformDefinition(e,t){return Dd(e,t)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,labelsAsText:e.labelsAsText??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`line`,labelRange:e.auxiliaryRange||void 0,stacked:e.stacked??!1,aggregated:e.aggregated??!1,cumulative:e.cumulative??!1,axesDesign:e.axesDesign,fillArea:e.fillArea,showValues:e.showValues}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`line`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,labelsAsText:this.labelsAsText,stacked:this.stacked,aggregated:this.aggregated,cumulative:this.cumulative,axesDesign:this.axesDesign,fillArea:this.fillArea,showValues:this.showValues}}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(t){let{dataSets:n,labelRange:r,isStale:i}=yd(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=>Td(this.getters,e)).filter(e=>e.range!==``&&e.range!==A.InvalidReference),t=Ed(this.getters,this.labelRange,jd(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),n=this.getDefinition();return{...n,backgroundColor:pD(this.background||`#FFFFFF`),fontColor:pD(Od(this.background)),dataSets:e,labelRange:t,verticalAxis:Pd(n)}}copyForSheetId(t){let n=bd(this.sheetId,t,this.dataSets),r=xd(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)}},KD=class e extends jg{dataSets;labelRange;background;legendPosition;type=`pie`;aggregated;dataSetsHaveTitle;isDoughnut;showValues;constructor(e,t,n){super(e,t,n),this.dataSets=Cd(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ks(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.isDoughnut=e.isDoughnut,this.showValues=e.showValues}static transformDefinition(e,t){return Dd(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,kd,Ad)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`pie`,labelRange:e.auxiliaryRange||void 0,aggregated:e.aggregated??!1,isDoughnut:!1,showValues:e.showValues}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getContextCreation(){return{...this,range:this.dataSets.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,this.sheetId)})),auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}getDefinitionWithSpecificDataSets(e,t,n){return{type:`pie`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,n||this.sheetId)})),legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,isDoughnut:this.isDoughnut,showValues:this.showValues}}copyForSheetId(t){let n=bd(this.sheetId,t,this.dataSets),r=xd(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinitionForExcel(){let e=this.dataSets.map(e=>Td(this.getters,e)).filter(e=>e.range!==``&&e.range!==A.InvalidReference),t=Ed(this.getters,this.labelRange,jd(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:pD(this.background||`#FFFFFF`),fontColor:pD(Od(this.background)),dataSets:e,labelRange:t}}updateRanges(t){let{dataSets:n,labelRange:r,isStale:i}=yd(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function qD(e,t,n){let r=Od(e.background),i=Zg(e,t,r,n),a={labels:{color:r}};return!e.labelRange&&e.dataSets.length===1||e.legendPosition===`none`?a.display=!1:a.position=e.legendPosition,Object.assign(i.options.plugins.legend||{},a),i.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},i.options.plugins.tooltip.callbacks.title=function(e){return e[0].dataset.label},i.options.plugins.tooltip.callbacks.label=function(e){let{format:t,locale:r}=n,i=e.dataset.data,a=e.dataIndex,o=YD(i,a),s=e.label||e.dataset.label,c=e.parsed.y??e.parsed,l=B(c,{format:!t&&c>=1e3?`#,##`:t,locale:r});return s?`${s}: ${l} (${o}%)`:`${l} (${o}%)`},i.options.plugins.chartShowValuesPlugin={showValues:e.showValues,callback:Bd(n)},i}function JD(e,t){let n=[],r=Gt(t.map(e=>e.data.length));for(let t=0;t<=r;t++)n.push(e.next());return n}function YD(e,t){let n=e.filter(e=>typeof e==`number`).reduce((e,t)=>e+t,0);return n?(e[t]/n*100).toFixed(2):``}function XD(e,t){let n=e.reduce((e,n,r)=>(t.some(e=>{let t=e.data[r];return typeof t!=`number`||t>=0})&&e.push(r),e),[]);return{labels:n.map(t=>e[t]||``),dataSetsValues:t.map(e=>({...e,data:n.map(t=>{let n=e.data[t];return typeof n!=`number`||n>=0?n:0})}))}}function ZD(e,t){let n=$g(t,e.dataSets,e.labelRange).formattedValues,r=t_(t,e.dataSets).filter(e=>!e.hidden);jd(e.labelRange,e.dataSets[0],e.dataSetsHaveTitle)&&n.shift(),{labels:n,dataSetsValues:r}=Jg(n,r),e.aggregated&&({labels:n,dataSetsValues:r}=Yg(n,r)),{dataSetsValues:r,labels:n}=XD(n,r);let i=e_(t,e.dataSets),a=t.getLocale(),o=qD(e,n,{format:i,locale:a}),s=JD(new wn(Math.max(0,...r.map(e=>e?.data?.length??0))),r);for(let{label:t,data:n}of r){let r={label:t,data:n,borderColor:e.background||`#FFFFFF`,backgroundColor:s,hoverOffset:30};o.data.datasets.push(r)}return e.isDoughnut&&(o.type=`doughnut`),{chartJsConfig:o,background:e.background||`#FFFFFF`}}var QD=class e extends jg{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=Cd(n,e.dataSets,t,e.dataSetsHaveTitle).slice(0,2),this.labelRange=Ks(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){return Dd(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,kd,Ad)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`pyramid`,labelRange:e.auxiliaryRange||void 0,axesDesign:e.axesDesign,horizontal:!0,stacked:!0,showValues:e.showValues}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}copyForSheetId(t){let n=bd(this.sheetId,t,this.dataSets),r=xd(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`pyramid`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,axesDesign:this.axesDesign,horizontal:!0,stacked:!0,showValues:this.showValues}}getDefinitionForExcel(){}updateRanges(t){let{dataSets:n,labelRange:r,isStale:i}=yd(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function $D(e,t){let n=hD(new mD({...e.getDefinition(),type:`bar`},e.sheetId,t),t).chartJsConfig,r=n.data?.datasets.filter(e=>!e.hidden);r&&r[0]&&(r[0].data=r[0].data.map(e=>e>0?e:0)),r&&r[1]&&(r[1].data=r[1].data.map(e=>e>0?-e:0));let i=Math.max(...n.data.datasets.map(e=>Math.max(...e.data.map(Math.abs)))),a=n.options.scales,o=a.x.ticks.callback;a.x.ticks.callback=e=>o(Math.abs(e)),a.x.suggestedMin=-i,a.x.suggestedMax=i;let s=n.options.plugins.tooltip.callbacks.label;n.options.plugins.tooltip.callbacks.label=e=>s({...e,parsed:{y:e.parsed.y,x:Math.abs(e.parsed.x)}});let c=n.options.plugins.chartShowValuesPlugin.callback;return n.options.plugins.chartShowValuesPlugin.callback=(e,t,n)=>c(Math.abs(e),t,n),{chartJsConfig:n,background:e.background||`#FFFFFF`}}var eO=class e extends jg{dataSets;labelRange;background;legendPosition;labelsAsText;aggregated;type=`scatter`;dataSetsHaveTitle;dataSetDesign;axesDesign;showValues;constructor(e,t,n){super(e,t,n),this.dataSets=Cd(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ks(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,kd,Ad)}static transformDefinition(e,t){return Dd(e,t)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,labelsAsText:e.labelsAsText??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`scatter`,labelRange:e.auxiliaryRange||void 0,aggregated:e.aggregated??!1,axesDesign:e.axesDesign,showValues:e.showValues}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`scatter`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,labelsAsText:this.labelsAsText,aggregated:this.aggregated,axesDesign:this.axesDesign,showValues:this.showValues}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}updateRanges(t){let{dataSets:n,labelRange:r,isStale:i}=yd(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=>Td(this.getters,e)).filter(e=>e.range!==``),t=Ed(this.getters,this.labelRange,jd(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),n=this.getDefinition();return{...n,backgroundColor:pD(this.background||`#FFFFFF`),fontColor:pD(Od(this.background)),dataSets:e,labelRange:t,verticalAxis:Pd(n)}}copyForSheetId(t){let n=bd(this.sheetId,t,this.dataSets),r=xd(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 tO(e,t){let{chartJsConfig:n,background:r}=ND(e,t);n.type=`line`;for(let e of n.data.datasets)e.showLine=`showLine`in e?e.showLine:!1;return{chartJsConfig:n,background:r}}var nO=class e extends jg{dataSets;labelRange;background;verticalAxisPosition;legendPosition;aggregated;type=`waterfall`;dataSetsHaveTitle;showSubTotals;firstValueAsSubtotal;showConnectorLines;positiveValuesColor;negativeValuesColor;subTotalValuesColor;dataSetDesign;axesDesign;showValues;constructor(e,t,n){super(e,t,n),this.dataSets=Cd(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ks(n,t,e.labelRange),this.background=e.background,this.verticalAxisPosition=e.verticalAxisPosition,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.showSubTotals=e.showSubTotals,this.showConnectorLines=e.showConnectorLines,this.positiveValuesColor=e.positiveValuesColor,this.negativeValuesColor=e.negativeValuesColor,this.subTotalValuesColor=e.subTotalValuesColor,this.firstValueAsSubtotal=e.firstValueAsSubtotal,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues}static transformDefinition(e,t){return Dd(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,kd,Ad)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range?e.range:[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`waterfall`,verticalAxisPosition:`left`,labelRange:e.auxiliaryRange||void 0,showSubTotals:e.showSubTotals??!1,showConnectorLines:e.showConnectorLines??!0,firstValueAsSubtotal:e.firstValueAsSubtotal??!1,axesDesign:e.axesDesign,showValues:e.showValues}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}copyForSheetId(t){let n=bd(this.sheetId,t,this.dataSets),r=xd(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`waterfall`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,verticalAxisPosition:this.verticalAxisPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,showSubTotals:this.showSubTotals,showConnectorLines:this.showConnectorLines,positiveValuesColor:this.positiveValuesColor,negativeValuesColor:this.negativeValuesColor,subTotalValuesColor:this.subTotalValuesColor,firstValueAsSubtotal:this.firstValueAsSubtotal,axesDesign:this.axesDesign,showValues:this.showValues}}getDefinitionForExcel(){}updateRanges(t){let{dataSets:n,labelRange:r,isStale:i}=yd(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function rO(e,t,n,r,i){let{locale:a,format:o}=r,s=Od(e.background),c=Zg(e,t,s,r),l=e.negativeValuesColor||`#EA6175`,u=e.positiveValuesColor||`#4EA7F2`,d=e.subTotalValuesColor||`#AAAAAA`,f={labels:{generateLabels:()=>{let t=[{text:T(`Positive values`),fontColor:s,fillStyle:u,strokeStyle:u},{text:T(`Negative values`),fontColor:s,fillStyle:l,strokeStyle:l}];return(e.showSubTotals||e.firstValueAsSubtotal)&&t.push({text:T(`Subtotals`),fontColor:s,fillStyle:d,strokeStyle:d}),t}}};e.legendPosition===`none`?f.display=!1:f.position=e.legendPosition,c.options.plugins.legend={...c.options.plugins?.legend,...f},c.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},c.options.scales={x:{ticks:{padding:5,color:s},grid:{display:!1},title:Nd(e.axesDesign?.x)},y:{position:e.verticalAxisPosition,ticks:{color:s,callback:e=>(e=Number(e),isNaN(e)?e:B(e,{locale:a,format:!o&&Math.abs(e)>1e3?`#,##`:o}))},grid:{lineWidth:e=>e.tick.value===0?2:1},title:Nd(e.axesDesign?.y)}},c.options.plugins.tooltip={callbacks:{label:function(e){let[r,i]=e.raw,s=i-r,c=n[Math.floor(e.dataIndex/t.length)],l=B(s,{format:!o&&Math.abs(s)>1e3?`#,##`:o,locale:a});return c?`${c}: ${l}`:l}}},c.options.plugins.waterfallLinesPlugin={showConnectorLines:e.showConnectorLines};let p=i.reduce((e,t)=>(e.push((e.at(-1)||-1)+t.data.length+1),e),[]);return c.options.plugins.chartShowValuesPlugin={showValues:e.showValues,background:e.background,callback:(t,n,i)=>{let a=n._dataset.data[i],o=a[1]-a[0],s=o>=0?`+`:``;return e.showSubTotals&&p.includes(i)&&s===`+`&&(s=``),`${s}${Bd(r)(o)}`}},c}function iO(e,t){let n=$g(t,e.dataSets,e.labelRange).formattedValues,r=t_(t,e.dataSets).filter(e=>!e.hidden);jd(e.labelRange,e.dataSets[0],e.dataSetsHaveTitle)&&n.shift(),{labels:n,dataSetsValues:r}=Jg(n,r),e.aggregated&&({labels:n,dataSetsValues:r}=Yg(n,r)),e.showSubTotals&&n.push(T(`Subtotal`));let i=e_(t,e.dataSets),a=t.getLocale(),o=r.map(e=>e.label),s=rO(e,n,o,{format:i,locale:a},r);s.type=`bar`;let c=e.negativeValuesColor||`#EA6175`,l=e.positiveValuesColor||`#4EA7F2`,u=e.subTotalValuesColor||`#AAAAAA`,d=[],f=[],p={label:``,data:f,backgroundColor:d},m=[],h=0;for(let t of r){for(let i=0;i<t.data.length;i++){let a=t.data[i];if(m.push(n[i]),isNaN(Number(a))){f.push([h,h]),d.push(``);continue}f.push([h,a+h]);let o=a>=0?l:c;i===0&&t===r[0]&&e.firstValueAsSubtotal&&(o=u),d.push(o),h+=a}e.showSubTotals&&(m.push(T(`Subtotal`)),f.push([0,h]),d.push(u))}return s.data.datasets.push(p),s.data.labels=m.map(Xg),{chartJsConfig:s,background:e.background||`#FFFFFF`}}let aO=new h;aO.add(`bar`,{match:e=>e===`bar`,createChart:(e,t,n)=>new mD(e,t,n),getChartRuntime:hD,validateChartDefinition:mD.validateChartDefinition,transformDefinition:mD.transformDefinition,getChartDefinitionFromContextCreation:mD.getDefinitionFromContextCreation,sequence:10}),aO.add(`combo`,{match:e=>e===`combo`,createChart:(e,t,n)=>new PD(e,t,n),getChartRuntime:FD,validateChartDefinition:PD.validateChartDefinition,transformDefinition:PD.transformDefinition,getChartDefinitionFromContextCreation:PD.getDefinitionFromContextCreation,sequence:15}),aO.add(`line`,{match:e=>e===`line`,createChart:(e,t,n)=>new GD(e,t,n),getChartRuntime:ND,validateChartDefinition:GD.validateChartDefinition,transformDefinition:GD.transformDefinition,getChartDefinitionFromContextCreation:GD.getDefinitionFromContextCreation,sequence:20}),aO.add(`pie`,{match:e=>e===`pie`,createChart:(e,t,n)=>new KD(e,t,n),getChartRuntime:ZD,validateChartDefinition:KD.validateChartDefinition,transformDefinition:KD.transformDefinition,getChartDefinitionFromContextCreation:KD.getDefinitionFromContextCreation,sequence:30}),aO.add(`scorecard`,{match:e=>e===`scorecard`,createChart:(e,t,n)=>new Bg(e,t,n),getChartRuntime:Hg,validateChartDefinition:Bg.validateChartDefinition,transformDefinition:Bg.transformDefinition,getChartDefinitionFromContextCreation:Bg.getDefinitionFromContextCreation,sequence:40}),aO.add(`gauge`,{match:e=>e===`gauge`,createChart:(e,t,n)=>new HD(e,t,n),getChartRuntime:UD,validateChartDefinition:HD.validateChartDefinition,transformDefinition:HD.transformDefinition,getChartDefinitionFromContextCreation:HD.getDefinitionFromContextCreation,sequence:50}),aO.add(`scatter`,{match:e=>e===`scatter`,createChart:(e,t,n)=>new eO(e,t,n),getChartRuntime:tO,validateChartDefinition:eO.validateChartDefinition,transformDefinition:eO.transformDefinition,getChartDefinitionFromContextCreation:eO.getDefinitionFromContextCreation,sequence:60}),aO.add(`waterfall`,{match:e=>e===`waterfall`,createChart:(e,t,n)=>new nO(e,t,n),getChartRuntime:iO,validateChartDefinition:nO.validateChartDefinition,transformDefinition:nO.transformDefinition,getChartDefinitionFromContextCreation:nO.getDefinitionFromContextCreation,sequence:70}),aO.add(`pyramid`,{match:e=>e===`pyramid`,createChart:(e,t,n)=>new QD(e,t,n),getChartRuntime:$D,validateChartDefinition:QD.validateChartDefinition,transformDefinition:QD.transformDefinition,getChartDefinitionFromContextCreation:QD.getDefinitionFromContextCreation,sequence:80});let oO=new h;oO.add(`line`,s_),oO.add(`bar`,s_),oO.add(`combo`,s_),oO.add(`pie`,s_),oO.add(`gauge`,fD),oO.add(`scatter`,s_),oO.add(`scorecard`,c_),oO.add(`waterfall`,s_),oO.add(`pyramid`,s_);let sO={line:T(`Line`),column:T(`Column`),bar:T(`Bar`),area:T(`Area`),pie:T(`Pie`),misc:T(`Miscellaneous`)},cO=new h;cO.add(`line`,{matcher:e=>e.type===`line`&&!e.stacked&&!e.fillArea,displayName:T(`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:T(`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:T(`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:T(`Stacked Area`),chartType:`line`,chartSubtype:`stacked_area`,subtypeDefinition:{stacked:!0,fillArea:!0},category:`area`,preview:`o-spreadsheet-ChartPreview.STACKED_AREA_CHART`}).add(`scatter`,{displayName:T(`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:T(`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:T(`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:T(`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:T(`Stacked Bar`),chartType:`bar`,chartSubtype:`stacked_bar`,subtypeDefinition:{horizontal:!0,stacked:!0},category:`bar`,preview:`o-spreadsheet-ChartPreview.STACKED_BAR_CHART`}).add(`combo`,{displayName:T(`Combo`),chartSubtype:`combo`,chartType:`combo`,category:`line`,preview:`o-spreadsheet-ChartPreview.COMBO_CHART`}).add(`pie`,{matcher:e=>e.type===`pie`&&!e.isDoughnut,displayName:T(`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:T(`Doughnut`),chartSubtype:`doughnut`,chartType:`pie`,subtypeDefinition:{isDoughnut:!0},category:`pie`,preview:`o-spreadsheet-ChartPreview.DOUGHNUT_CHART`}).add(`gauge`,{displayName:T(`Gauge`),chartSubtype:`gauge`,chartType:`gauge`,category:`misc`,preview:`o-spreadsheet-ChartPreview.GAUGE_CHART`}).add(`scorecard`,{displayName:T(`Scorecard`),chartSubtype:`scorecard`,chartType:`scorecard`,category:`misc`,preview:`o-spreadsheet-ChartPreview.SCORECARD_CHART`}).add(`waterfall`,{displayName:T(`Waterfall`),chartSubtype:`waterfall`,chartType:`waterfall`,category:`misc`,preview:`o-spreadsheet-ChartPreview.WATERFALL_CHART`}).add(`pyramid`,{displayName:T(`Population Pyramid`),chartSubtype:`pyramid`,chartType:`pyramid`,category:`misc`,preview:`o-spreadsheet-ChartPreview.POPULATION_PYRAMID_CHART`});let lO=new h;H`
|
|
170
|
+
`,e.endsWith(`{`)&&n++;return t.trim()}let TE=zT.content,EE={"=":`EQ`,"+":`ADD`,"-":`MINUS`,"*":`MULTIPLY`,"/":`DIVIDE`,">=":`GTE`,"<>":`NE`,">":`GT`,"<=":`LTE`,"<":`LT`,"^":`POWER`,"&":`CONCATENATE`},DE={"-":`UMINUS`,"+":`UPLUS`,"%":`UNARY.PERCENT`},OE={};function kE(e){return AE(Nh(e))}function AE(e){try{return jE(e)}catch(t){return{tokens:e,dependencies:[],execute:function(){return t},isBadExpression:!0}}}function jE(e){let{dependencies:t,literalValues:n,symbols:r}=NE(e),i=ME(e);if(!OE[i]){let t=gC([...e]),n=new SE,s=0,c=0,l=0;if(t.type===`BIN_OPERATION`&&t.value===`:`||t.type===`EMPTY`)throw new ra(T(`Invalid formula`));let u=o(t),d=new bE;d.append(u),d.append(`return ${u.returnExpression};`),OE[i]=Function(`deps`,`ref`,`range`,`getSymbolValue`,`ctx`,d.toString());function a(e){let{args:t}=e,n=TE[e.value.toUpperCase()];if(!n)throw new sa(T(`Unknown function: "%s"`,e.value));PE(e);let r=[];for(let e=0;e<t.length;e++){let i=n.getArgToFocus(e+1)-1,a=n.args[i],s=t[e],c=a.type||[],l=c.includes(`META`),u=c.some(e=>FE(e));r.push(o(s,l,u))}return r}function o(e,t=!1,i=!1){let u=new bE(n);if(e.type!==`REFERENCE`&&!(e.type===`BIN_OPERATION`&&e.value===`:`)&&t)throw new ra(T(`Argument must be a reference to a cell or range.`));switch(e.debug&&u.append(`debugger;`),e.type){case`BOOLEAN`:return u.return(`{ value: ${e.value} }`);case`NUMBER`:return u.return(`this.literalValues.numbers[${c++}]`);case`STRING`:return u.return(`this.literalValues.strings[${s++}]`);case`REFERENCE`:return!t&&e.value.includes(`:`)||i?u.return(`range(deps[${l++}])`):u.return(`ref(deps[${l++}], ${t?`true`:`false`})`);case`FUNCALL`:let n=a(e).map(e=>e.assignResultToVariable());u.append(...n);let d=e.value.toUpperCase();return u.return(`ctx['${d}'](${n.map(e=>e.returnExpression)})`);case`UNARY_OPERATION`:{let t=DE[e.value],n=o(e.operand,!1,!1).assignResultToVariable();return u.append(n),u.return(`ctx['${t}'](${n.returnExpression})`)}case`BIN_OPERATION`:{let t=EE[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:OE[i],dependencies:t,literalValues:n,symbols:r,tokens:e,isBadExpression:!1}}function ME(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 NE(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=et(i.value);t.strings.push({value:e});break;case`NUMBER`:{let e=ji(i.value,O);t.numbers.push({value:e});break}case`SYMBOL`:r.push(at(i.value,`'`))}return{dependencies:n,literalValues:t,symbols:r}}function PE(e){let t=e.args.length,n=e.value.toUpperCase(),r=TE[n];if(t<r.minArgRequired)throw new ra(T(`Invalid number of arguments for the %s function. Expected %s minimum, but got %s instead.`,n,r.minArgRequired.toString(),t.toString()));if(t>r.maxArgPossible)throw new ra(T(`Invalid number of arguments for the %s function. Expected %s maximum, but got %s instead.`,n,r.maxArgPossible.toString(),t.toString()));let i=r.nbrArgRepeating;if(i>1){let e=r.args.length-i;if((t-e)%i!==0)throw new ra(T(`Invalid number of arguments for the %s function. Expected all arguments after position %s to be supplied by groups of %s arguments`,n,e.toString(),i.toString()))}}function FE(e){return e.startsWith(`RANGE`)}let IE=zT.content;function LE(e){try{return vC(gC(e)).filter(e=>e.type===`FUNCALL`&&!IE[e.value.toUpperCase()]?.isExported).length===0}catch{return!1}}function RE(e,t){if(!e.some(e=>e.type===`SYMBOL`&&t.includes(e.value.toUpperCase())))return[];let n;try{n=gC(e)}catch{return[]}return zE(n,t)}function zE(e,t){return vC(e).filter(e=>e.type===`FUNCALL`&&t.includes(e.value.toUpperCase())).map(e=>({functionName:e.value.toUpperCase(),args:e.args}))}let BE=[`PIVOT.VALUE`,`PIVOT.HEADER`,`PIVOT`];function VE(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:vE.STRING}],fuzzySearchKey:r}}function HE(e){let t=`"${e.id}"`,n=e.displayName+e.fieldName+t;return{text:t,description:e.displayName,htmlContent:[{value:t,color:vE.STRING}],fuzzySearchKey:n}}function UE(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 WE(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 GE(e){let t=e.functionContext?.args[0];if(!(!t||![`STRING`,`NUMBER`].includes(t.type)))return t.value}function KE(e){return RE(e,BE)[0]}function qE(e){return RE(e,BE)}function JE(e){return RE(e,BE).length}let YE=new h;YE.add(`SPREADSHEET`,!1),l_.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:vE.NUMBER}],fuzzySearchKey:n+t.name}}).filter(S)},selectProposal:WE}),l_.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=GE(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:T(`Count`),htmlContent:[{value:e,color:vE.STRING}],fuzzySearchKey:T(`Count`)+e}}return HE(e)}).filter(S):[]},selectProposal:UE}),l_.add(`pivot_group_fields`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||!XE(e)&&!ZE(e))return;let n=GE(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(S),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=YE.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(S);return h.map(e=>{let[t,n]=e.split(`:`),r=a[t];return r?VE(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:T(`%s (positional)`,t.string)+(t.help?` (${t.help})`:``),htmlContent:[{value:n,color:vE.STRING}],fuzzySearchKey:t.string+n}})).filter(S)},selectProposal:UE});function XE(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.VALUE`&&t.argPosition>=2&&t.argPosition%2==0}function ZE(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.HEADER`&&t.argPosition>=1&&t.argPosition%2==1}l_.add(`pivot_group_values`,{sequence:50,autoSelectFirstProposal:!0,getProposals(e){let t=e.functionContext;if(!t||!e||!QE(e)&&!$E(e))return;let n=GE(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(Mo).map((e,t)=>({text:`${t+1}`,fuzzySearchKey:e.toString(),description:e.toString(),htmlContent:[{value:`${t+1}`,color:vE.NUMBER}]})):s.granularity===`quarter_number`?[1,2,3,4].map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:T(`Quarter %s`,e),htmlContent:[{value:`${e}`,color:vE.NUMBER}]})):s.granularity===`day_of_month`?x(1,32).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:vE.NUMBER}]})):s.granularity===`iso_week_number`?x(0,54).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:vE.NUMBER}]})):s.granularity===`day_of_week`?x(1,8).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:vE.NUMBER}]})):s.granularity===`hour_number`?x(0,24).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:vE.NUMBER}]})):s.granularity===`minute_number`?x(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:vE.NUMBER}]})):s.granularity===`second_number`?x(0,60).map(e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:``,htmlContent:[{value:`${e}`,color:vE.NUMBER}]})):i.getPossibleFieldValues(s).map(({value:e,label:t})=>{let n=typeof e==`string`,r=n?`"${e}"`:e.toString(),i=n?vE.STRING:vE.NUMBER,a=t===e?``:t;return{text:r,description:a,htmlContent:[{value:r,color:i}],fuzzySearchKey:r+a}})},selectProposal:UE});function QE(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.VALUE`&&t.argPosition>=2&&t.argPosition%2==1}function $E(e){let t=e.functionContext;return t?.parent.toUpperCase()===`PIVOT.HEADER`&&t.argPosition>=1&&t.argPosition%2==0}l_.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=ot(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 eD=new h;eD.add(`ALPHANUMERIC_INCREMENT_MODIFIER`,{apply:(e,t)=>{e.current+=e.increment;let n=`${e.prefix}${e.current.toString().padStart(e.numberPostfixLength||0,`0`)}`;return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:n},tooltip:{props:{content:n}}}}}).add(`INCREMENT_MODIFIER`,{apply:(e,t,n)=>{e.current+=e.increment;let r=e.current.toString(),i=n.getLocale(),a=B(e.current,{format:t.cell?.format,locale:i});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:a}}:void 0}}}).add(`DATE_INCREMENT_MODIFIER`,{apply:(e,t,n)=>{let r=R(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=di(r);e.current=i;let a=n.getLocale(),o=B(i,{format:t.cell?.format,locale:a});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:i.toString()},tooltip:i?{props:{content:o}}:void 0}}}).add(`COPY_MODIFIER`,{apply:(e,t,n)=>{let r=t.cell?.content||``,i={locale:n.getLocale(),format:t.cell?.format};return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:t.cell?hs(t.cell,i).formattedValue:``}}:void 0}}}).add(`FORMULA_MODIFIER`,{apply:(e,t,n,r)=>{e.current+=e.increment;let i=0,a=0;switch(r){case`up`:i=0,a=-e.current;break;case`down`:i=0,a=e.current;break;case`left`:i=-e.current,a=0;break;case`right`:i=e.current,a=0;break}let o=t.cell;if(!o||!o.isFormula)return{cellData:{}};let s=t.sheetId,c=n.getTranslatedCellFormula(s,i,a,o.compiledFormula.tokens);return{cellData:{border:t.border,style:o.style,format:o.format,content:c},tooltip:c?{props:{content:c}}:void 0}}});let tD=new h,nD=/(\d+)$/,rD=/^(.*\D+)/,iD=/^(.*\D+)(\d+)$/;function aD(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:hs(a,{locale:O,format:a.format});if(t&&n(t))r.push(t);else{if(i)return r;r=[]}}return r}function oD(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 sD(e){let t=1;return e.length>=2&&(t=oD(e)*e.length),t}function cD(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 lD(e){if(e.length<2)return 1;let t=e.map(e=>R(e,O)),n=cD(uD(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}}tD.add(`simple_value_copy`,{condition:(e,t)=>t.length===1&&!e.isFormula&&!(e.format&&Ko(e.format)),generateRule:()=>({type:`COPY_MODIFIER`}),sequence:10}).add(`increment_alphanumeric_value`,{condition:e=>!e.isFormula&&hs(e,{locale:O}).type===`text`&&iD.test(e.content),generateRule:(e,t,n)=>{let r=parseInt(e.content.match(nD)[0]),i=e.content.match(rD)[0],a=e.content.length-i.length,o=aD(e,t,e=>e.type===`text`&&iD.test(e.value)).filter(e=>i===(e.value??``).toString().match(rD)[0]).map(e=>parseInt((e.value??``).toString().match(nD)[0])),s=sD(o);return[`up`,`left`].includes(n)&&o.length===1&&(s=-s),{type:`ALPHANUMERIC_INCREMENT_MODIFIER`,prefix:i,current:r,increment:s,numberPostfixLength:a}},sequence:15}).add(`copy_text`,{condition:e=>!e.isFormula&&hs(e,{locale:O}).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&&hs(e,{locale:O}).type===`number`&&!!e.format&&Ko(e.format),generateRule:(e,t)=>{let n=lD(aD(e,t,e=>e.type===`number`&&!!e.format&&Ko(e.format)).map(e=>Number(e.value)));if(n===void 0)return{type:`COPY_MODIFIER`};let r=hs(e,{locale:O});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&&hs(e,{locale:O}).type===`number`,generateRule:(e,t,n)=>{let r=aD(e,t,e=>e.type===`number`&&!Ko(e.format||``)).map(e=>Number(e.value)),i=sD(r);[`up`,`left`].includes(n)&&r.length===1&&(i=-i);let a=hs(e,{locale:O});return{type:`INCREMENT_MODIFIER`,increment:i,current:a.type===`number`?a.value:0}},sequence:40});function uD(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=D.fromTimestamp(e[n-1].getTime()),i=yi(r,t),a=_i(r,t)%12;return r.setFullYear(r.getFullYear()+i),r.setMonth(r.getMonth()+a),{years:i,months:a,days:vi(r,t)}}).slice(1)}let dD=new h;var fD=class extends t.Component{static template=`o-spreadsheet-GaugeChartComponent`;canvas=(0,t.useRef)(`chartContainer`);get runtime(){return this.env.model.getters.getChartRuntime(this.props.figure.id)}setup(){(0,t.useEffect)(()=>gg(this.canvas.el,this.runtime),()=>{let e=this.canvas.el.getBoundingClientRect();return[e.width,e.height,this.runtime,this.canvas.el,window.devicePixelRatio]})}};fD.props={figure:Object};function pD(e){return e=en(e).replace(`#`,``),e.length===8?e.slice(6)+e.slice(0,6):e}var mD=class e extends jg{dataSets;labelRange;background;legendPosition;stacked;aggregated;type=`bar`;dataSetsHaveTitle;dataSetDesign;axesDesign;horizontal;showValues;constructor(e,t,n){super(e,t,n),this.dataSets=Cd(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ks(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.axesDesign=e.axesDesign,this.horizontal=e.horizontal,this.showValues=e.showValues}static transformDefinition(e,t){return Dd(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,kd,Ad)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,stacked:e.stacked??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`bar`,labelRange:e.auxiliaryRange||void 0,axesDesign:e.axesDesign,showValues:e.showValues}}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}}copyForSheetId(t){let n=bd(this.sheetId,t,this.dataSets),r=xd(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:`bar`,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,axesDesign:this.axesDesign,horizontal:this.horizontal,showValues:this.showValues}}getDefinitionForExcel(){let e=this.dataSets.map(e=>Td(this.getters,e)).filter(e=>e.range!==``&&e.range!==A.InvalidReference),t=Ed(this.getters,this.labelRange,jd(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),n=this.getDefinition();return{...n,backgroundColor:pD(this.background||`#FFFFFF`),fontColor:pD(Od(this.background)),dataSets:e,labelRange:t,verticalAxis:Pd(n)}}updateRanges(t){let{dataSets:n,labelRange:r,isStale:i}=yd(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function hD(e,t){let n=$g(t,e.dataSets,e.labelRange).formattedValues,r=t_(t,e.dataSets);jd(e.labelRange,e.dataSets[0],e.dataSetsHaveTitle)&&n.shift(),{labels:n,dataSetsValues:r}=Jg(n,r),e.aggregated&&({labels:n,dataSetsValues:r}=Yg(n,r));let i={format:e_(t,e.dataSets),locale:t.getLocale()},a=Od(e.background),o=Zg(e,n,a,{...i,horizontalChart:e.horizontal}),s=a_(a);e.legendPosition===`none`?s.display=!1:s.position=e.legendPosition,o.options.plugins.legend={...o.options.plugins?.legend,...s},o.options.layout={padding:Fd({displayTitle:!!e.title.text,displayLegend:e.legendPosition===`top`})},o.options.indexAxis=e.horizontal?`y`:`x`,o.options.scales={};let c={ticks:{padding:5,color:a}},l={beginAtZero:!0,ticks:{color:a,callback:Bd(i)}},u=e.horizontal?l:c,d=e.horizontal?c:l,{useLeftAxis:f,useRightAxis:p}=Pd(e.getDefinition());o.options.scales.x={...u,title:Nd(e.axesDesign?.x)},f&&(o.options.scales.y={...d,position:`left`,title:Nd(e.axesDesign?.y)}),p&&(o.options.scales.y1={...d,position:`right`,title:Nd(e.axesDesign?.y1)}),e.stacked&&(o.options.scales.x.stacked=!0,f&&(o.options.scales.y.stacked=!0),p&&(o.options.scales.y1.stacked=!0)),o.options.plugins.chartShowValuesPlugin={showValues:e.showValues,background:e.background,horizontal:e.horizontal,callback:Bd(i)};let m=e.getDefinition(),h=Vd(m,r.length),g=[];for(let t in r){let{label:n,data:i,hidden:a}=r[t],s=h.next(),c={label:n,data:i,hidden:a,borderColor:m.background||`#FFFFFF`,borderWidth:+!!m.stacked,backgroundColor:s};o.data.datasets.push(c),m.dataSets?.[t]?.label&&(c.label=m.dataSets[t].label),m.dataSets?.[t]?.yAxisId&&!e.horizontal&&(c.yAxisID=m.dataSets[t].yAxisId);let l=m.dataSets?.[t].trend;if(!l?.display||e.horizontal)continue;let u=Id(l,c);u&&g.push(u)}if(g.length){let e=Math.max(...g.map(e=>e.data.length));o.options.scales.x1={...u,labels:Array(e).fill(``),offset:!1,display:!1},g.forEach(e=>o.data.datasets.push(e)),o.options.plugins.tooltip.callbacks.title=function(e){return e.some(e=>e.dataset.xAxisID!==`x1`)?void 0:``}}return{chartJsConfig:o,background:e.background||`#FFFFFF`}}let gD={second:1e3,minute:1e3*60,hour:1e3*3600,day:1e3*3600*24,month:1e3*3600*24*30,year:1e3*3600*24*365},_D={inSeconds:function(e){return Math.floor(e/gD.second)},inMinutes:function(e){return Math.floor(e/gD.minute)},inHours:function(e){return Math.floor(e/gD.hour)},inDays:function(e){return Math.floor(e/gD.day)},inMonths:function(e){return Math.floor(e/gD.month)},inYears:function(e){return Math.floor(e/gD.year)}},vD=/^((d|dd|m|mm|yyyy|yy|hh|h|ss|a)(-|:|\s|\/))*(d|dd|m|mm|yyyy|yy|hh|h|ss|a)$/i;function yD(e,t,n){let r=bD(t),i=SD(e,r,n),a={};return i&&(a[i]=r),{parser:r,displayFormats:a,unit:i??!1,tooltipFormat:r}}function bD(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 xD(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 SD(e,t,n){let r=e.map(e=>$r(e,n)?.jsDate);if(r.some(e=>e===void 0)||e.length<2)return;let i=r.map(e=>e.getTime()),a=Gt(i)-Kt(i),o=xD(t);return gD.second>=gD[o]&&_D.inSeconds(a)<180?`second`:gD.minute>=gD[o]&&_D.inMinutes(a)<180?`minute`:gD.hour>=gD[o]&&_D.inHours(a)<96?`hour`:gD.day>=gD[o]&&_D.inDays(a)<90?`day`:gD.month>=gD[o]&&_D.inMonths(a)<36?`month`:`year`}function CD(e,t){if(e.length===0||e.every(e=>!e))return{labels:e,dataSetsValues:t};let n=[...e],r=y(t);for(let e=0;e<n.length;e++)if(!n[e]){n[e]=Dt(n,e);for(let t of r)t.data[e]=void 0}return{labels:n,dataSetsValues:r}}function wD(e,t){return OD(e,t)||kD(e,t)}function TD(e,t){return ED(e,t)&&jD()?`time`:DD(e,t)?`linear`:`category`}function ED(e,t){return!e.labelsAsText&&OD(e,t)}function DD(e,t){return!e.labelsAsText&&kD(e,t)}function OD(e,t){if(!e.labelRange||!kD(e,t))return!1;let n=Qg(t,e.labelRange,jd(e.labelRange,e.dataSets[0],e.dataSetsHaveTitle));return!!(n&&vD.test(n))}function kD(e,t){if(!e.labelRange)return!1;let n=t.getRangeValues(e.labelRange);return jd(e.labelRange,e.dataSets[0],e.dataSetsHaveTitle)&&n.shift(),!(n.some(e=>isNaN(Number(e))&&e)||n.every(e=>!e))}let AD=!1;function jD(){let e=o_();if(!e)return!1;let t=new e._adapters._date({})._id===`luxon`;return!t&&!AD&&(AD=!0,console.warn(`'chartjs-adapter-luxon' time adapter is not installed. Time scale axes are disabled.`)),t}function MD(e,t,n,r){let i=[],a=[],o=[],s=t.data.length;if(t.hidden||s<2)return;switch(n){case`category`:for(let e=0;e<s;e++)typeof t.data[e]==`number`&&(i.push(t.data[e]),a.push(e+1)),o.push(e+1);break;case`linear`:for(let e of t.data){let t=Number(e.x);isNaN(t)||(typeof e.y==`number`&&(i.push(e.y),a.push(t)),o.push(t))}break;case`time`:for(let e of t.data){let t=P({value:e.x},r);e.y!==null&&(i.push(e.y),a.push(t)),o.push(t)}break}let c=Math.min(...o),l=Math.max(...o);if(l===c)return;let u=5*o.length,d=(l-c)/u,f=x(c,l+d/2,d),p=Rd(e,i,a,f);if(p.length)return Ld(t,e,p,f)}function ND(e,t){let n=TD(e,t),r=$g(t,e.dataSets,e.labelRange),i=n===`linear`?r.values:r.formattedValues,a=t_(t,e.dataSets),o=jd(e.labelRange,e.dataSets[0],e.dataSetsHaveTitle);o&&i.shift(),{labels:i,dataSetsValues:a}=Jg(i,a),n===`time`&&({labels:i,dataSetsValues:a}=CD(i,a)),e.aggregated&&({labels:i,dataSetsValues:a}=Yg(i,a));let s=t.getLocale(),c=n===`category`,l=e_(t,e.dataSets),u={format:l,locale:s,truncateLabels:c},d=Od(e.background),f=Zg(e,i,d,u),p=a_(d,{labels:{generateLabels(e){let{data:t}=e,n=o_().defaults.plugins.legend.labels.generateLabels(e);for(let[e,r]of n.entries())r.fillStyle=t.datasets[e].borderColor;return n}}});e.legendPosition===`none`?p.display=!1:p.position=e.legendPosition,Object.assign(f.options.plugins.legend||{},p),f.options.layout={padding:Fd({displayTitle:!!e.title.text,displayLegend:e.legendPosition===`top`})};let m={ticks:{padding:5,color:d},title:Nd(e.axesDesign?.x)};f.options.scales={x:m};let h={beginAtZero:!0,ticks:{color:d,callback:Bd(u)}},{useLeftAxis:g,useRightAxis:_}=Pd(e.getDefinition());g&&(f.options.scales.y={...h,position:`left`,title:Nd(e.axesDesign?.y)}),_&&(f.options.scales.y1={...h,position:`right`,title:Nd(e.axesDesign?.y1)}),`stacked`in e&&e.stacked&&(g&&(f.options.scales.y.stacked=!0),_&&(f.options.scales.y1.stacked=!0)),f.options.plugins.chartShowValuesPlugin={showValues:e.showValues,background:e.background,callback:Bd(u)};let v=Qg(t,e.labelRange,o);if(n===`time`){let e={type:`time`,time:yD(i,v,s)};Object.assign(f.options.scales.x,e),f.options.scales.x.ticks.maxTicksLimit=15}else n===`linear`&&(f.options.scales.x.type=`linear`,f.options.scales.x.ticks.callback=e=>B(e,{format:v,locale:s}),f.options.plugins.tooltip.callbacks.label=e=>{let t,n;e.dataset.xAxisID===`x1`?(t=a[e.datasetIndex].data[e.dataIndex].y,n=``):(t=a[e.datasetIndex].data[e.dataIndex],n=r.values[e.dataIndex]),ki(n,s)&&(n=P(n,s));let i=B(n,{locale:s,format:v}),o=B(t,{locale:s,format:l}),c=e.dataset.label;return i?`${c}: (${i}, ${o})`:`${c}: ${o}`});let ee=`fillArea`in e?e.fillArea:!1,te=`stacked`in e?e.stacked:!1,ne=`cumulative`in e?e.cumulative:!1,re=e.getDefinition(),ie=Vd(re,a.length);for(let[e,{label:t,data:r,hidden:o}]of a.entries()){let a=ie.next(),s=ln(a);if(ee&&(s.a=.4),ne){let e=0;r=r.map(t=>isNaN(t)?t:(e+=parseFloat(t),e))}[`linear`,`time`].includes(n)&&(r=r.map((e,t)=>({x:i[t]||void 0,y:e})));let c=cn(s),l={label:t,data:r,hidden:o,tension:0,borderColor:a,backgroundColor:c,pointBackgroundColor:a,fill:ee?n_(e,te):!1};f.data.datasets.push(l)}let ae=0,oe=[];for(let[e,t]of f.data.datasets.entries()){re.dataSets?.[e]?.label&&(t.label=re.dataSets[e].label),re.dataSets?.[e]?.yAxisId&&(t.yAxisID=re.dataSets[e].yAxisId);let r=re.dataSets?.[e].trend;if(!r?.display)continue;let i=MD(r,t,n,s);i&&(ae=Math.max(ae,i.data.length),oe.push(i),a.push(i))}return oe.length&&(f.options.scales.x1={...m,display:!1},(n===`category`||n===`time`)&&(f.options.scales.x1.type=`category`,f.options.scales.x1.labels=x(0,ae).map(e=>e.toString()),f.options.scales.x1.offset=!1),oe.forEach(e=>f.data.datasets.push(e))),f.options.plugins.tooltip.callbacks.title=function(e){return n!==`linear`&&e.some(e=>e.dataset.xAxisID!==`x1`)?void 0:``},{chartJsConfig:f,background:e.background||`#FFFFFF`}}var PD=class e extends jg{dataSets;labelRange;background;legendPosition;aggregated;dataSetsHaveTitle;dataSetDesign;axesDesign;type=`combo`;showValues;constructor(e,t,n){super(e,t,n),this.dataSets=Cd(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ks(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){return Dd(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,kd,Ad)}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}}getDefinitionForExcel(){let e=this.dataSets.map(e=>Td(this.getters,e)).filter(e=>e.range!==``&&e.range!==A.InvalidReference),t=Ed(this.getters,this.labelRange,jd(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),n=this.getDefinition();return{...n,backgroundColor:pD(this.background||`#FFFFFF`),fontColor:pD(Od(this.background)),dataSets:e,labelRange:t,verticalAxis:Pd(n)}}updateRanges(t){let{dataSets:n,labelRange:r,isStale:i}=yd(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}}copyForSheetId(t){let n=bd(this.sheetId,t,this.dataSets),r=xd(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 FD(e,t){let n=e.dataSets.length?e_(t,[e.dataSets[0]]):void 0,r=e_(t,e.dataSets.slice(1)),i=t.getLocale(),a=$g(t,e.dataSets,e.labelRange).formattedValues,o=t_(t,e.dataSets);jd(e.labelRange,e.dataSets[0],e.dataSetsHaveTitle)&&a.shift(),{labels:a,dataSetsValues:o}=Jg(a,o),e.aggregated&&({labels:a,dataSetsValues:o}=Yg(a,o));let s={format:n,locale:i},c=Od(e.background),l=Zg(e,a,c,s);l.type=`bar`;let u=a_(c);e.legendPosition===`none`?u.display=!1:u.position=e.legendPosition,l.options.plugins.legend={...l.options.plugins?.legend,...u},l.options.layout={padding:Fd({displayTitle:!!e.title.text,displayLegend:e.legendPosition===`top`})},l.options.scales={x:{ticks:{padding:5,color:c},title:Nd(e.axesDesign?.x)}};let d={beginAtZero:!0,ticks:{color:c,callback:Bd({format:n,locale:i})}},f={beginAtZero:!0,ticks:{color:c,callback:Bd({format:r,locale:i})}},p=e.getDefinition(),{useLeftAxis:m,useRightAxis:h}=Pd(p);m&&(l.options.scales.y={...d,position:`left`,title:Nd(e.axesDesign?.y)}),h&&(l.options.scales.y1={...f,position:`right`,grid:{display:!1},title:Nd(e.axesDesign?.y1)}),l.options.plugins.chartShowValuesPlugin={showValues:e.showValues,background:e.background,callback:Bd({format:n,locale:i})};let g=Vd(p,o.length),_=0,v=[];for(let[e,{label:t,data:n,hidden:r}]of o.entries()){let i=p.dataSets[e],a=g.next(),s=i?.type??`line`,c={label:i?.label??t,data:n,hidden:r,borderColor:a,backgroundColor:a,yAxisID:i?.yAxisId??`y`,type:s,order:s===`bar`?o.length+e:e};l.data.datasets.push(c);let u=p.dataSets?.[e].trend;if(!u?.display)continue;_=Math.max(_,n.length);let d=Id(u,c);d&&v.push(d)}if(v.length){let e=Math.max(...v.map(e=>e.data.length));l.options.scales.x1={labels:Array(Math.round(e)).fill(``),offset:!1,display:!1},v.forEach(e=>l.data.datasets.push(e)),l.options.plugins.tooltip.callbacks.title=function(e){return e.some(e=>e.dataset.xAxisID!==`x1`)?void 0:``}}return{chartJsConfig:l,background:e.background||`#FFFFFF`}}function ID(e){return e.dataRange&&!Is.test(e.dataRange)?`InvalidGaugeDataRange`:`Success`}function LD(e,t){return t(t=>t.sectionRule?e(t.sectionRule.rangeMin,`rangeMin`):`Success`,t=>t.sectionRule?e(t.sectionRule.rangeMax,`rangeMax`):`Success`)}function RD(e,t){return t(t=>t.sectionRule?e(t.sectionRule.lowerInflectionPoint.value,`lowerInflectionPointValue`):`Success`,t=>t.sectionRule?e(t.sectionRule.upperInflectionPoint.value,`upperInflectionPointValue`):`Success`)}function zD(e){return e.sectionRule&&Number(e.sectionRule.rangeMin)>=Number(e.sectionRule.rangeMax)?`GaugeRangeMinBiggerThanRangeMax`:`Success`}function BD(e,t){if(e===``)switch(t){case`rangeMin`:return`EmptyGaugeRangeMin`;case`rangeMax`:return`EmptyGaugeRangeMax`}return`Success`}function VD(e,t){if(isNaN(e))switch(t){case`rangeMin`:return`GaugeRangeMinNaN`;case`rangeMax`:return`GaugeRangeMaxNaN`;case`lowerInflectionPointValue`:return`GaugeLowerInflectionPointNaN`;case`upperInflectionPointValue`:return`GaugeUpperInflectionPointNaN`}return`Success`}var HD=class e extends jg{dataRange;sectionRule;background;type=`gauge`;constructor(e,t,n){super(e,t,n),this.dataRange=Ks(this.getters,this.sheetId,e.dataRange),this.sectionRule=e.sectionRule,this.background=e.background}static validateChartDefinition(e,t){return e.checkValidations(t,ID,e.chainValidations(LD(BD,e.batchValidations),LD(VD,e.batchValidations),zD),e.chainValidations(RD(VD,e.batchValidations)))}static transformDefinition(e,t){let n;return e.dataRange&&(n=nd(Qn(e.dataRange),t)),{...e,dataRange:n?nr(n):void 0}}static getDefinitionFromContextCreation(e){return{background:e.background,title:e.title||{text:``},type:`gauge`,dataRange:e.range?.[0]?.dataRange,sectionRule:{colors:{lowerColor:`#EA6175`,middleColor:`#FFD86D`,upperColor:`#43C5B1`},rangeMin:`0`,rangeMax:`100`,lowerInflectionPoint:{type:`percentage`,value:`15`,operator:`<=`},upperInflectionPoint:{type:`percentage`,value:`40`,operator:`<=`}}}}copyForSheetId(t){let n=xd(this.sheetId,t,this.dataRange);return new e(this.getDefinitionWithSpecificRanges(n,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificRanges(this.dataRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificRanges(this.dataRange)}getDefinitionWithSpecificRanges(e,t){return{background:this.background,sectionRule:this.sectionRule,title:this.title,type:`gauge`,dataRange:e?this.getters.getRangeString(e,t||this.sheetId):void 0}}getDefinitionForExcel(){}getContextCreation(){return{...this,range:this.dataRange?[{dataRange:this.getters.getRangeString(this.dataRange,this.sheetId)}]:void 0}}updateRanges(t){let n=Sd(this.dataRange,t);return this.dataRange===n?this:new e(this.getDefinitionWithSpecificRanges(n),this.sheetId,this.getters)}};function UD(e,t){let n=t.getLocale(),r=e.sectionRule.colors,i,a,o,s=e.dataRange;if(s!==void 0){let e=t.getEvaluatedCell({sheetId:s.sheetId,col:s.zone.left,row:s.zone.top});e.type===`number`&&(i=e.value,a=e.formattedValue,o=e.format)}let c=Number(e.sectionRule.rangeMin),l=Number(e.sectionRule.rangeMax),u=e.sectionRule.lowerInflectionPoint,d=e.sectionRule.upperInflectionPoint,f=WD(u,c,l),p=WD(d,c,l),m=[],h=[];return f!==void 0&&(m.push({value:f,label:B(f,{locale:n,format:o}),operator:u.operator}),h.push(r.lowerColor)),p!==void 0&&p!==f&&(m.push({value:p,label:B(p,{locale:n,format:o}),operator:d.operator}),h.push(r.middleColor)),p!==void 0&&f!==void 0&&f>p&&(m.reverse(),h.reverse()),h.push(r.upperColor),{background:t.getStyleOfSingleCellChart(e.background,s).background,title:{...e.title,text:T(e.title.text??``)},minValue:{value:c,label:B(c,{locale:n,format:o})},maxValue:{value:l,label:B(l,{locale:n,format:o})},gaugeValue:i!==void 0&&a?{value:i,label:a}:void 0,inflectionValues:m,colors:h}}function WD(e,t,n){if(e.value===``||isNaN(Number(e.value)))return;let r=Number(e.value);return b(e.type===`number`?r:t+(n-t)*r/100,t,n)}var GD=class e extends jg{dataSets;labelRange;background;legendPosition;labelsAsText;stacked;aggregated;type=`line`;dataSetsHaveTitle;cumulative;dataSetDesign;axesDesign;fillArea;showValues;constructor(e,t,n){super(e,t,n),this.dataSets=Cd(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ks(this.getters,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.labelsAsText=e.labelsAsText,this.stacked=e.stacked,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.cumulative=e.cumulative,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.fillArea=e.fillArea,this.showValues=e.showValues}static validateChartDefinition(e,t){return e.checkValidations(t,kd,Ad)}static transformDefinition(e,t){return Dd(e,t)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,labelsAsText:e.labelsAsText??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`line`,labelRange:e.auxiliaryRange||void 0,stacked:e.stacked??!1,aggregated:e.aggregated??!1,cumulative:e.cumulative??!1,axesDesign:e.axesDesign,fillArea:e.fillArea,showValues:e.showValues}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`line`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,labelsAsText:this.labelsAsText,stacked:this.stacked,aggregated:this.aggregated,cumulative:this.cumulative,axesDesign:this.axesDesign,fillArea:this.fillArea,showValues:this.showValues}}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(t){let{dataSets:n,labelRange:r,isStale:i}=yd(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=>Td(this.getters,e)).filter(e=>e.range!==``&&e.range!==A.InvalidReference),t=Ed(this.getters,this.labelRange,jd(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),n=this.getDefinition();return{...n,backgroundColor:pD(this.background||`#FFFFFF`),fontColor:pD(Od(this.background)),dataSets:e,labelRange:t,verticalAxis:Pd(n)}}copyForSheetId(t){let n=bd(this.sheetId,t,this.dataSets),r=xd(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)}},KD=class e extends jg{dataSets;labelRange;background;legendPosition;type=`pie`;aggregated;dataSetsHaveTitle;isDoughnut;showValues;constructor(e,t,n){super(e,t,n),this.dataSets=Cd(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ks(n,t,e.labelRange),this.background=e.background,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.isDoughnut=e.isDoughnut,this.showValues=e.showValues}static transformDefinition(e,t){return Dd(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,kd,Ad)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`pie`,labelRange:e.auxiliaryRange||void 0,aggregated:e.aggregated??!1,isDoughnut:!1,showValues:e.showValues}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getContextCreation(){return{...this,range:this.dataSets.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,this.sheetId)})),auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}getDefinitionWithSpecificDataSets(e,t,n){return{type:`pie`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:e.map(e=>({dataRange:this.getters.getRangeString(e.dataRange,n||this.sheetId)})),legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,isDoughnut:this.isDoughnut,showValues:this.showValues}}copyForSheetId(t){let n=bd(this.sheetId,t,this.dataSets),r=xd(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinitionForExcel(){let e=this.dataSets.map(e=>Td(this.getters,e)).filter(e=>e.range!==``&&e.range!==A.InvalidReference),t=Ed(this.getters,this.labelRange,jd(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle));return{...this.getDefinition(),backgroundColor:pD(this.background||`#FFFFFF`),fontColor:pD(Od(this.background)),dataSets:e,labelRange:t}}updateRanges(t){let{dataSets:n,labelRange:r,isStale:i}=yd(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function qD(e,t,n){let r=Od(e.background),i=Zg(e,t,r,n),a={labels:{color:r}};return!e.labelRange&&e.dataSets.length===1||e.legendPosition===`none`?a.display=!1:a.position=e.legendPosition,Object.assign(i.options.plugins.legend||{},a),i.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},i.options.plugins.tooltip.callbacks.title=function(e){return e[0].dataset.label},i.options.plugins.tooltip.callbacks.label=function(e){let{format:t,locale:r}=n,i=e.dataset.data,a=e.dataIndex,o=YD(i,a),s=e.label||e.dataset.label,c=e.parsed.y??e.parsed,l=B(c,{format:!t&&c>=1e3?`#,##`:t,locale:r});return s?`${s}: ${l} (${o}%)`:`${l} (${o}%)`},i.options.plugins.chartShowValuesPlugin={showValues:e.showValues,callback:Bd(n)},i}function JD(e,t){let n=[],r=Gt(t.map(e=>e.data.length));for(let t=0;t<=r;t++)n.push(e.next());return n}function YD(e,t){let n=e.filter(e=>typeof e==`number`).reduce((e,t)=>e+t,0);return n?(e[t]/n*100).toFixed(2):``}function XD(e,t){let n=e.reduce((e,n,r)=>(t.some(e=>{let t=e.data[r];return typeof t!=`number`||t>=0})&&e.push(r),e),[]);return{labels:n.map(t=>e[t]||``),dataSetsValues:t.map(e=>({...e,data:n.map(t=>{let n=e.data[t];return typeof n!=`number`||n>=0?n:0})}))}}function ZD(e,t){let n=$g(t,e.dataSets,e.labelRange).formattedValues,r=t_(t,e.dataSets).filter(e=>!e.hidden);jd(e.labelRange,e.dataSets[0],e.dataSetsHaveTitle)&&n.shift(),{labels:n,dataSetsValues:r}=Jg(n,r),e.aggregated&&({labels:n,dataSetsValues:r}=Yg(n,r)),{dataSetsValues:r,labels:n}=XD(n,r);let i=e_(t,e.dataSets),a=t.getLocale(),o=qD(e,n,{format:i,locale:a}),s=JD(new wn(Math.max(0,...r.map(e=>e?.data?.length??0))),r);for(let{label:t,data:n}of r){let r={label:t,data:n,borderColor:e.background||`#FFFFFF`,backgroundColor:s,hoverOffset:30};o.data.datasets.push(r)}return e.isDoughnut&&(o.type=`doughnut`),{chartJsConfig:o,background:e.background||`#FFFFFF`}}var QD=class e extends jg{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=Cd(n,e.dataSets,t,e.dataSetsHaveTitle).slice(0,2),this.labelRange=Ks(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){return Dd(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,kd,Ad)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`pyramid`,labelRange:e.auxiliaryRange||void 0,axesDesign:e.axesDesign,horizontal:!0,stacked:!0,showValues:e.showValues}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}copyForSheetId(t){let n=bd(this.sheetId,t,this.dataSets),r=xd(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`pyramid`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,axesDesign:this.axesDesign,horizontal:!0,stacked:!0,showValues:this.showValues}}getDefinitionForExcel(){}updateRanges(t){let{dataSets:n,labelRange:r,isStale:i}=yd(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function $D(e,t){let n=hD(new mD({...e.getDefinition(),type:`bar`},e.sheetId,t),t).chartJsConfig,r=n.data?.datasets.filter(e=>!e.hidden);r&&r[0]&&(r[0].data=r[0].data.map(e=>e>0?e:0)),r&&r[1]&&(r[1].data=r[1].data.map(e=>e>0?-e:0));let i=Math.max(...n.data.datasets.map(e=>Math.max(...e.data.map(Math.abs)))),a=n.options.scales,o=a.x.ticks.callback;a.x.ticks.callback=e=>o(Math.abs(e)),a.x.suggestedMin=-i,a.x.suggestedMax=i;let s=n.options.plugins.tooltip.callbacks.label;n.options.plugins.tooltip.callbacks.label=e=>s({...e,parsed:{y:e.parsed.y,x:Math.abs(e.parsed.x)}});let c=n.options.plugins.chartShowValuesPlugin.callback;return n.options.plugins.chartShowValuesPlugin.callback=(e,t,n)=>c(Math.abs(e),t,n),{chartJsConfig:n,background:e.background||`#FFFFFF`}}var eO=class e extends jg{dataSets;labelRange;background;legendPosition;labelsAsText;aggregated;type=`scatter`;dataSetsHaveTitle;dataSetDesign;axesDesign;showValues;constructor(e,t,n){super(e,t,n),this.dataSets=Cd(this.getters,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ks(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,kd,Ad)}static transformDefinition(e,t){return Dd(e,t)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range??[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,labelsAsText:e.labelsAsText??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`scatter`,labelRange:e.auxiliaryRange||void 0,aggregated:e.aggregated??!1,axesDesign:e.axesDesign,showValues:e.showValues}}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`scatter`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,labelsAsText:this.labelsAsText,aggregated:this.aggregated,axesDesign:this.axesDesign,showValues:this.showValues}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}updateRanges(t){let{dataSets:n,labelRange:r,isStale:i}=yd(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=>Td(this.getters,e)).filter(e=>e.range!==``),t=Ed(this.getters,this.labelRange,jd(this.labelRange,this.dataSets[0],this.dataSetsHaveTitle)),n=this.getDefinition();return{...n,backgroundColor:pD(this.background||`#FFFFFF`),fontColor:pD(Od(this.background)),dataSets:e,labelRange:t,verticalAxis:Pd(n)}}copyForSheetId(t){let n=bd(this.sheetId,t,this.dataSets),r=xd(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 tO(e,t){let{chartJsConfig:n,background:r}=ND(e,t);n.type=`line`;for(let e of n.data.datasets)e.showLine=`showLine`in e?e.showLine:!1;return{chartJsConfig:n,background:r}}var nO=class e extends jg{dataSets;labelRange;background;verticalAxisPosition;legendPosition;aggregated;type=`waterfall`;dataSetsHaveTitle;showSubTotals;firstValueAsSubtotal;showConnectorLines;positiveValuesColor;negativeValuesColor;subTotalValuesColor;dataSetDesign;axesDesign;showValues;constructor(e,t,n){super(e,t,n),this.dataSets=Cd(n,e.dataSets,t,e.dataSetsHaveTitle),this.labelRange=Ks(n,t,e.labelRange),this.background=e.background,this.verticalAxisPosition=e.verticalAxisPosition,this.legendPosition=e.legendPosition,this.aggregated=e.aggregated,this.dataSetsHaveTitle=e.dataSetsHaveTitle,this.showSubTotals=e.showSubTotals,this.showConnectorLines=e.showConnectorLines,this.positiveValuesColor=e.positiveValuesColor,this.negativeValuesColor=e.negativeValuesColor,this.subTotalValuesColor=e.subTotalValuesColor,this.firstValueAsSubtotal=e.firstValueAsSubtotal,this.dataSetDesign=e.dataSets,this.axesDesign=e.axesDesign,this.showValues=e.showValues}static transformDefinition(e,t){return Dd(e,t)}static validateChartDefinition(e,t){return e.checkValidations(t,kd,Ad)}static getDefinitionFromContextCreation(e){return{background:e.background,dataSets:e.range?e.range:[],dataSetsHaveTitle:e.dataSetsHaveTitle??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`waterfall`,verticalAxisPosition:`left`,labelRange:e.auxiliaryRange||void 0,showSubTotals:e.showSubTotals??!1,showConnectorLines:e.showConnectorLines??!0,firstValueAsSubtotal:e.firstValueAsSubtotal??!1,axesDesign:e.axesDesign,showValues:e.showValues}}getContextCreation(){let e=[];for(let[t,n]of this.dataSets.entries())e.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(n.dataRange,this.sheetId)});return{...this,range:e,auxiliaryRange:this.labelRange?this.getters.getRangeString(this.labelRange,this.sheetId):void 0}}copyForSheetId(t){let n=bd(this.sheetId,t,this.dataSets),r=xd(this.sheetId,t,this.labelRange);return new e(this.getDefinitionWithSpecificDataSets(n,r,t),t,this.getters)}copyInSheetId(t){return new e(this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange,t),t,this.getters)}getDefinition(){return this.getDefinitionWithSpecificDataSets(this.dataSets,this.labelRange)}getDefinitionWithSpecificDataSets(e,t,n){let r=[];for(let[t,i]of e.entries())r.push({...this.dataSetDesign?.[t],dataRange:this.getters.getRangeString(i.dataRange,n||this.sheetId)});return{type:`waterfall`,dataSetsHaveTitle:e.length?!!e[0].labelCell:!1,background:this.background,dataSets:r,legendPosition:this.legendPosition,verticalAxisPosition:this.verticalAxisPosition,labelRange:t?this.getters.getRangeString(t,n||this.sheetId):void 0,title:this.title,aggregated:this.aggregated,showSubTotals:this.showSubTotals,showConnectorLines:this.showConnectorLines,positiveValuesColor:this.positiveValuesColor,negativeValuesColor:this.negativeValuesColor,subTotalValuesColor:this.subTotalValuesColor,firstValueAsSubtotal:this.firstValueAsSubtotal,axesDesign:this.axesDesign,showValues:this.showValues}}getDefinitionForExcel(){}updateRanges(t){let{dataSets:n,labelRange:r,isStale:i}=yd(this.getters,t,this.dataSets,this.labelRange);return i?new e(this.getDefinitionWithSpecificDataSets(n,r),this.sheetId,this.getters):this}};function rO(e,t,n,r,i){let{locale:a,format:o}=r,s=Od(e.background),c=Zg(e,t,s,r),l=e.negativeValuesColor||`#EA6175`,u=e.positiveValuesColor||`#4EA7F2`,d=e.subTotalValuesColor||`#AAAAAA`,f={labels:{generateLabels:()=>{let t=[{text:T(`Positive values`),fontColor:s,fillStyle:u,strokeStyle:u},{text:T(`Negative values`),fontColor:s,fillStyle:l,strokeStyle:l}];return(e.showSubTotals||e.firstValueAsSubtotal)&&t.push({text:T(`Subtotals`),fontColor:s,fillStyle:d,strokeStyle:d}),t}}};e.legendPosition===`none`?f.display=!1:f.position=e.legendPosition,c.options.plugins.legend={...c.options.plugins?.legend,...f},c.options.layout={padding:{left:20,right:20,top:e.title?10:25,bottom:10}},c.options.scales={x:{ticks:{padding:5,color:s},grid:{display:!1},title:Nd(e.axesDesign?.x)},y:{position:e.verticalAxisPosition,ticks:{color:s,callback:e=>(e=Number(e),isNaN(e)?e:B(e,{locale:a,format:!o&&Math.abs(e)>1e3?`#,##`:o}))},grid:{lineWidth:e=>e.tick.value===0?2:1},title:Nd(e.axesDesign?.y)}},c.options.plugins.tooltip={callbacks:{label:function(e){let[r,i]=e.raw,s=i-r,c=n[Math.floor(e.dataIndex/t.length)],l=B(s,{format:!o&&Math.abs(s)>1e3?`#,##`:o,locale:a});return c?`${c}: ${l}`:l}}},c.options.plugins.waterfallLinesPlugin={showConnectorLines:e.showConnectorLines};let p=i.reduce((e,t)=>(e.push((e.at(-1)||-1)+t.data.length+1),e),[]);return c.options.plugins.chartShowValuesPlugin={showValues:e.showValues,background:e.background,callback:(t,n,i)=>{let a=n._dataset.data[i],o=a[1]-a[0],s=o>=0?`+`:``;return e.showSubTotals&&p.includes(i)&&s===`+`&&(s=``),`${s}${Bd(r)(o)}`}},c}function iO(e,t){let n=$g(t,e.dataSets,e.labelRange).formattedValues,r=t_(t,e.dataSets).filter(e=>!e.hidden);jd(e.labelRange,e.dataSets[0],e.dataSetsHaveTitle)&&n.shift(),{labels:n,dataSetsValues:r}=Jg(n,r),e.aggregated&&({labels:n,dataSetsValues:r}=Yg(n,r)),e.showSubTotals&&n.push(T(`Subtotal`));let i=e_(t,e.dataSets),a=t.getLocale(),o=r.map(e=>e.label),s=rO(e,n,o,{format:i,locale:a},r);s.type=`bar`;let c=e.negativeValuesColor||`#EA6175`,l=e.positiveValuesColor||`#4EA7F2`,u=e.subTotalValuesColor||`#AAAAAA`,d=[],f=[],p={label:``,data:f,backgroundColor:d},m=[],h=0;for(let t of r){for(let i=0;i<t.data.length;i++){let a=t.data[i];if(m.push(n[i]),isNaN(Number(a))){f.push([h,h]),d.push(``);continue}f.push([h,a+h]);let o=a>=0?l:c;i===0&&t===r[0]&&e.firstValueAsSubtotal&&(o=u),d.push(o),h+=a}e.showSubTotals&&(m.push(T(`Subtotal`)),f.push([0,h]),d.push(u))}return s.data.datasets.push(p),s.data.labels=m.map(Xg),{chartJsConfig:s,background:e.background||`#FFFFFF`}}let aO=new h;aO.add(`bar`,{match:e=>e===`bar`,createChart:(e,t,n)=>new mD(e,t,n),getChartRuntime:hD,validateChartDefinition:mD.validateChartDefinition,transformDefinition:mD.transformDefinition,getChartDefinitionFromContextCreation:mD.getDefinitionFromContextCreation,sequence:10}),aO.add(`combo`,{match:e=>e===`combo`,createChart:(e,t,n)=>new PD(e,t,n),getChartRuntime:FD,validateChartDefinition:PD.validateChartDefinition,transformDefinition:PD.transformDefinition,getChartDefinitionFromContextCreation:PD.getDefinitionFromContextCreation,sequence:15}),aO.add(`line`,{match:e=>e===`line`,createChart:(e,t,n)=>new GD(e,t,n),getChartRuntime:ND,validateChartDefinition:GD.validateChartDefinition,transformDefinition:GD.transformDefinition,getChartDefinitionFromContextCreation:GD.getDefinitionFromContextCreation,sequence:20}),aO.add(`pie`,{match:e=>e===`pie`,createChart:(e,t,n)=>new KD(e,t,n),getChartRuntime:ZD,validateChartDefinition:KD.validateChartDefinition,transformDefinition:KD.transformDefinition,getChartDefinitionFromContextCreation:KD.getDefinitionFromContextCreation,sequence:30}),aO.add(`scorecard`,{match:e=>e===`scorecard`,createChart:(e,t,n)=>new Bg(e,t,n),getChartRuntime:Hg,validateChartDefinition:Bg.validateChartDefinition,transformDefinition:Bg.transformDefinition,getChartDefinitionFromContextCreation:Bg.getDefinitionFromContextCreation,sequence:40}),aO.add(`gauge`,{match:e=>e===`gauge`,createChart:(e,t,n)=>new HD(e,t,n),getChartRuntime:UD,validateChartDefinition:HD.validateChartDefinition,transformDefinition:HD.transformDefinition,getChartDefinitionFromContextCreation:HD.getDefinitionFromContextCreation,sequence:50}),aO.add(`scatter`,{match:e=>e===`scatter`,createChart:(e,t,n)=>new eO(e,t,n),getChartRuntime:tO,validateChartDefinition:eO.validateChartDefinition,transformDefinition:eO.transformDefinition,getChartDefinitionFromContextCreation:eO.getDefinitionFromContextCreation,sequence:60}),aO.add(`waterfall`,{match:e=>e===`waterfall`,createChart:(e,t,n)=>new nO(e,t,n),getChartRuntime:iO,validateChartDefinition:nO.validateChartDefinition,transformDefinition:nO.transformDefinition,getChartDefinitionFromContextCreation:nO.getDefinitionFromContextCreation,sequence:70}),aO.add(`pyramid`,{match:e=>e===`pyramid`,createChart:(e,t,n)=>new QD(e,t,n),getChartRuntime:$D,validateChartDefinition:QD.validateChartDefinition,transformDefinition:QD.transformDefinition,getChartDefinitionFromContextCreation:QD.getDefinitionFromContextCreation,sequence:80});let oO=new h;oO.add(`line`,s_),oO.add(`bar`,s_),oO.add(`combo`,s_),oO.add(`pie`,s_),oO.add(`gauge`,fD),oO.add(`scatter`,s_),oO.add(`scorecard`,c_),oO.add(`waterfall`,s_),oO.add(`pyramid`,s_);let sO={line:T(`Line`),column:T(`Column`),bar:T(`Bar`),area:T(`Area`),pie:T(`Pie`),misc:T(`Miscellaneous`)},cO=new h;cO.add(`line`,{matcher:e=>e.type===`line`&&!e.stacked&&!e.fillArea,displayName:T(`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:T(`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:T(`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:T(`Stacked Area`),chartType:`line`,chartSubtype:`stacked_area`,subtypeDefinition:{stacked:!0,fillArea:!0},category:`area`,preview:`o-spreadsheet-ChartPreview.STACKED_AREA_CHART`}).add(`scatter`,{displayName:T(`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:T(`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:T(`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:T(`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:T(`Stacked Bar`),chartType:`bar`,chartSubtype:`stacked_bar`,subtypeDefinition:{horizontal:!0,stacked:!0},category:`bar`,preview:`o-spreadsheet-ChartPreview.STACKED_BAR_CHART`}).add(`combo`,{displayName:T(`Combo`),chartSubtype:`combo`,chartType:`combo`,category:`line`,preview:`o-spreadsheet-ChartPreview.COMBO_CHART`}).add(`pie`,{matcher:e=>e.type===`pie`&&!e.isDoughnut,displayName:T(`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:T(`Doughnut`),chartSubtype:`doughnut`,chartType:`pie`,subtypeDefinition:{isDoughnut:!0},category:`pie`,preview:`o-spreadsheet-ChartPreview.DOUGHNUT_CHART`}).add(`gauge`,{displayName:T(`Gauge`),chartSubtype:`gauge`,chartType:`gauge`,category:`misc`,preview:`o-spreadsheet-ChartPreview.GAUGE_CHART`}).add(`scorecard`,{displayName:T(`Scorecard`),chartSubtype:`scorecard`,chartType:`scorecard`,category:`misc`,preview:`o-spreadsheet-ChartPreview.SCORECARD_CHART`}).add(`waterfall`,{displayName:T(`Waterfall`),chartSubtype:`waterfall`,chartType:`waterfall`,category:`misc`,preview:`o-spreadsheet-ChartPreview.WATERFALL_CHART`}).add(`pyramid`,{displayName:T(`Population Pyramid`),chartSubtype:`pyramid`,chartType:`pyramid`,category:`misc`,preview:`o-spreadsheet-ChartPreview.POPULATION_PYRAMID_CHART`});let lO=new h;H`
|
|
171
171
|
.o-chart-container {
|
|
172
172
|
width: 100%;
|
|
173
173
|
height: 100%;
|
|
@@ -1207,7 +1207,7 @@ stores.inject(MyMetaStore, storeInstance);
|
|
|
1207
1207
|
}
|
|
1208
1208
|
}
|
|
1209
1209
|
}
|
|
1210
|
-
`;var YP=class extends t.Component{static template=`o-spreadsheet-FindAndReplacePanel`;static components={SelectionInput:kN,Section:Z,Checkbox:EN,ValidationMessages:jN};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 T(`%s matches in all sheets`,this.store.allSheetMatchesCount)}get currentSheetMatchesCount(){return T(`%(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 T(`%(matches)s matches in range %(range)s of %(sheetName)s`,{matches:this.store.specificRangeMatchesCount,range:nr(n),sheetName:this.env.model.getters.getSheetName(t)})}get searchInfo(){return this.store.toSearch?[this.specificRangeMatchesCount,this.currentSheetMatchesCount,this.allSheetsMatchesCount]:[]}setup(){this.store=ud(JP),this.state=(0,t.useState)({dataRange:``}),(0,t.onMounted)(()=>this.searchInput.el?.focus()),(0,t.onWillUnmount)(()=>this.updateSearchContent.stopDebounce()),this.updateSearchContent=Ct(this.store.updateSearchContent,200)}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()}};H`
|
|
1210
|
+
`;var YP=class extends t.Component{static template=`o-spreadsheet-FindAndReplacePanel`;static components={SelectionInput:kN,Section:Z,Checkbox:EN,ValidationMessages:jN};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 T(`%s matches in all sheets`,this.store.allSheetMatchesCount)}get currentSheetMatchesCount(){return T(`%(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||e.invalidSheetName||e.invalidXc)return``;let{sheetId:t,zone:n}=e;return T(`%(matches)s matches in range %(range)s of %(sheetName)s`,{matches:this.store.specificRangeMatchesCount,range:nr(n),sheetName:this.env.model.getters.getSheetName(t)})}get searchInfo(){return this.store.toSearch?[this.specificRangeMatchesCount,this.currentSheetMatchesCount,this.allSheetsMatchesCount]:[]}setup(){this.store=ud(JP),this.state=(0,t.useState)({dataRange:``}),(0,t.onMounted)(()=>this.searchInput.el?.focus()),(0,t.onWillUnmount)(()=>this.updateSearchContent.stopDebounce()),this.updateSearchContent=Ct(this.store.updateSearchContent,200)}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()}};H`
|
|
1211
1211
|
.o-more-formats-panel {
|
|
1212
1212
|
.format-preview {
|
|
1213
1213
|
height: 48px;
|
|
@@ -1306,7 +1306,7 @@ stores.inject(MyMetaStore, storeInstance);
|
|
|
1306
1306
|
.add-calculated-measure {
|
|
1307
1307
|
cursor: pointer;
|
|
1308
1308
|
}
|
|
1309
|
-
`;var uF=class extends t.Component{static template=`o-spreadsheet-PivotLayoutConfigurator`;static components={AddDimensionButton:nF,PivotDimension:aF,PivotDimensionOrder:sF,PivotDimensionGranularity:oF,PivotMeasureEditor:lF};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=pP();AGGREGATORS=Du;composerFocus;isDateOrDatetimeField=Nu;setup(){this.composerFocus=V(vd)}startDragAndDrop(e,t){if(t.button!==0||t.target.tagName===`SELECT`)return;let n=this.getDimensionElementsRects(),{columns:r,rows:i}=this.props.definition,a=[...r.map(e=>e.nameWithGranularity),`__rows_title__`,...i.map(e=>e.nameWithGranularity)],o=r.concat(i),s=a.map((e,t)=>({id:e,size:n[t+1].height,position:n[t+1].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.nameWithGranularity,initialMousePosition:t.clientY,items:s,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{let n=a.findIndex(t=>t===e);if(n===t)return;let r=[...a];r.splice(n,1),r.splice(t,0,e);let i=r.slice(0,r.indexOf(`__rows_title__`)),s=r.slice(r.indexOf(`__rows_title__`)+1);this.props.onDimensionsUpdated({columns:i.map(e=>o.find(t=>t.nameWithGranularity===e)).filter(S),rows:s.map(e=>o.find(t=>t.nameWithGranularity===e)).filter(S)})}})}getGranularitiesFor(e){return Nu(e)?e.type===`date`?this.props.dateGranularities:this.props.datetimeGranularities:[]}startDragAndDropMeasures(e,t){if(t.button!==0||t.target.tagName===`SELECT`||t.target.tagName===`INPUT`||this.composerFocus.focusMode!==`inactive`)return;let n=this.getDimensionElementsRects(),{measures:r,columns:i,rows:a}=this.props.definition,o=r.map(e=>e.id),s=3+i.length+a.length,c=o.map((e,t)=>({id:e,size:n[t+s].height,position:n[t+s].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.id,initialMousePosition:t.clientY,items:c,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{let n=o.findIndex(t=>t===e);if(n===t)return;let i=[...o];i.splice(n,1),i.splice(t,0,e),this.props.onDimensionsUpdated({measures:i.map(e=>r.find(t=>t.id===e)).filter(S)})}})}getDimensionElementsRects(){return Array.from(this.dimensionsRef.el.children).map(e=>{let t=getComputedStyle(e),n=e.getBoundingClientRect();return{x:n.x,y:n.y,width:n.width+parseInt(t.marginLeft||`0`)+parseInt(t.marginRight||`0`),height:n.height+parseInt(t.marginTop||`0`)+parseInt(t.marginBottom||`0`)}})}removeDimension(e){let{columns:t,rows:n}=this.props.definition;this.props.onDimensionsUpdated({columns:t.filter(t=>t.nameWithGranularity!==e.nameWithGranularity),rows:n.filter(t=>t.nameWithGranularity!==e.nameWithGranularity)})}removeMeasureDimension(e){let{measures:t}=this.props.definition;this.props.onDimensionsUpdated({measures:t.filter(t=>t.id!==e.id)})}addColumnDimension(e){let{columns:t}=this.props.definition;this.props.onDimensionsUpdated({columns:t.concat([{fieldName:e,order:`asc`}])})}addRowDimension(e){let{rows:t}=this.props.definition;this.props.onDimensionsUpdated({rows:t.concat([{fieldName:e,order:`asc`}])})}addMeasureDimension(e){let{measures:t}=this.props.definition,n=this.getDefaultMeasureAggregator(e);this.props.onDimensionsUpdated({measures:t.concat([{id:this.getMeasureId(e,n),fieldName:e,aggregator:n}])})}updateMeasure(e,t){let{measures:n}=this.props.definition;this.props.onDimensionsUpdated({measures:n.map(n=>n.id===e.id?t:n)})}getMeasureId(e,t){let n=e.replaceAll(`'`,``)+(t?`:${t}`:``),r=n,i=2;for(;this.props.definition.measures.some(e=>e.id===r);)r=`${n}:${i}`,i++;return r}getDefaultMeasureAggregator(e){let t=this.props.measureFields.find(t=>t.name===e);return t?.aggregator?t.aggregator:`count`}addCalculatedMeasure(){let{measures:e}=this.props.definition,t=this.env.model.getters.generateNewCalculatedMeasureName(e);this.props.onDimensionsUpdated({measures:e.concat([{id:this.getMeasureId(t,`sum`),fieldName:t,aggregator:`sum`,computedBy:{sheetId:this.env.model.getters.getActiveSheetId(),formula:`=0`}}])})}updateOrder(e,t){let{rows:n,columns:r}=this.props.definition;this.props.onDimensionsUpdated({rows:n.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,order:t||void 0}:n),columns:r.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,order:t||void 0}:n)})}updateGranularity(e,t){let{rows:n,columns:r}=this.props.definition;this.props.onDimensionsUpdated({rows:n.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,granularity:t}:n),columns:r.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,granularity:t}:n)})}getMeasureDescription(e){let t=e.display;if(!t||t.type===`no_calculations`)return``;let n=this.env.model.getters.getPivot(this.props.pivotId),r=[...n.definition.columns,...n.definition.rows].find(e=>e.nameWithGranularity===t.fieldNameWithGranularity),i=r?Uu(r):``;return mg.descriptions[t.type](i)}},dF=class extends t.Component{static template=`o-spreadsheet-PivotTitleSection`;static components={CogWheelMenu:iF,Section:Z,TextInput:rF};static props={pivotId:String,flipAxis:Function};get cogWheelMenuItems(){return[{name:T(`Flip axes`),icon:`o-spreadsheet-Icon.EXCHANGE`,execute:this.props.flipAxis},{name:T(`Duplicate`),icon:`o-spreadsheet-Icon.COPY`,execute:()=>this.duplicatePivot()},{name:T(`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?T(`Pivot duplicated.`):n.isCancelledBecause(`PivotInError`)?T(`Cannot duplicate a pivot in error.`):T(`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(T(`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}})}},fF=class{measures;columns;rows;constructor(e,t){this.measures=e.measures.map(e=>pF(t,e)),this.columns=e.columns.map(e=>this.createPivotDimension(t,e)),this.rows=e.rows.map(e=>this.createPivotDimension(t,e))}getDimension(e){let t=this.columns.find(t=>t.nameWithGranularity===e)||this.rows.find(t=>t.nameWithGranularity===e);if(!t)throw new j(T(`Dimension %s does not exist`,e));return t}getMeasure(e){let t=this.measures.find(t=>t.id===e);if(!t)throw new j(T(`Field %s is not a measure`,e));return t}createPivotDimension(e,t){let n=e[t.fieldName],r=n?.type??`integer`,i=n&&Nu(n)?t.granularity:void 0;return{displayName:n?.string??t.fieldName,nameWithGranularity:t.fieldName+(i?`:${i}`:``),fieldName:t.fieldName,granularity:i,type:r,order:t.order,isValid:!!n}}};function pF(e,t){let n=t.fieldName,r=n===`__count`?{name:`__count`,string:T(`Count`),type:`integer`,aggregator:`sum`}:e[n],i=t.aggregator;return{id:t.id,get displayName(){return t.userDefinedName??r?.string??t.fieldName},userDefinedName:t.userDefinedName,fieldName:n,aggregator:i,type:n===`__count`?`integer`:r?.type??`integer`,isValid:!!(r||t.computedBy),isHidden:t.isHidden,format:t.format,computedBy:t.computedBy,display:t.display}}var mF=class extends fF{range;constructor(e,t,n){if(super(e,t),e.dataSet){let{sheetId:t,zone:r}=e.dataSet;this.range=n.getRangeFromZone(t,r)}}},hF=class{columns;rows;measures;fieldsType;maxIndent;pivotCells={};rowTree;colTree;constructor(e,t,n,r){this.columns=e.map(e=>{let t=1;return e.map(e=>(e={...e,offset:t},t+=e.width,e))}),this.rows=t,this.measures=n,this.fieldsType=r,this.maxIndent=Math.max(...this.rows.map(e=>e.indent)),this.rowTree=Et(()=>this.buildRowsTree()),this.colTree=Et(()=>this.buildColumnsTree())}getNumberOfDataColumns(){return this.columns.at(-1)?.length||0}getPivotCells(e=!0,t=!0){let n=JSON.stringify({includeTotal:e,includeColumnHeaders:t});if(!this.pivotCells[n]){let r=this.rows.length,i=this.getNumberOfDataColumns(),a=this.columns.length+r,o=1+i;!e&&r!==1&&--a,!e&&i!==this.measures.length&&(o-=this.measures.length);let s=[],c=t?0:this.columns.length;for(let t=0;t<o;t++){s.push([]);for(let n=c;n<a;n++)!e&&n===a||s[t].push(this.getPivotCell(t,n,e))}this.pivotCells[n]=s}return this.pivotCells[n]}getRowTree(){return this.rowTree()}getColTree(){return this.colTree()}isTotalRow(e){return this.rows[e].indent!==this.maxIndent}getPivotCell(e,t,n=!0){let r=this.columns.length;if(e>0&&t===r-1){let n=this.getColHeaderDomain(e,t);if(!n)return gF;let r=n.at(-1)?.value?.toString()||``;return{type:`MEASURE_HEADER`,domain:n.slice(0,-1),measure:r}}else if(t<=r-1){let n=this.getColHeaderDomain(e,t);return n?{type:`HEADER`,domain:n}:gF}else if(e===0){let e=t-r;return{type:`HEADER`,domain:this.getRowDomain(e)}}else{let i=t-r;return!n&&this.isTotalRow(i)?gF:{type:`VALUE`,domain:[...this.getRowDomain(i),...this.getColDomain(e)],measure:this.getColMeasure(e)}}}getColHeaderDomain(e,t){if(e===0)return;let n=[],r=this.columns[t].find(t=>t.offset===e);if(r){for(let e=0;e<r.fields.length;e++){let t=r.fields[e];if(t===`measure`)n.push({type:`char`,field:t,value:Lu({displayName:`measure`,type:`char`},r.values[e])});else{let{fieldName:i,granularity:a}=Mu(t),o=this.fieldsType[i]||`char`;n.push({type:o,field:t,value:Lu({displayName:i,type:o,granularity:a},r.values[e])})}}return n}}getColDomain(e){let t=this.getColHeaderDomain(e,this.columns.length-1);return t?t.slice(0,-1):[]}getColMeasure(e){let t=this.getColHeaderDomain(e,this.columns.length-1)?.at(-1)?.value;if(t==null)throw Error(`Measure is missing`);return t.toString()}getRowDomain(e){let t=[];for(let n=0;n<this.rows[e].fields.length;n++){let r=this.rows[e].fields[n],{fieldName:i,granularity:a}=Mu(r),o=this.fieldsType[i]||`char`;t.push({type:o,field:r,value:Lu({displayName:i,type:o,granularity:a},this.rows[e].values[n])})}return t}buildRowsTree(){let e=[],t=0,n={};n[0]=e;for(let r of this.rows){if(r.fields.length===0||r.values.length===0)return e;let i=r.fields.length-1,a=r.fields[i],{fieldName:o,granularity:s}=Mu(a),c=Lu({displayName:o,type:this.fieldsType[o]??`char`,granularity:s},r.values[i]);if(i>t){t=i,n[t]=[];let e=n[t-1].at(-1);e&&(e.children=n[t])}t=i;let l={value:c,field:r.fields[i],children:[],width:0};n[t].push(l)}return e}buildColumnsTree(){let e=[],t=this.columns.at(-2)||[],n={};n[0]=e;for(let e of t)for(let t=0;t<e.fields.length;t++){let r=e.fields[t],{fieldName:i,granularity:a}=Mu(r),o=Lu({displayName:i,type:this.fieldsType[i]??`char`,granularity:a},e.values[t]),s={value:o,field:e.fields[t],children:[],width:e.width};n[t]?.at(-1)?.value!==o&&(n[t+1]=[],s.children=n[t+1],n[t].push(s))}return e}export(){return{cols:this.columns,rows:this.rows,measures:this.measures,fieldsType:this.fieldsType}}};let gF={type:`EMPTY`};function _F(e,t){let n=t.measures.filter(e=>!e.isHidden).map(e=>e.id),r=yF(e,t.columns,0);bF(r,n.length);let i=xF(r,t),a=vF(e,0,t.rows,[],[]);a.push({fields:[],values:[],indent:0});let o={};for(let e of t.columns)o[e.fieldName]=e.type;for(let e of t.rows)o[e.fieldName]=e.type;return new hF(i,a,n,o)}function vF(e,t,n,r,i){if(t>=n.length)return[];let a=n[t],o=a.nameWithGranularity,s=SF(e,a),c=wF(s,a),l=[],u=r.concat(o);for(let e of c){let r=i.concat(e);l.push({fields:u,values:r,indent:t});let a=s[e];a&&l.push(...vF(a,t+1,n,u,r))}return l}function yF(e,t,n){if(n>=t.length)return[];let r=t[n],i=t[n].nameWithGranularity,a=SF(e,r);return wF(a,t[n]).map(e=>({value:a[e]?.[0]?.[r.nameWithGranularity]?.value??null,field:i,children:yF(a[e]||[],t,n+1),width:0}))}function bF(e,t){for(let n in e){let r=e[n];r.children.length===0?r.width=t:(bF(r.children,t),r.width=r.children.reduce((e,t)=>e+t.width,0))}}function xF(e,t){let n=t.columns.map(e=>e.nameWithGranularity),r=n.length,i=t.measures.filter(e=>!e.isHidden),a=i.length,o=Array(r).fill(0).map(()=>[]);function s(e,t,i){let a=o[t];for(let o of e){let e=i.concat([o.value]),c={fields:n.slice(0,t+1),values:e,width:o.width,offset:0};a.push(c),t<=r-1&&s(o.children,t+1,e)}}s(e,0,[]);let c=n.length>0,l=[];return c&&o[o.length-1].forEach(e=>{i.forEach(t=>{let n={fields:[...e.fields,`measure`],values:[...e.values,t.id],width:1,offset:0};l.push(n)})}),i.forEach(e=>{let t={fields:[`measure`],values:[e.id],width:1,offset:0};l.push(t)}),o.push(l),o.length===1&&o.unshift([]),o[o.length-2].push({fields:[],values:[],width:a,offset:0}),o}function SF(e,t){return Object.groupBy(e,CF(t))}function CF(e){let t=e.nameWithGranularity;return e=>`${e[t]?.value??null}`}function wF(e,t){return t.order?Object.keys(e).sort((e,n)=>TF(t,e,n)):Object.keys(e)}function TF(e,t,n){return t===`null`?e.order===`asc`?1:-1:n===`null`?e.order===`asc`?-1:1:e.type===`integer`||e.type===`datetime`?e.order===`asc`?P(t,O)-P(n,O):P(n,O)-P(t,O):e.order===`asc`?t.localeCompare(n):n.localeCompare(t)}let EF=Symbol(`NULL`);function DF(e,t,n){let r=e.granularity||`month`;if(!(r in OF))throw Error(`Unknown date granularity: ${r}`);let i=typeof t==`number`||typeof t==`string`?t:EF;if(!OF[r].set.has(t)){OF[r].set.add(t);let a=null;if(typeof t==`number`||typeof t==`string`){let e=R(t,n);switch(r){case`year`:a=e.getFullYear();break;case`quarter_number`:a=Math.floor(e.getMonth()/3)+1;break;case`month_number`:a=e.getMonth()+1;break;case`month`:a=Math.floor(P(t,n));break;case`iso_week_number`:a=e.getIsoWeek();break;case`day_of_month`:a=e.getDate();break;case`day`:a=Math.floor(P(t,n));break;case`day_of_week`:a=(e.getDay()+7-n.weekStart)%7+1;break;case`hour_number`:a=e.getHours();break;case`minute_number`:a=e.getMinutes();break;case`second_number`:a=e.getSeconds();break}}OF[r].values[i]=Lu(e,a)}return OF[r].values[i]}let OF={year:{set:new Set,values:{}},quarter_number:{set:new Set,values:{}},month_number:{set:new Set,values:{}},month:{set:new Set,values:{}},iso_week_number:{set:new Set,values:{}},day_of_month:{set:new Set,values:{}},day:{set:new Set,values:{}},day_of_week:{set:new Set,values:{}},hour_number:{set:new Set,values:{}},minute_number:{set:new Set,values:{}},second_number:{set:new Set,values:{}}};function kF(){for(let e in OF)OF[e].set.clear(),OF[e].values={}}var AF=class{type=`SPREADSHEET`;getters;_definition;coreDefinition;metaData={fields:{},fieldKeys:[]};dataEntries=[];table;invalidRangeError;needsReevaluation=!0;constructor(e,t){this.getters=t.getters,this.coreDefinition=t.definition}init(e={}){(!this._definition||e.reload)&&(this.reload(4),this.needsReevaluation=!1)}reload(e){e===4&&(this.metaData=this.loadMetaData()),e>=3&&(this._definition=this.loadRuntimeDefinition()),e>=2&&(this.dataEntries=this.loadData()),e>=1&&(this.table=void 0)}onDefinitionChange(e){let t=this.coreDefinition;if(this.coreDefinition=e,this._definition){let n=Math.max(this.computeShouldReload(t,e),0);this.reload(n)}}computeShouldReload(e,t){return C(e.dataSet,t.dataSet)?3:4}get isInvalidRange(){return!!this.invalidRangeError}get invalidRangeMessage(){return this.invalidRangeError?.message}get definition(){if(this._definition||this.init(),!this._definition)throw Error(`Pivot definition should be defined at this point.`);return this._definition}isValid(){if(this.invalidRangeError||!this.definition)return!1;for(let e of this.definition.measures)if(!e.isValid)return!1;for(let e of this.definition.columns)if(!e.isValid)return!1;for(let e of this.definition.rows)if(!e.isValid)return!1;return!0}assertIsValid({throwOnError:e}){if(!this.isValid()){if(e)throw this.invalidRangeError?this.invalidRangeError:new j(T(`At least one measure and/or dimension is not correct.`));return{value:A.GenericError,message:this.invalidRangeError?.message??T(`At least one measure and/or dimension is not correct.`)}}}areDomainArgsFieldsValid(e){let t=e.filter((e,t)=>t%2==0).map(F);return t.length&&t.at(-1)===`measure`&&(t=t.slice(0,-1)),Fu(t,this.definition)}parseArgsToPivotDomain(e){let t=[];for(let n=0;n<e.length-1;n+=2){let r=F(e[n]),i=this.getTypeOfDimension(r),a=r===`measure`?F(e[n+1]):Lu(this.getDimension(r),e[n+1]);t.push({field:r,value:a,type:i})}return t}markAsDirtyForEvaluation(){this.needsReevaluation=!0}getMeasure(e){return this.definition.getMeasure(e)}getPivotMeasureValue(e){return{value:this.getMeasure(e).displayName}}getPivotHeaderValueAndFormat(e){let t=e.at(-1);if(!t)return{value:T(`Total`)};let n=this.getDimension(t.field),r=this.filterDataEntriesFromDomain(this.dataEntries,e)[0]?.[n.nameWithGranularity];return n.type===`datetime`?du(n.granularity||`month`).toValueAndFormat(t.value,this.getters.getLocale()):r?r.value===null?{value:T(`(Undefined)`)}:r:{value:``}}getPivotCellValueAndFormat(e,t){let n=this.filterDataEntriesFromDomain(this.dataEntries,t);if(n.length===0)return{value:``};let r=this.getMeasure(e),i=n.map(e=>e[r.fieldName]).filter(S),a=i.filter(e=>e.type!==`empty`),o=r.aggregator,s=Ou[o];if(!s)throw Error(`Aggregator ${o} does not exist`);try{let e=s([i],this.getters.getLocale());return a.length===0?{...e,value:``}:e}catch(e){return VT(e,o.toUpperCase())}}getPossibleFieldValues(e){let t=[],n=SF(this.dataEntries,e),r=wF(n,e);for(let i of r)t.push({value:n[i]?.[0]?.[e.nameWithGranularity]?.value??``,label:n[i]?.[0]?.[e.nameWithGranularity]?.formattedValue||``});return t}getTableStructure(){if(!this.isValid())throw Error(`Pivot is not valid !`);return this.table||=_F(this.dataEntries,this.definition),this.table}getFields(){return this.metaData.fields}get fields(){return this.getFields()}loadMetaData(){if(this.invalidRangeError=void 0,this.coreDefinition.dataSet){let{zone:e,sheetId:t}=this.coreDefinition.dataSet,n=this.getters.getRangeFromZone(t,e);try{return this.extractFieldsFromRange(n)}catch(e){return this.invalidRangeError=e,{fields:{},fieldKeys:[]}}}else return this.invalidRangeError=new j(T(`The pivot cannot be created because the dataset is missing.`)),{fields:{},fieldKeys:[]}}loadRuntimeDefinition(){return new mF(this.coreDefinition,this.fields,this.getters)}loadData(){let e=this._definition?.range;return this.isValid()&&e?this.extractDataEntriesFromRange(e):[]}getTypeOfDimension(e){if(e===`measure`)return`char`;let{fieldName:t}=Mu(e),n=this.fields[t]?.type;if(!n)throw Error(`Field ${t} does not exist`);return n}filterDataEntriesFromDomain(e,t){return t.reduce((e,t)=>this.filterDataEntriesFromDomainNode(e,t),e)}filterDataEntriesFromDomainNode(e,t){let{field:n,value:r,type:i}=t,{nameWithGranularity:a}=this.getDimension(n);return e.filter(e=>{let t=e[a]?.value;return i===`char`?String(t)===String(r):t===r})}getDimension(e){return this.definition.getDimension(e)}getTypeFromZone(e,t){let n=this.getters.getEvaluatedCellsInZone(e,t).filter(e=>!(e.type===`empty`||e.value===``));return n.length===0?`integer`:n.every(e=>e.type===`number`&&e.format&&Ko(e.format))?`datetime`:n.every(e=>e.type===`boolean`)?`boolean`:n.every(e=>e.type===`number`)?`integer`:`char`}assertCellIsValidField(e,t,n){if(n.type===`error`)throw new j(T(`The pivot cannot be created because cell %s contains an error`,w(e,t)));if(n.type===`empty`||n.value===``)throw new j(T(`The pivot cannot be created because cell %s is empty`,w(e,t)));if(n.value===`__count`)throw new j(T(`The pivot cannot be created because cell %s contains a reserved value`,w(e,t)))}extractFieldsFromRange(e){let t={},n=[],r=e.sheetId,i=e.zone.top;for(let a=e.zone.left;a<=e.zone.right;a++){let o=this.getters.getEvaluatedCell({sheetId:r,col:a,row:i});this.assertCellIsValidField(a,i,o);let s=o.value?.toString();if(s){let i=this.getTypeFromZone(r,{top:e.zone.top+1,left:a,bottom:e.zone.bottom,right:a}),o=this.findName(s,t);t[o]={name:o,type:i,string:o,aggregator:i===`integer`?`sum`:`count`},n.push(o)}}return{fields:t,fieldKeys:n}}findName(e,t){let n=1,r=e;for(;e in t;)e=`${r}${++n}`;return e}extractDataEntriesFromRange(e){let t=[];for(let n=e.zone.top+1;n<=e.zone.bottom;n++){let r={top:n,bottom:n,left:e.zone.left,right:e.zone.right},i=this.getters.getEvaluatedCellsInZone(e.sheetId,r),a={};for(let e in i){let t=i[e],n=this.fields[this.metaData.fieldKeys[e]];if(!n)throw Error(`Field ${this.metaData.fieldKeys[e]} does not exist`);t.value===``?a[n.name]={value:null,type:`empty`,formattedValue:``}:a[n.name]=t}a.__count={value:1,type:`number`,formattedValue:`1`},t.push(a)}let n=this.definition.columns.concat(this.definition.rows).filter(e=>e.type===`datetime`);if(n.length){let e=this.getters.getLocale();for(let r of t)for(let t of n){let n=DF(t,r[t.fieldName]?.value||null,this.getters.getLocale()),{format:i,value:a}=du(t.granularity||`month`).toValueAndFormat(n,e);r[t.nameWithGranularity]={value:n,type:r[t.fieldName]?.type||`empty`,format:r[t.fieldName]?.format,formattedValue:B(a,{locale:e,format:i})}}}return t}};let jF=new h,MF=[`year`,`quarter_number`,`month_number`,`month`,`iso_week_number`,`day_of_month`,`day`,`day_of_week`],NF=[...MF,`hour_number`,`minute_number`,`second_number`];jF.add(`SPREADSHEET`,{ui:AF,definition:mF,dateGranularities:[...MF],datetimeGranularities:[...NF],isMeasureCandidate:e=>![`datetime`,`boolean`].includes(e.type),isGroupable:()=>!0,adaptRanges:(e,t,n)=>{if(t.type!==`SPREADSHEET`||!t.dataSet)return t;let{sheetId:r,zone:i}=t.dataSet,a=e.getRangeFromZone(r,i),o=PF(a,n);if(o===a)return t;let s=o&&{sheetId:o.sheetId,zone:o.zone};return{...t,dataSet:s}}});function PF(e,t){if(!e)return;let n=t(e);switch(n.changeType){case`NONE`:return e;case`REMOVE`:return;default:return n.range}}var FF=class extends gd{pivotId;mutators=[`reset`,`deferUpdates`,`applyUpdate`,`discardPendingUpdate`,`update`];updatesAreDeferred=!1;draft=null;notification=this.get(cP);alreadyNotified=!1;constructor(e,t){super(e),this.pivotId=t}handle(e){switch(e.type){case`UPDATE_PIVOT`:e.pivotId===this.pivotId&&this.getters.getPivot(this.pivotId).init()}}get fields(){return this.pivot.getFields()}get pivot(){return this.getters.getPivot(this.pivotId)}get definition(){let e=jF.get(this.pivot.type).definition;return this.draft?new e(this.draft,this.fields,this.getters):this.pivot.definition}get isDirty(){return!!this.draft}get measureFields(){let e=[{name:`__count`,string:T(`Count`),type:`integer`,aggregator:`sum`}],t=this.fields;for(let n in t){let r=t[n];r&&jF.get(this.pivot.type).isMeasureCandidate(r)&&e.push(r)}return e.sort((e,t)=>e.string.localeCompare(t.string))}get unusedGroupableFields(){let e=[],t=this.fields;for(let n in t){let r=t[n];r&&jF.get(this.pivot.type).isGroupable(r)&&e.push(r)}let{columns:n,rows:r,measures:i}=this.definition,a=i.concat(r).concat(n).map(e=>e.fieldName),o=this.unusedGranularities;return e.filter(e=>Nu(e)?!a.includes(e.name)||o[e.name].size>0:!a.includes(e.name)).sort((e,t)=>e.string.localeCompare(t.string))}get datetimeGranularities(){return jF.get(this.pivot.type).datetimeGranularities}get dateGranularities(){return jF.get(this.pivot.type).dateGranularities}get unusedGranularities(){return this.getUnusedGranularities(this.fields,this.draft??this.getters.getPivotCoreDefinition(this.pivotId))}reset(e){this.pivotId=e,this.updatesAreDeferred=!0,this.draft=null}deferUpdates(e){this.updatesAreDeferred=e,e===!1&&this.draft&&this.applyUpdate()}applyUpdate(){if(this.draft&&(this.model.dispatch(`UPDATE_PIVOT`,{pivotId:this.pivotId,pivot:this.draft}),this.draft=null,!this.alreadyNotified&&this.isUpdatedPivotVisibleInViewportOnlyAsStaticPivot())){let e=`=PIVOT(${this.getters.getPivotFormulaId(this.pivotId)})`;this.alreadyNotified=!0,this.notification.notifyUser({type:`info`,text:T(`Pivot updates only work with dynamic pivot tables. Use %s or re-insert the static pivot from the Data menu.`,e),sticky:!0})}}discardPendingUpdate(){this.draft=null}update(e){let t=this.getters.getPivotCoreDefinition(this.pivotId),n={...t,...this.draft,...e},r={...n,columns:n.columns.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),rows:n.rows.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),measures:n.measures.map(e=>({id:e.id,fieldName:e.fieldName,aggregator:e.aggregator,userDefinedName:e.userDefinedName,computedBy:e.computedBy,isHidden:e.isHidden,format:e.format,display:e.display}))};if(!this.draft&&C(t,r))return;let i=this.addDefaultDateTimeGranularity(this.fields,r);this.draft=i,this.updatesAreDeferred||this.applyUpdate()}isUpdatedPivotVisibleInViewportOnlyAsStaticPivot(){let e=0,t=this.getters.getPivotFormulaId(this.pivotId);for(let n of this.getters.getVisibleCellPositions()){let r=this.getters.getCell(n);if(r?.isFormula){let n=KE(r.compiledFormula.tokens),i=n?.args[0]?.value;if(n&&t===i.toString()){if(n.functionName===`PIVOT`)return!1;e++}}}return e>0}addDefaultDateTimeGranularity(e,t){let{columns:n,rows:r}=t,i=y(n),a=y(r),o=this.getUnusedGranularities(e,t);for(let t of i.concat(a)){let n=e[t.fieldName]?.type;if((n===`date`||n===`datetime`)&&!t.granularity){let e=o[t.fieldName]?.values().next().value;o[t.fieldName]?.delete(e),t.granularity=e}}return{...t,columns:i,rows:a}}getUnusedGranularities(e,t){let{columns:n,rows:r}=t,i=n.concat(r).filter(t=>{let n=e[t.fieldName]?.type;return n===`date`||n===`datetime`}),a={};for(let t of i)a[t.fieldName]=new Set(e[t.fieldName]?.type===`date`?this.dateGranularities:this.datetimeGranularities);for(let e of i)a[e.fieldName].delete(e.granularity);return a}},IF=class extends t.Component{static template=`o-spreadsheet-PivotSpreadsheetSidePanel`;static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:uF,Section:Z,SelectionInput:kN,Checkbox:EN,PivotDeferUpdate:eF,PivotTitleSection:dF};store;state;pivotSidePanelRef=(0,t.useRef)(`pivotSidePanel`);setup(){this.store=ud(FF,this.props.pivotId),this.state=(0,t.useState)({range:void 0,rangeHasChanged:!1})}get shouldDisplayInvalidRangeError(){return this.store.isDirty&&this.state.rangeHasChanged?!1:this.pivot.isInvalidRange}get ranges(){return this.state.range?[this.state.range]:this.definition.range?[this.env.model.getters.getRangeString(this.definition.range,`forceSheetReference`)]:[]}get pivot(){return this.store.pivot}get definition(){return this.store.definition}getScrollableContainerEl(){return this.pivotSidePanelRef.el}onSelectionChanged(e){this.state.rangeHasChanged=!0,this.state.range=e[0]}onSelectionConfirmed(){if(this.state.range){let e=this.env.model.getters.getRangeFromSheetXC(this.env.model.getters.getActiveSheetId(),this.state.range);if(e.invalidSheetName||e.invalidXc)return;let t={sheetId:e.sheetId,zone:e.zone};this.store.update({dataSet:t}),this.store.applyUpdate()}}flipAxis(){let{rows:e,columns:t}=this.definition;this.onDimensionsUpdated({rows:t,columns:e})}onDimensionsUpdated(e){this.store.update(e)}};let LF=new h;LF.add(`SPREADSHEET`,{editor:IF});var RF=class extends t.Component{static template=`o-spreadsheet-PivotSidePanel`;static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:uF,Section:Z};get sidePanelEditor(){let e=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);if(!e)throw Error(`pivotId does not correspond to a pivot.`);return LF.get(e.type).editor}};H`
|
|
1309
|
+
`;var uF=class extends t.Component{static template=`o-spreadsheet-PivotLayoutConfigurator`;static components={AddDimensionButton:nF,PivotDimension:aF,PivotDimensionOrder:sF,PivotDimensionGranularity:oF,PivotMeasureEditor:lF};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=pP();AGGREGATORS=Du;composerFocus;isDateOrDatetimeField=Nu;setup(){this.composerFocus=V(vd)}startDragAndDrop(e,t){if(t.button!==0||t.target.tagName===`SELECT`)return;let n=this.getDimensionElementsRects(),{columns:r,rows:i}=this.props.definition,a=[...r.map(e=>e.nameWithGranularity),`__rows_title__`,...i.map(e=>e.nameWithGranularity)],o=r.concat(i),s=a.map((e,t)=>({id:e,size:n[t+1].height,position:n[t+1].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.nameWithGranularity,initialMousePosition:t.clientY,items:s,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{let n=a.findIndex(t=>t===e);if(n===t)return;let r=[...a];r.splice(n,1),r.splice(t,0,e);let i=r.slice(0,r.indexOf(`__rows_title__`)),s=r.slice(r.indexOf(`__rows_title__`)+1);this.props.onDimensionsUpdated({columns:i.map(e=>o.find(t=>t.nameWithGranularity===e)).filter(S),rows:s.map(e=>o.find(t=>t.nameWithGranularity===e)).filter(S)})}})}getGranularitiesFor(e){return Nu(e)?e.type===`date`?this.props.dateGranularities:this.props.datetimeGranularities:[]}startDragAndDropMeasures(e,t){if(t.button!==0||t.target.tagName===`SELECT`||t.target.tagName===`INPUT`||this.composerFocus.focusMode!==`inactive`)return;let n=this.getDimensionElementsRects(),{measures:r,columns:i,rows:a}=this.props.definition,o=r.map(e=>e.id),s=3+i.length+a.length,c=o.map((e,t)=>({id:e,size:n[t+s].height,position:n[t+s].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.id,initialMousePosition:t.clientY,items:c,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{let n=o.findIndex(t=>t===e);if(n===t)return;let i=[...o];i.splice(n,1),i.splice(t,0,e),this.props.onDimensionsUpdated({measures:i.map(e=>r.find(t=>t.id===e)).filter(S)})}})}getDimensionElementsRects(){return Array.from(this.dimensionsRef.el.children).map(e=>{let t=getComputedStyle(e),n=e.getBoundingClientRect();return{x:n.x,y:n.y,width:n.width+parseInt(t.marginLeft||`0`)+parseInt(t.marginRight||`0`),height:n.height+parseInt(t.marginTop||`0`)+parseInt(t.marginBottom||`0`)}})}removeDimension(e){let{columns:t,rows:n}=this.props.definition;this.props.onDimensionsUpdated({columns:t.filter(t=>t.nameWithGranularity!==e.nameWithGranularity),rows:n.filter(t=>t.nameWithGranularity!==e.nameWithGranularity)})}removeMeasureDimension(e){let{measures:t}=this.props.definition;this.props.onDimensionsUpdated({measures:t.filter(t=>t.id!==e.id)})}addColumnDimension(e){let{columns:t}=this.props.definition;this.props.onDimensionsUpdated({columns:t.concat([{fieldName:e,order:`asc`}])})}addRowDimension(e){let{rows:t}=this.props.definition;this.props.onDimensionsUpdated({rows:t.concat([{fieldName:e,order:`asc`}])})}addMeasureDimension(e){let{measures:t}=this.props.definition,n=this.getDefaultMeasureAggregator(e);this.props.onDimensionsUpdated({measures:t.concat([{id:this.getMeasureId(e,n),fieldName:e,aggregator:n}])})}updateMeasure(e,t){let{measures:n}=this.props.definition;this.props.onDimensionsUpdated({measures:n.map(n=>n.id===e.id?t:n)})}getMeasureId(e,t){let n=e.replaceAll(`'`,``)+(t?`:${t}`:``),r=n,i=2;for(;this.props.definition.measures.some(e=>e.id===r);)r=`${n}:${i}`,i++;return r}getDefaultMeasureAggregator(e){let t=this.props.measureFields.find(t=>t.name===e);return t?.aggregator?t.aggregator:`count`}addCalculatedMeasure(){let{measures:e}=this.props.definition,t=this.env.model.getters.generateNewCalculatedMeasureName(e);this.props.onDimensionsUpdated({measures:e.concat([{id:this.getMeasureId(t,`sum`),fieldName:t,aggregator:`sum`,computedBy:{sheetId:this.env.model.getters.getActiveSheetId(),formula:`=0`}}])})}updateOrder(e,t){let{rows:n,columns:r}=this.props.definition;this.props.onDimensionsUpdated({rows:n.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,order:t||void 0}:n),columns:r.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,order:t||void 0}:n)})}updateGranularity(e,t){let{rows:n,columns:r}=this.props.definition;this.props.onDimensionsUpdated({rows:n.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,granularity:t}:n),columns:r.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,granularity:t}:n)})}getMeasureDescription(e){let t=e.display;if(!t||t.type===`no_calculations`)return``;let n=this.env.model.getters.getPivot(this.props.pivotId),r=[...n.definition.columns,...n.definition.rows].find(e=>e.nameWithGranularity===t.fieldNameWithGranularity),i=r?Uu(r):``;return mg.descriptions[t.type](i)}},dF=class extends t.Component{static template=`o-spreadsheet-PivotTitleSection`;static components={CogWheelMenu:iF,Section:Z,TextInput:rF};static props={pivotId:String,flipAxis:Function};get cogWheelMenuItems(){return[{name:T(`Flip axes`),icon:`o-spreadsheet-Icon.EXCHANGE`,execute:this.props.flipAxis},{name:T(`Duplicate`),icon:`o-spreadsheet-Icon.COPY`,execute:()=>this.duplicatePivot()},{name:T(`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?T(`Pivot duplicated.`):n.isCancelledBecause(`PivotInError`)?T(`Cannot duplicate a pivot in error.`):T(`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(T(`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}})}},fF=class{measures;columns;rows;constructor(e,t){this.measures=e.measures.map(e=>pF(t,e)),this.columns=e.columns.map(e=>this.createPivotDimension(t,e)),this.rows=e.rows.map(e=>this.createPivotDimension(t,e))}getDimension(e){let t=this.columns.find(t=>t.nameWithGranularity===e)||this.rows.find(t=>t.nameWithGranularity===e);if(!t)throw new j(T(`Dimension %s does not exist`,e));return t}getMeasure(e){let t=this.measures.find(t=>t.id===e);if(!t)throw new j(T(`Field %s is not a measure`,e));return t}createPivotDimension(e,t){let n=e[t.fieldName],r=n?.type??`integer`,i=n&&Nu(n)?t.granularity:void 0;return{displayName:n?.string??t.fieldName,nameWithGranularity:t.fieldName+(i?`:${i}`:``),fieldName:t.fieldName,granularity:i,type:r,order:t.order,isValid:!!n}}};function pF(e,t){let n=t.fieldName,r=n===`__count`?{name:`__count`,string:T(`Count`),type:`integer`,aggregator:`sum`}:e[n],i=t.aggregator;return{id:t.id,get displayName(){return t.userDefinedName??r?.string??t.fieldName},userDefinedName:t.userDefinedName,fieldName:n,aggregator:i,type:n===`__count`?`integer`:r?.type??`integer`,isValid:!!(r||t.computedBy),isHidden:t.isHidden,format:t.format,computedBy:t.computedBy,display:t.display}}var mF=class extends fF{range;constructor(e,t,n){if(super(e,t),e.dataSet){let{sheetId:t,zone:r}=e.dataSet;this.range=n.getRangeFromZone(t,r)}}},hF=class{columns;rows;measures;fieldsType;maxIndent;pivotCells={};rowTree;colTree;constructor(e,t,n,r){this.columns=e.map(e=>{let t=1;return e.map(e=>(e={...e,offset:t},t+=e.width,e))}),this.rows=t,this.measures=n,this.fieldsType=r,this.maxIndent=Math.max(...this.rows.map(e=>e.indent)),this.rowTree=Et(()=>this.buildRowsTree()),this.colTree=Et(()=>this.buildColumnsTree())}getNumberOfDataColumns(){return this.columns.at(-1)?.length||0}getPivotCells(e=!0,t=!0){let n=JSON.stringify({includeTotal:e,includeColumnHeaders:t});if(!this.pivotCells[n]){let r=this.rows.length,i=this.getNumberOfDataColumns(),a=this.columns.length+r,o=1+i;!e&&r!==1&&--a,!e&&i!==this.measures.length&&(o-=this.measures.length);let s=[],c=t?0:this.columns.length;for(let t=0;t<o;t++){s.push([]);for(let n=c;n<a;n++)!e&&n===a||s[t].push(this.getPivotCell(t,n,e))}this.pivotCells[n]=s}return this.pivotCells[n]}getRowTree(){return this.rowTree()}getColTree(){return this.colTree()}isTotalRow(e){return this.rows[e].indent!==this.maxIndent}getPivotCell(e,t,n=!0){let r=this.columns.length;if(e>0&&t===r-1){let n=this.getColHeaderDomain(e,t);if(!n)return gF;let r=n.at(-1)?.value?.toString()||``;return{type:`MEASURE_HEADER`,domain:n.slice(0,-1),measure:r}}else if(t<=r-1){let n=this.getColHeaderDomain(e,t);return n?{type:`HEADER`,domain:n}:gF}else if(e===0){let e=t-r;return{type:`HEADER`,domain:this.getRowDomain(e)}}else{let i=t-r;return!n&&this.isTotalRow(i)?gF:{type:`VALUE`,domain:[...this.getRowDomain(i),...this.getColDomain(e)],measure:this.getColMeasure(e)}}}getColHeaderDomain(e,t){if(e===0)return;let n=[],r=this.columns[t].find(t=>t.offset===e);if(r){for(let e=0;e<r.fields.length;e++){let t=r.fields[e];if(t===`measure`)n.push({type:`char`,field:t,value:Lu({displayName:`measure`,type:`char`},r.values[e])});else{let{fieldName:i,granularity:a}=Mu(t),o=this.fieldsType[i]||`char`;n.push({type:o,field:t,value:Lu({displayName:i,type:o,granularity:a},r.values[e])})}}return n}}getColDomain(e){let t=this.getColHeaderDomain(e,this.columns.length-1);return t?t.slice(0,-1):[]}getColMeasure(e){let t=this.getColHeaderDomain(e,this.columns.length-1)?.at(-1)?.value;if(t==null)throw Error(`Measure is missing`);return t.toString()}getRowDomain(e){let t=[];for(let n=0;n<this.rows[e].fields.length;n++){let r=this.rows[e].fields[n],{fieldName:i,granularity:a}=Mu(r),o=this.fieldsType[i]||`char`;t.push({type:o,field:r,value:Lu({displayName:i,type:o,granularity:a},this.rows[e].values[n])})}return t}buildRowsTree(){let e=[],t=0,n={};n[0]=e;for(let r of this.rows){if(r.fields.length===0||r.values.length===0)return e;let i=r.fields.length-1,a=r.fields[i],{fieldName:o,granularity:s}=Mu(a),c=Lu({displayName:o,type:this.fieldsType[o]??`char`,granularity:s},r.values[i]);if(i>t){t=i,n[t]=[];let e=n[t-1].at(-1);e&&(e.children=n[t])}t=i;let l={value:c,field:r.fields[i],children:[],width:0};n[t].push(l)}return e}buildColumnsTree(){let e=[],t=this.columns.at(-2)||[],n={};n[0]=e;for(let e of t)for(let t=0;t<e.fields.length;t++){let r=e.fields[t],{fieldName:i,granularity:a}=Mu(r),o=Lu({displayName:i,type:this.fieldsType[i]??`char`,granularity:a},e.values[t]),s={value:o,field:e.fields[t],children:[],width:e.width};n[t]?.at(-1)?.value!==o&&(n[t+1]=[],s.children=n[t+1],n[t].push(s))}return e}export(){return{cols:this.columns,rows:this.rows,measures:this.measures,fieldsType:this.fieldsType}}};let gF={type:`EMPTY`};function _F(e,t){let n=t.measures.filter(e=>!e.isHidden).map(e=>e.id),r=yF(e,t.columns,0);bF(r,n.length);let i=xF(r,t),a=vF(e,0,t.rows,[],[]);a.push({fields:[],values:[],indent:0});let o={};for(let e of t.columns)o[e.fieldName]=e.type;for(let e of t.rows)o[e.fieldName]=e.type;return new hF(i,a,n,o)}function vF(e,t,n,r,i){if(t>=n.length)return[];let a=n[t],o=a.nameWithGranularity,s=SF(e,a),c=wF(s,a),l=[],u=r.concat(o);for(let e of c){let r=i.concat(e);l.push({fields:u,values:r,indent:t});let a=s[e];a&&l.push(...vF(a,t+1,n,u,r))}return l}function yF(e,t,n){if(n>=t.length)return[];let r=t[n],i=t[n].nameWithGranularity,a=SF(e,r);return wF(a,t[n]).map(e=>({value:a[e]?.[0]?.[r.nameWithGranularity]?.value??null,field:i,children:yF(a[e]||[],t,n+1),width:0}))}function bF(e,t){for(let n in e){let r=e[n];r.children.length===0?r.width=t:(bF(r.children,t),r.width=r.children.reduce((e,t)=>e+t.width,0))}}function xF(e,t){let n=t.columns.map(e=>e.nameWithGranularity),r=n.length,i=t.measures.filter(e=>!e.isHidden),a=i.length,o=Array(r).fill(0).map(()=>[]);function s(e,t,i){let a=o[t];for(let o of e){let e=i.concat([o.value]),c={fields:n.slice(0,t+1),values:e,width:o.width,offset:0};a.push(c),t<=r-1&&s(o.children,t+1,e)}}s(e,0,[]);let c=n.length>0,l=[];return c&&o[o.length-1].forEach(e=>{i.forEach(t=>{let n={fields:[...e.fields,`measure`],values:[...e.values,t.id],width:1,offset:0};l.push(n)})}),i.forEach(e=>{let t={fields:[`measure`],values:[e.id],width:1,offset:0};l.push(t)}),o.push(l),o.length===1&&o.unshift([]),o[o.length-2].push({fields:[],values:[],width:a,offset:0}),o}function SF(e,t){return Object.groupBy(e,CF(t))}function CF(e){let t=e.nameWithGranularity;return e=>`${e[t]?.value??null}`}function wF(e,t){return t.order?Object.keys(e).sort((e,n)=>TF(t,e,n)):Object.keys(e)}function TF(e,t,n){return t===`null`?e.order===`asc`?1:-1:n===`null`?e.order===`asc`?-1:1:e.type===`integer`||e.type===`datetime`?e.order===`asc`?P(t,O)-P(n,O):P(n,O)-P(t,O):e.order===`asc`?t.localeCompare(n):n.localeCompare(t)}let EF=Symbol(`NULL`);function DF(e,t,n){let r=e.granularity||`month`;if(!(r in OF))throw Error(`Unknown date granularity: ${r}`);let i=typeof t==`number`||typeof t==`string`?t:EF;if(!OF[r].set.has(t)){OF[r].set.add(t);let a=null;if(typeof t==`number`||typeof t==`string`){let e=R(t,n);switch(r){case`year`:a=e.getFullYear();break;case`quarter_number`:a=Math.floor(e.getMonth()/3)+1;break;case`month_number`:a=e.getMonth()+1;break;case`month`:a=Math.floor(P(t,n));break;case`iso_week_number`:a=e.getIsoWeek();break;case`day_of_month`:a=e.getDate();break;case`day`:a=Math.floor(P(t,n));break;case`day_of_week`:a=(e.getDay()+7-n.weekStart)%7+1;break;case`hour_number`:a=e.getHours();break;case`minute_number`:a=e.getMinutes();break;case`second_number`:a=e.getSeconds();break}}OF[r].values[i]=Lu(e,a)}return OF[r].values[i]}let OF={year:{set:new Set,values:{}},quarter_number:{set:new Set,values:{}},month_number:{set:new Set,values:{}},month:{set:new Set,values:{}},iso_week_number:{set:new Set,values:{}},day_of_month:{set:new Set,values:{}},day:{set:new Set,values:{}},day_of_week:{set:new Set,values:{}},hour_number:{set:new Set,values:{}},minute_number:{set:new Set,values:{}},second_number:{set:new Set,values:{}}};function kF(){for(let e in OF)OF[e].set.clear(),OF[e].values={}}var AF=class{type=`SPREADSHEET`;getters;_definition;coreDefinition;metaData={fields:{},fieldKeys:[]};dataEntries=[];table;invalidRangeError;needsReevaluation=!0;constructor(e,t){this.getters=t.getters,this.coreDefinition=t.definition}init(e={}){(!this._definition||e.reload)&&(this.reload(4),this.needsReevaluation=!1)}reload(e){e===4&&(this.metaData=this.loadMetaData()),e>=3&&(this._definition=this.loadRuntimeDefinition()),e>=2&&(this.dataEntries=this.loadData()),e>=1&&(this.table=void 0)}onDefinitionChange(e){let t=this.coreDefinition;if(this.coreDefinition=e,this._definition){let n=Math.max(this.computeShouldReload(t,e),0);this.reload(n)}}computeShouldReload(e,t){return C(e.dataSet,t.dataSet)?3:4}get isInvalidRange(){return!!this.invalidRangeError}get invalidRangeMessage(){return this.invalidRangeError?.message}get definition(){if(this._definition||this.init(),!this._definition)throw Error(`Pivot definition should be defined at this point.`);return this._definition}isValid(){if(this.invalidRangeError||!this.definition)return!1;for(let e of this.definition.measures)if(!e.isValid)return!1;for(let e of this.definition.columns)if(!e.isValid)return!1;for(let e of this.definition.rows)if(!e.isValid)return!1;return!0}assertIsValid({throwOnError:e}){if(!this.isValid()){if(e)throw this.invalidRangeError?this.invalidRangeError:new j(T(`At least one measure and/or dimension is not correct.`));return{value:A.GenericError,message:this.invalidRangeError?.message??T(`At least one measure and/or dimension is not correct.`)}}}areDomainArgsFieldsValid(e){let t=e.filter((e,t)=>t%2==0).map(F);return t.length&&t.at(-1)===`measure`&&(t=t.slice(0,-1)),Fu(t,this.definition)}parseArgsToPivotDomain(e){let t=[];for(let n=0;n<e.length-1;n+=2){let r=F(e[n]),i=this.getTypeOfDimension(r),a=r===`measure`?F(e[n+1]):Lu(this.getDimension(r),e[n+1]);t.push({field:r,value:a,type:i})}return t}markAsDirtyForEvaluation(){this.needsReevaluation=!0}getMeasure(e){return this.definition.getMeasure(e)}getPivotMeasureValue(e){return{value:this.getMeasure(e).displayName}}getPivotHeaderValueAndFormat(e){let t=e.at(-1);if(!t)return{value:T(`Total`)};let n=this.getDimension(t.field),r=this.filterDataEntriesFromDomain(this.dataEntries,e)[0]?.[n.nameWithGranularity];return n.type===`datetime`?du(n.granularity||`month`).toValueAndFormat(t.value,this.getters.getLocale()):r?r.value===null?{value:T(`(Undefined)`)}:r:{value:``}}getPivotCellValueAndFormat(e,t){let n=this.filterDataEntriesFromDomain(this.dataEntries,t);if(n.length===0)return{value:``};let r=this.getMeasure(e),i=n.map(e=>e[r.fieldName]).filter(S),a=i.filter(e=>e.type!==`empty`),o=r.aggregator,s=Ou[o];if(!s)throw Error(`Aggregator ${o} does not exist`);try{let e=s([i],this.getters.getLocale());return a.length===0?{...e,value:``}:e}catch(e){return VT(e,o.toUpperCase())}}getPossibleFieldValues(e){let t=[],n=SF(this.dataEntries,e),r=wF(n,e);for(let i of r)t.push({value:n[i]?.[0]?.[e.nameWithGranularity]?.value??``,label:n[i]?.[0]?.[e.nameWithGranularity]?.formattedValue||``});return t}getTableStructure(){if(!this.isValid())throw Error(`Pivot is not valid !`);return this.table||=_F(this.dataEntries,this.definition),this.table}getFields(){return this.metaData.fields}get fields(){return this.getFields()}loadMetaData(){if(this.invalidRangeError=void 0,this.coreDefinition.dataSet){let{zone:e,sheetId:t}=this.coreDefinition.dataSet,n=this.getters.getRangeFromZone(t,e);try{return this.extractFieldsFromRange(n)}catch(e){return this.invalidRangeError=e,{fields:{},fieldKeys:[]}}}else return this.invalidRangeError=new j(T(`The pivot cannot be created because the dataset is missing.`)),{fields:{},fieldKeys:[]}}loadRuntimeDefinition(){return new mF(this.coreDefinition,this.fields,this.getters)}loadData(){let e=this._definition?.range;return this.isValid()&&e?this.extractDataEntriesFromRange(e):[]}getTypeOfDimension(e){if(e===`measure`)return`char`;let{fieldName:t}=Mu(e),n=this.fields[t]?.type;if(!n)throw Error(`Field ${t} does not exist`);return n}filterDataEntriesFromDomain(e,t){return t.reduce((e,t)=>this.filterDataEntriesFromDomainNode(e,t),e)}filterDataEntriesFromDomainNode(e,t){let{field:n,value:r,type:i}=t,{nameWithGranularity:a}=this.getDimension(n);return e.filter(e=>{let t=e[a]?.value;return i===`char`?String(t)===String(r):t===r})}getDimension(e){return this.definition.getDimension(e)}getTypeFromZone(e,t){let n=this.getters.getEvaluatedCellsInZone(e,t).filter(e=>!(e.type===`empty`||e.value===``));return n.length===0?`integer`:n.every(e=>e.type===`number`&&e.format&&Ko(e.format))?`datetime`:n.every(e=>e.type===`boolean`)?`boolean`:n.every(e=>e.type===`number`)?`integer`:`char`}assertCellIsValidField(e,t,n){if(n.type===`error`)throw new j(T(`The pivot cannot be created because cell %s contains an error`,w(e,t)));if(n.type===`empty`||n.value===``)throw new j(T(`The pivot cannot be created because cell %s is empty`,w(e,t)));if(n.value===`__count`)throw new j(T(`The pivot cannot be created because cell %s contains a reserved value`,w(e,t)))}extractFieldsFromRange(e){let t={},n=[],r=e.sheetId,i=e.zone.top;for(let a=e.zone.left;a<=e.zone.right;a++){let o=this.getters.getEvaluatedCell({sheetId:r,col:a,row:i});this.assertCellIsValidField(a,i,o);let s=o.value?.toString();if(s){let i=this.getTypeFromZone(r,{top:e.zone.top+1,left:a,bottom:e.zone.bottom,right:a}),o=this.findName(s,t);t[o]={name:o,type:i,string:o,aggregator:i===`integer`?`sum`:`count`},n.push(o)}}return{fields:t,fieldKeys:n}}findName(e,t){let n=1,r=e;for(;e in t;)e=`${r}${++n}`;return e}extractDataEntriesFromRange(e){let t=[];for(let n=e.zone.top+1;n<=e.zone.bottom;n++){let r={top:n,bottom:n,left:e.zone.left,right:e.zone.right},i=this.getters.getEvaluatedCellsInZone(e.sheetId,r),a={};for(let e in i){let t=i[e],n=this.fields[this.metaData.fieldKeys[e]];if(!n)throw Error(`Field ${this.metaData.fieldKeys[e]} does not exist`);t.value===``?a[n.name]={value:null,type:`empty`,formattedValue:``}:a[n.name]=t}a.__count={value:1,type:`number`,formattedValue:`1`},t.push(a)}let n=this.definition.columns.concat(this.definition.rows).filter(e=>e.type===`datetime`);if(n.length){let e=this.getters.getLocale();for(let r of t)for(let t of n){let n=DF(t,r[t.fieldName]?.value||null,this.getters.getLocale()),{format:i,value:a}=du(t.granularity||`month`).toValueAndFormat(n,e);r[t.nameWithGranularity]={value:n,type:r[t.fieldName]?.type||`empty`,format:r[t.fieldName]?.format,formattedValue:B(a,{locale:e,format:i})}}}return t}};let jF=new h,MF=[`year`,`quarter_number`,`month_number`,`month`,`iso_week_number`,`day_of_month`,`day`,`day_of_week`],NF=[...MF,`hour_number`,`minute_number`,`second_number`];jF.add(`SPREADSHEET`,{ui:AF,definition:mF,dateGranularities:[...MF],datetimeGranularities:[...NF],isMeasureCandidate:e=>![`datetime`,`boolean`].includes(e.type),isGroupable:()=>!0,adaptRanges:(e,t,n)=>{if(t.type!==`SPREADSHEET`||!t.dataSet)return t;let{sheetId:r,zone:i}=t.dataSet,a=e.getRangeFromZone(r,i),o=PF(a,n);if(o===a)return t;let s=o&&{sheetId:o.sheetId,zone:o.zone};return{...t,dataSet:s}}});function PF(e,t){if(!e)return;let n=t(e);switch(n.changeType){case`NONE`:return e;case`REMOVE`:return;default:return n.range}}var FF=class extends gd{pivotId;mutators=[`reset`,`deferUpdates`,`applyUpdate`,`discardPendingUpdate`,`update`];updatesAreDeferred=!1;draft=null;notification=this.get(cP);alreadyNotified=!1;constructor(e,t){super(e),this.pivotId=t}handle(e){switch(e.type){case`UPDATE_PIVOT`:e.pivotId===this.pivotId&&this.getters.getPivot(this.pivotId).init()}}get fields(){return this.pivot.getFields()}get pivot(){return this.getters.getPivot(this.pivotId)}get definition(){let e=jF.get(this.pivot.type).definition;return this.draft?new e(this.draft,this.fields,this.getters):this.pivot.definition}get isDirty(){return!!this.draft}get measureFields(){let e=[{name:`__count`,string:T(`Count`),type:`integer`,aggregator:`sum`}],t=this.fields;for(let n in t){let r=t[n];r&&jF.get(this.pivot.type).isMeasureCandidate(r)&&e.push(r)}return e.sort((e,t)=>e.string.localeCompare(t.string))}get unusedGroupableFields(){let e=[],t=this.fields;for(let n in t){let r=t[n];r&&jF.get(this.pivot.type).isGroupable(r)&&e.push(r)}let{columns:n,rows:r,measures:i}=this.definition,a=i.concat(r).concat(n).map(e=>e.fieldName),o=this.unusedGranularities;return e.filter(e=>Nu(e)?!a.includes(e.name)||o[e.name].size>0:!a.includes(e.name)).sort((e,t)=>e.string.localeCompare(t.string))}get datetimeGranularities(){return jF.get(this.pivot.type).datetimeGranularities}get dateGranularities(){return jF.get(this.pivot.type).dateGranularities}get unusedGranularities(){return this.getUnusedGranularities(this.fields,this.draft??this.getters.getPivotCoreDefinition(this.pivotId))}reset(e){this.pivotId=e,this.updatesAreDeferred=!0,this.draft=null}deferUpdates(e){this.updatesAreDeferred=e,e===!1&&this.draft&&this.applyUpdate()}applyUpdate(){if(this.draft&&(this.model.dispatch(`UPDATE_PIVOT`,{pivotId:this.pivotId,pivot:this.draft}),this.draft=null,!this.alreadyNotified&&this.isUpdatedPivotVisibleInViewportOnlyAsStaticPivot())){let e=`=PIVOT(${this.getters.getPivotFormulaId(this.pivotId)})`;this.alreadyNotified=!0,this.notification.notifyUser({type:`info`,text:T(`Pivot updates only work with dynamic pivot tables. Use %s or re-insert the static pivot from the Data menu.`,e),sticky:!0})}}discardPendingUpdate(){this.draft=null}update(e){let t=this.getters.getPivotCoreDefinition(this.pivotId),n={...t,...this.draft,...e},r={...n,columns:n.columns.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),rows:n.rows.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),measures:n.measures.map(e=>({id:e.id,fieldName:e.fieldName,aggregator:e.aggregator,userDefinedName:e.userDefinedName,computedBy:e.computedBy,isHidden:e.isHidden,format:e.format,display:e.display}))};if(!this.draft&&C(t,r))return;let i=this.addDefaultDateTimeGranularity(this.fields,r);this.draft=i,this.updatesAreDeferred||this.applyUpdate()}isUpdatedPivotVisibleInViewportOnlyAsStaticPivot(){let e=0,t=this.getters.getPivotFormulaId(this.pivotId);for(let n of this.getters.getVisibleCellPositions()){let r=this.getters.getCell(n);if(r?.isFormula){let n=KE(r.compiledFormula.tokens),i=n?.args[0]?.value;if(n&&t===i.toString()){if(n.functionName===`PIVOT`)return!1;e++}}}return e>0}addDefaultDateTimeGranularity(e,t){let{columns:n,rows:r}=t,i=y(n),a=y(r),o=this.getUnusedGranularities(e,t);for(let t of i.concat(a)){let n=e[t.fieldName]?.type;if((n===`date`||n===`datetime`)&&!t.granularity){let e=o[t.fieldName]?.values().next().value;o[t.fieldName]?.delete(e),t.granularity=e}}return{...t,columns:i,rows:a}}getUnusedGranularities(e,t){let{columns:n,rows:r}=t,i=n.concat(r).filter(t=>{let n=e[t.fieldName]?.type;return n===`date`||n===`datetime`}),a={};for(let t of i)a[t.fieldName]=new Set(e[t.fieldName]?.type===`date`?this.dateGranularities:this.datetimeGranularities);for(let e of i)a[e.fieldName].delete(e.granularity);return a}},IF=class extends t.Component{static template=`o-spreadsheet-PivotSpreadsheetSidePanel`;static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:uF,Section:Z,SelectionInput:kN,Checkbox:EN,PivotDeferUpdate:eF,PivotTitleSection:dF};store;state;pivotSidePanelRef=(0,t.useRef)(`pivotSidePanel`);setup(){this.store=ud(FF,this.props.pivotId),this.state=(0,t.useState)({range:void 0,rangeHasChanged:!1})}get shouldDisplayInvalidRangeError(){return this.store.isDirty&&this.state.rangeHasChanged?!1:this.pivot.isInvalidRange}get ranges(){return this.state.range?[this.state.range]:this.definition.range?[this.env.model.getters.getRangeString(this.definition.range,`forceSheetReference`)]:[]}get pivot(){return this.store.pivot}get definition(){return this.store.definition}getScrollableContainerEl(){return this.pivotSidePanelRef.el}onSelectionChanged(e){if(this.state.rangeHasChanged=!0,e.length===0){this.state.range=void 0;return}let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getRangeFromSheetXC(t,e[0]);this.state.range=this.env.model.getters.getRangeString(n,`forceSheetReference`,{useBoundedReference:!0})}onSelectionConfirmed(){if(this.state.range){let e=this.env.model.getters.getRangeFromSheetXC(this.env.model.getters.getActiveSheetId(),this.state.range);if(e.invalidSheetName||e.invalidXc)return;let t={sheetId:e.sheetId,zone:e.zone};this.store.update({dataSet:t}),this.store.applyUpdate()}}flipAxis(){let{rows:e,columns:t}=this.definition;this.onDimensionsUpdated({rows:t,columns:e})}onDimensionsUpdated(e){this.store.update(e)}};let LF=new h;LF.add(`SPREADSHEET`,{editor:IF});var RF=class extends t.Component{static template=`o-spreadsheet-PivotSidePanel`;static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:uF,Section:Z};get sidePanelEditor(){let e=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);if(!e)throw Error(`pivotId does not correspond to a pivot.`);return LF.get(e.type).editor}};H`
|
|
1310
1310
|
.o-checkbox-selection {
|
|
1311
1311
|
max-height: 300px;
|
|
1312
1312
|
}
|
|
@@ -1894,11 +1894,11 @@ stores.inject(MyMetaStore, storeInstance);
|
|
|
1894
1894
|
background: #e7f2f6;
|
|
1895
1895
|
}
|
|
1896
1896
|
}
|
|
1897
|
-
`;var TL=class extends t.Component{static template=`o_spreadsheet.PivotHTMLRenderer`;static components={Checkbox:EN};static props={pivotId:String,onCellClicked:Function};pivot=this.env.model.getters.getPivot(this.props.pivotId);data={columns:[],rows:[],values:[]};state=(0,t.useState)({showMissingValuesOnly:!1});setup(){let e=this.pivot.getTableStructure(),t=this.env.model.getters.getPivotFormulaId(this.props.pivotId);this.data={columns:this._buildColHeaders(t,e),rows:this._buildRowHeaders(t,e),values:this._buildValues(t,e)}}get tracker(){return this.env.model.getters.getPivotPresenceTracker(this.props.pivotId)}getTableData(){if(!this.state.showMissingValuesOnly)return this.data;let e=this.getColumnsIndexes(),t=this.getRowsIndexes();return{columns:this.buildColumnsMissing(e),rows:this.buildRowsMissing(t),values:this.buildValuesMissing(e,t)}}addRecursiveRow(e){let t=this.pivot.getTableStructure().rows,n=[...t[e].values];if(n.length<=1)return[e];n.pop();let r=t.findIndex(e=>JSON.stringify(e.values)===JSON.stringify(n));return[e].concat(this.addRecursiveRow(r))}buildColumnsMissing(e){let t=[];for(let e of this.data.columns){let n=[];for(let t in e)for(let r=0;r<e[t].span;r++)n.push(parseInt(t,10));t.push(n)}for(let n=t[t.length-1].length;n>=0;n--)if(!e.includes(n))for(let e of t)e.splice(n,1);let n=[];for(let e in t){let r=[],i,a=1;for(let n=0;n<t[e].length;n++)i===t[e][n]?a++:(i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),i=t[e][n],a=1);i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),n.push(r)}return n}buildRowsMissing(e){return e.map(e=>this.data.rows[e])}buildValuesMissing(e,t){let n=e.map(()=>[]);for(let r of t)for(let t in e)n[t].push(this.data.values[e[t]][r]);return n}getColumnsIndexes(){let e=new Set;for(let t=0;t<this.data.columns.length;t++){let n=[];for(let e=0;e<this.data.columns[t].length;e++)for(let r=0;r<this.data.columns[t][e].span;r++)n.push(this.data.columns[t][e]);for(let t=0;t<n.length;t++)n[t].isMissing&&e.add(t)}for(let t=0;t<this.data.columns[this.data.columns.length-1].length;t++)this.data.values[t].find(e=>e.isMissing)&&e.add(t);return Array.from(e).sort((e,t)=>e-t)}getRowsIndexes(){let e=new Set;for(let t=0;t<this.data.rows.length;t++){this.data.rows[t].isMissing&&e.add(t);for(let n of this.data.values)n[t].isMissing&&this.addRecursiveRow(t).forEach(t=>e.add(t))}return Array.from(e).sort((e,t)=>e-t)}_buildColHeaders(e,t){let n=[];for(let r of t.columns){let t=[];for(let n of r){let r=[];for(let e=0;e<n.fields.length;e++)r.push({value:n.fields[e]},{value:n.values[e]});let i=this.pivot.parseArgsToPivotDomain(r),a=this.env.model.getters.getLocale();if(i.at(-1)?.field===`measure`){let{value:r,format:o}=this.pivot.getPivotMeasureValue(F(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${Pu(e,i).join(`,`)})`,value:B(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}else{let{value:r,format:o}=this.pivot.getPivotHeaderValueAndFormat(i);t.push({formula:`=PIVOT.HEADER(${Pu(e,i).join(`,`)})`,value:B(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}}n.push(t)}let r=n[n.length-1];return n[n.length-1]=r.map(e=>(e.isMissing||(e.style=`color: #756f6f;`),e)),n}_buildRowHeaders(e,t){let n=[];for(let r of t.rows){let t=[];for(let e=0;e<r.fields.length;e++)t.push({value:r.fields[e]},{value:r.values[e]});let i=this.pivot.parseArgsToPivotDomain(t),{value:a,format:o}=this.pivot.getPivotHeaderValueAndFormat(i),s=this.env.model.getters.getLocale(),c={formula:`=PIVOT.HEADER(${Pu(e,i).join(`,`)})`,value:B(a,{format:o,locale:s}),isMissing:!this.tracker?.isHeaderPresent(i)};r.indent>1&&(c.style=`padding-left: ${r.indent-10}px`),n.push(c)}return n}_buildValues(e,t){let n=[];for(let r of t.columns.at(-1)||[]){let i=[],a=F(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(${Pu(e,o,a).join(`,`)})`,value:B(s,{format:c,locale:l}),isMissing:!this.tracker?.isValuePresent(a,o)})}n.push(i)}return n}},EL=class{static getters=[];history;dispatch;canDispatch;constructor(e,t,n){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}}),this.dispatch=t,this.canDispatch=n}exportForExcel(e){}allowDispatch(e){return`Success`}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map(e=>e.call(this,t)).flat()}chainValidations(...e){return t=>{for(let n of e){let e=n.call(this,t);Array.isArray(e)||(e=[e]);let r=e.filter(e=>e!==`Success`);if(r.length)return r}return`Success`}}checkValidations(e,...t){return this.batchValidations(...t)(e)}},DL=class extends EL{getters;uuidGenerator;constructor({getters:e,stateObserver:t,range:n,dispatch:r,canDispatch:i,uuidGenerator:a}){super(t,r,i),n.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.uuidGenerator=a}import(e){}export(e){}adaptRanges(e,t){}garbageCollectExternalResources(){}},OL=class extends DL{static getters=[`getCellBorder`,`getBordersColors`];borders={};allowDispatch(e){switch(e.type){case`SET_BORDER`:return this.checkBordersUnchanged(e);default:return`Success`}}handle(e){switch(e.type){case`ADD_MERGE`:for(let t of e.target)this.addBordersToMerge(e.sheetId,t);break;case`DUPLICATE_SHEET`:let t=this.borders[e.sheetId];if(t){let n=t.slice().map(e=>e?.slice().map(e=>({...e})));this.history.update(`borders`,e.sheetIdTo,n)}break;case`DELETE_SHEET`:let n={...this.borders};delete n[e.sheetId],this.history.update(`borders`,n);break;case`SET_BORDER`:this.setBorder(e.sheetId,e.col,e.row,e.border);break;case`SET_BORDERS_ON_TARGET`:for(let t of e.target)for(let n=t.top;n<=t.bottom;n++)for(let r=t.left;r<=t.right;r++)this.setBorder(e.sheetId,r,n,e.border);break;case`SET_ZONE_BORDERS`:if(e.border){let t=e.target.map(t=>this.getters.expandZone(e.sheetId,t));this.setBorders(e.sheetId,t,e.border.position,e.border.color===``?void 0:{style:e.border.style||Be.style,color:e.border.color||Be.color})}break;case`CLEAR_FORMATTING`:this.clearBorders(e.sheetId,e.target);break;case`REMOVE_COLUMNS_ROWS`:let r=[...e.elements].sort((e,t)=>t-e);for(let t of ct(r))if(e.dimension===`COL`){if(t[0]>=this.getters.getNumberCols(e.sheetId))for(let n=0;n<this.getters.getNumberRows(e.sheetId);n++)this.history.update(`borders`,e.sheetId,t[0]+1,n,`vertical`,void 0);if(t[t.length-1]===0)for(let t=0;t<this.getters.getNumberRows(e.sheetId);t++)this.history.update(`borders`,e.sheetId,0,t,`vertical`,void 0);let n=this.getters.getColsZone(e.sheetId,t[t.length-1]+1,t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersHorizontally(e.sheetId,t[0]+1,-t.length)}else{if(t[0]>=this.getters.getNumberRows(e.sheetId))for(let n=0;n<this.getters.getNumberCols(e.sheetId);n++)this.history.update(`borders`,e.sheetId,n,t[0]+1,`horizontal`,void 0);if(t[t.length-1]===0)for(let t=0;t<this.getters.getNumberCols(e.sheetId);t++)this.history.update(`borders`,e.sheetId,t,0,`horizontal`,void 0);let n=this.getters.getRowsZone(e.sheetId,t[t.length-1]+1,t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersVertically(e.sheetId,t[0]+1,-t.length)}break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumns(e):this.handleAddRows(e);break}}handleAddColumns(e){let t,n;e.position===`before`?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity,{moveFirstLeftBorder:!0}),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity,{moveFirstLeftBorder:!1}),t=e.base,n=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,n)}handleAddRows(e){let t,n;e.position===`before`?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity,{moveFirstTopBorder:!0}),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity,{moveFirstTopBorder:!1}),t=e.base,n=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,n)}getCellBorder({sheetId:e,col:t,row:n}){let r={top:this.borders[e]?.[t]?.[n]?.horizontal,bottom:this.borders[e]?.[t]?.[n+1]?.horizontal,left:this.borders[e]?.[t]?.[n]?.vertical,right:this.borders[e]?.[t+1]?.[n]?.vertical};return!r.bottom&&!r.left&&!r.right&&!r.top?null:r}getBordersColors(e){let t=[],n=this.borders[e];if(n)for(let e of n.filter(S))for(let n of e)n?.horizontal&&t.push(n.horizontal.color),n?.vertical&&t.push(n.vertical.color);return t}ensureColumnBorderContinuity(e,t,n){let r=x(t+1,n);for(let i=0;i<this.getters.getNumberRows(e);i++){let a=this.getCellBorder({sheetId:e,col:t,row:i}),o=this.getCellBorder({sheetId:e,col:n,row:i});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,n,i,t)}}}ensureRowBorderContinuity(e,t,n){let r=x(t+1,n);for(let i=0;i<this.getters.getNumberCols(e);i++){let a=this.getCellBorder({sheetId:e,col:i,row:t}),o=this.getCellBorder({sheetId:e,col:i,row:n});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,i,n,t)}}}getCommonSides(e,t){let n={};for(let r of[`top`,`bottom`,`left`,`right`])e[r]&&C(e[r],t[r])&&(n[r]=e[r]);return n}getColumnsWithBorders(e){let t=this.borders[e];return t?Object.keys(t).map(e=>parseInt(e,10)):[]}getRowsWithBorders(e){let t=this.borders[e]?.filter(S);if(!t)return[];let n=new Set;for(let e of t)for(let t in e)n.add(parseInt(t,10));return Array.from(n)}getRowsRange(e){return this.borders[e]?x(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,n,{moveFirstLeftBorder:r}={}){this.borders[e]&&(n<0&&this.moveBordersOfColumn(e,t,n,`vertical`,{destructive:!1}),this.getColumnsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(i=>{(i===t&&r||i!==t)&&this.moveBordersOfColumn(e,i,n,`vertical`),this.moveBordersOfColumn(e,i,n,`horizontal`)}))}shiftBordersVertically(e,t,n,{moveFirstTopBorder:r}={}){this.borders[e]&&(n<0&&this.moveBordersOfRow(e,t,n,`horizontal`,{destructive:!1}),this.getRowsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(i=>{(i===t&&r||i!==t)&&this.moveBordersOfRow(e,i,n,`horizontal`),this.moveBordersOfRow(e,i,n,`vertical`)}))}moveBordersOfRow(e,t,n,r,{destructive:i}={destructive:!0}){let a=this.borders[e];a&&this.getColumnsWithBorders(e).forEach(o=>{let s=a[o]?.[t+n]?.[r],c=a[o]?.[t]?.[r];this.history.update(`borders`,e,o,t+n,r,i?c:c||s),this.history.update(`borders`,e,o,t,r,void 0)})}moveBordersOfColumn(e,t,n,r,{destructive:i}={destructive:!0}){let a=this.borders[e];a&&this.getRowsRange(e).forEach(o=>{let s=a[t+n]?.[o]?.[r],c=a[t]?.[o]?.[r];this.history.update(`borders`,e,t+n,o,r,i?c:c||s),this.history.update(`borders`,e,t,o,r,void 0)})}setBorder(e,t,n,r,i=!0){(i||!this.borders?.[e]?.[t]?.[n]?.vertical)&&this.history.update(`borders`,e,t,n,`vertical`,r?.left),(i||!this.borders?.[e]?.[t]?.[n]?.horizontal)&&this.history.update(`borders`,e,t,n,`horizontal`,r?.top),(i||!this.borders?.[e]?.[t+1]?.[n]?.vertical)&&this.history.update(`borders`,e,t+1,n,`vertical`,r?.right),(i||!this.borders?.[e]?.[t]?.[n+1]?.horizontal)&&this.history.update(`borders`,e,t,n+1,`horizontal`,r?.bottom)}clearBorders(e,t){for(let n of Fn(t)){for(let t=n.top;t<=n.bottom;t++){this.history.update(`borders`,e,n.right+1,t,`vertical`,void 0);for(let r=n.left;r<=n.right;r++)this.history.update(`borders`,e,r,t,void 0)}for(let t=n.left;t<=n.right;t++)this.history.update(`borders`,e,t,n.bottom+1,`horizontal`,void 0)}}clearInsideBorders(e,t){for(let n of t)for(let t=n.top;t<=n.bottom;t++)for(let r=n.left;r<=n.right;r++)this.history.update(`borders`,e,r,t,void 0)}addBorder(e,t,n,r){this.setBorder(e,t,n,{...this.getCellBorder({sheetId:e,col:t,row:n}),...r})}setBorders(e,t,n,r){if(n===`clear`)return this.clearBorders(e,t);for(let i of Fn(t)){if(n===`h`||n===`hv`||n===`all`)for(let t=i.top+1;t<=i.bottom;t++)for(let n=i.left;n<=i.right;n++)this.addBorder(e,n,t,{top:r});if(n===`v`||n===`hv`||n===`all`)for(let t=i.top;t<=i.bottom;t++)for(let n=i.left+1;n<=i.right;n++)this.addBorder(e,n,t,{left:r});if(n===`left`||n===`all`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.left,t,{left:r});if(n===`right`||n===`all`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.right+1,t,{left:r});if(n===`top`||n===`all`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.top,{top:r});if(n===`bottom`||n===`all`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.bottom+1,{top:r})}}addBordersToMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t,o=this.getCellBorder({sheetId:e,col:n,row:i}),s=this.getCellBorder({sheetId:e,col:r,row:a});this.clearBorders(e,[t]),o?.top&&this.setBorders(e,[{...t,bottom:i}],`top`,o.top),o?.left&&this.setBorders(e,[{...t,right:n}],`left`,o.left),s?.bottom?this.setBorders(e,[{...t,top:a}],`bottom`,s.bottom):o?.bottom&&this.setBorders(e,[{...t,top:a}],`bottom`,o.bottom),s?.right?this.setBorders(e,[{...t,left:r}],`right`,s.right):o?.right&&this.setBorders(e,[{...t,left:r}],`right`,o.right)}checkBordersUnchanged(e){let t=this.getCellBorder(e),n=!e.border?.bottom&&!e.border?.left&&!e.border?.right&&!e.border?.top;return!t&&n||C(t,e.border)?`NoChanges`:`Success`}import(e){if(Object.keys(e.borders||{}).length)for(let t of e.sheets)for(let n in t.borders){let r=t.borders[n],i=e.borders[r],a=$n(n);for(let e=a.top;e<=a.bottom;e++)for(let n=a.left;n<=a.right;n++)this.setBorder(t.id,n,e,i,!1)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,$n(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=Fr(a,t),s={sheetId:n.id,col:r,row:i};e[o]??=[],e[o].push(s)}}n.borders=Ir(e)}e.borders=t}exportForExcel(e){for(let t of e.sheets)for(let n=0;n<t.colNumber;n++)for(let r=0;r<t.rowNumber;r++){let i=this.getCellBorder({sheetId:t.id,col:n,row:r});if(i){let a=w(n,r);t.cells[a]??={},t.cells[a].border=Fr(i,e.borders)}}}},kL=class{map={};set({sheetId:e,col:t,row:n},r){let i=this.map;i[e]||(i[e]={}),i[e][t]||(i[e][t]={}),i[e][t][n]=r}get({sheetId:e,col:t,row:n}){return this.map[e]?.[t]?.[n]}getSheet(e){return this.map[e]}has({sheetId:e,col:t,row:n}){return this.map[e]?.[t]?.[n]!==void 0}delete({sheetId:e,col:t,row:n}){delete this.map[e]?.[t]?.[n]}keys(){let e=this.map,t=[];for(let n in e)for(let r in e[n])for(let i in e[n][r])t.push({sheetId:n,col:parseInt(r),row:parseInt(i)});return t}keysForSheet(e){let t=this.map[e];if(!t)return[];let n=[];for(let r in t)for(let i in t[r])n.push({sheetId:e,col:parseInt(r),row:parseInt(i)});return n}},AL=class extends DL{static getters=[`zoneToXC`,`getCells`,`getTranslatedCellFormula`,`getCellStyle`,`getCellById`,`getFormulaString`,`getFormulaMovedInSheet`];nextId=1;cells={};adaptRanges(e,t){for(let n of Object.keys(this.cells))for(let r of Object.values(this.cells[n]||{}))if(r.isFormula){for(let i of r.compiledFormula.dependencies)if(!t||i.sheetId===t){let t=e(i);t.changeType!==`NONE`&&this.history.update(`cells`,n,r.id,`compiledFormula`,`dependencies`,r.compiledFormula.dependencies.indexOf(i),t.range)}}}allowDispatch(e){switch(e.type){case`UPDATE_CELL`:return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessUpdateCell);case`CLEAR_CELL`:return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessClearCell);case`UPDATE_CELL_POSITION`:return!e.cellId||this.cells[e.sheetId]?.[e.cellId]?`Success`:`InvalidCellId`;default:return`Success`}}handle(e){switch(e.type){case`SET_FORMATTING`:`style`in e&&this.setStyle(e.sheetId,e.target,e.style),`format`in e&&e.format!==void 0&&this.setFormatter(e.sheetId,e.target,e.format);break;case`CLEAR_FORMATTING`:this.clearFormatting(e.sheetId,e.target);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case`UPDATE_CELL`:this.updateCell(e.sheetId,e.col,e.row,e);break;case`CLEAR_CELL`:this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col,row:e.row,content:``,style:null,format:``});break;case`CLEAR_CELLS`:this.clearCells(e.sheetId,e.target);break;case`DELETE_CONTENT`:this.clearZones(e.sheetId,e.target);break;case`DELETE_SHEET`:this.history.update(`cells`,e.sheetId,void 0)}}clearZones(e,t){for(let n of Fn(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.getters.getCell({sheetId:e,col:t,row:r})&&this.dispatch(`UPDATE_CELL`,{sheetId:e,content:``,col:t,row:r})}setFormatter(e,t,n){for(let r of Fn(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 Fn(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,style:null,format:``})}clearCells(e,t){for(let n of t)for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,content:``,style:null,format:``})}handleAddColumnsRows(e,t){let n,r;e.position===`before`?(n=x(e.base,e.base+e.quantity),r=e.base+e.quantity):(n=x(e.base+1,e.base+e.quantity+1),r=e.base),t(e.sheetId,r,n)}import(e){for(let t of e.sheets){let n=t.id,r=new kL;for(let e in t.cells)if(t.cells[e]?.content){let{col:n,row:i}=Pn(e),a={sheetId:t.id,col:n,row:i};r.set(a,{content:t.cells[e]?.content})}for(let[e,i]of[[`style`,t.styles],[`format`,t.formats]])for(let t in i){let a=i[t],o=$n(t);for(let t=o.top;t<=o.bottom;t++)for(let i=o.left;i<=o.right;i++){let o={sheetId:n,col:i,row:t},s=r.get(o);s?s[e]=a:r.set(o,{[e]:a})}}for(let i of r.keysForSheet(n)){let n=r.get(i);if(n?.content||n?.format||n?.style){let r=this.importCell(t.id,n?.content,n?.style?e.styles[n?.style]:void 0,n?.format?e.formats[n?.format]:void 0);this.history.update(`cells`,t.id,r.id,r),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:r.id,...i})}}}}export(e){let t={},n={};for(let r of e.sheets){let e=[],i=[],a={},o=Object.keys(this.cells[r.id]||{}).map(e=>this.getters.getCellPosition(e)).sort((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col);for(let r of o){let o=this.getters.getCell(r),s=w(r.col,r.row),c=this.extractCustomStyle(o);if(Object.keys(c).length){let n=Fr(c,t);e[n]??=[],e[n].push(r)}if(o.format){let e=Fr(o.format,n);i[e]??=[],i[e].push(r)}o.content&&(a[s]={content:o.content})}r.styles=Ir(e),r.formats=Ir(i),r.cells=a}e.styles=t,e.formats=n}importCell(e,t,n,r){let i=this.getNextUid();return this.createCell(i,t||``,r,n,e)}exportForExcel(e){this.export(e);for(let t of e.sheets)for(let n in this.getters.getCells(t.id)){let{col:r,row:i}=this.getters.getCellPosition(n),a=w(r,i),o=this.getCellById(n);t.cells[a]??={},o?.format&&(t.cells[a].format=Fr(o.format,e.formats)),o?.style&&(t.cells[a]??={},t.cells[a].style=Fr(this.extractCustomStyle(o),e.styles))}let t=[];for(let n in e.formats||[])ps(e.formats[n])||(t.push(n),delete e.formats[n]);if(t.length)for(let n of e.sheets)for(let e in n.cells){let r=n.cells[e],i=r?.format;i&&t.includes(i.toString())&&delete r.format}}extractCustomStyle(e){let t={...e.style},n=ki(e.content,O)?Fe:Pe;for(let r in t)(r!==`align`||!e.isFormula)&&t[r]===n[r]&&delete t[r];return t}getCells(e){return this.cells[e]||{}}getCellById(e){let t=this.getters.getCellPosition(e);return this.cells[t.sheetId][e]}getFormulaString(e,t,n,r=!1){if(!n.length)return Tt(t.map(e=>e.value));let i=0;return Tt(t.map(t=>{if(t.type===`REFERENCE`){let t=n[i++];return this.getters.getRangeString(t,e,{useBoundedReference:r})}return t.value}))}getTranslatedCellFormula(e,t,n,r){let i=this.getters.createAdaptedRanges(AE(r).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),t,n,e);return this.getFormulaString(e,r,i)}getFormulaMovedInSheet(e,t,n){let r=AE(n).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),i=this.getters.removeRangesSheetPrefix(t,r);return this.getFormulaString(t,n,i)}getCellStyle(e){return this.getters.getCell(e)?.style||{}}zoneToXC(e,t,n=[{colFixed:!1,rowFixed:!1}]){t=this.getters.expandZone(e,t);let r=w(t.left,t.top,n[0]),i=w(t.right,t.bottom,n.length>1?n[1]:n[0]),a=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),o=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),s=a.col===o.col&&a.row===o.row;return r!==i&&!s?r+`:`+i:r}setStyle(e,t,n){for(let r of Fn(t))for(let t=r.left;t<=r.right;t++)for(let i=r.top;i<=r.bottom;i++){let r=this.getters.getCell({sheetId:e,col:t,row:i});this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:i,style:n?{...r?.style,...n}:void 0})}}copyColumnStyle(e,t,n){for(let r=0;r<this.getters.getNumberRows(e);r++){let i=this.getFormat(e,t,r);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,...i})}}copyRowStyle(e,t,n){for(let r=0;r<this.getters.getNumberCols(e);r++){let i=this.getFormat(e,r,t);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:r,row:t,...i})}}getFormat(e,t,n){let r={},i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.getters.getCell(i);return a&&(a.style&&(r.style=a.style),a.format&&(r.format=a.format)),r}getNextUid(){let e=this.nextId.toString();return this.history.update(`nextId`,this.nextId+1),e}updateCell(e,t,n,r){let i=this.getters.getCell({sheetId:e,col:t,row:n}),a=r.content!==void 0||`formula`in r,o=a?It(r?.content||void 0):i?.content||``,s;s=r.style===void 0?i?i.style:void 0:r.style||void 0;let c=r.format===void 0?i&&i.format:r.format;if((a&&!o&&!r.formula||!a&&(!i||i.content===``))&&!s&&!c){i&&(this.history.update(`cells`,e,i.id,void 0),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:void 0,col:t,row:n,sheetId:e}));return}let l=i?.id||this.getNextUid(),u=this.createCell(l,o,c,s,e);this.history.update(`cells`,e,u.id,u),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:u.id,col:t,row:n,sheetId:e})}createCell(e,t,n,r,i){return t.startsWith(`=`)?this.createFormulaCell(e,t,n,r,i):this.createLiteralCell(e,t,n,r)}createLiteralCell(e,t,n,r){let i=this.getters.getLocale(),a=gs(t,i);return n||=typeof a==`number`?Zo(t,i)||Qo(t):void 0,!ms(n)&&!N(t)&&(t=F(a)),{id:e,content:t,style:r,format:n,isFormula:!1,parsedValue:a}}createFormulaCell(e,t,n,r,i){let a=kE(t);return a.dependencies.length?this.createFormulaCellWithDependencies(e,a,n,r,i):{id:e,content:t,style:r,format:n,isFormula:!0,compiledFormula:{...a,dependencies:[]}}}createFormulaCellWithDependencies(e,t,n,r,i){let a=[];for(let e of t.dependencies)a.push(this.getters.getRangeFromSheetXC(i,e));return new jL(e,t,n,r,a,i,this.getters.getRangeString)}checkCellOutOfSheet(e){let{sheetId:t,col:n,row:r}=e;return this.getters.tryGetSheet(t)?fr(n,r,this.getters.getSheetZone(t))?`Success`:`TargetOutOfSheet`:`InvalidSheetId`}checkUselessClearCell(e){let t=this.getters.getCell(e);return!t||!t.content&&!t.style&&!t.format?`NoChanges`:`Success`}checkUselessUpdateCell(e){let t=this.getters.getCell(e),n=`content`in e||`formula`in e,r=`style`in e,i=`format`in e;return(!n||t?.content===e.content)&&(!r||C(t?.style,e.style))&&(!i||t?.format===e.format)?`NoChanges`:`Success`}},jL=class{id;format;style;sheetId;getRangeString;isFormula=!0;compiledFormula;constructor(e,t,n,r,i,a,o){this.id=e,this.format=n,this.style=r,this.sheetId=a,this.getRangeString=o;let s=0,c=t.tokens.map(e=>e.type===`REFERENCE`?new ML(i,s++,this.sheetId,this.getRangeString):e);this.compiledFormula={...t,dependencies:i,tokens:c}}get content(){return Tt(this.compiledFormula.tokens.map(e=>e.value))}get contentWithFixedReferences(){let e=0;return Tt(this.compiledFormula.tokens.map(t=>{if(t.type===`REFERENCE`){let t=e++;return this.getRangeString(this.compiledFormula.dependencies[t],this.sheetId,{useBoundedReference:!0})}return t.value}))}},ML=class{ranges;rangeIndex;sheetId;getRangeString;type=`REFERENCE`;constructor(e,t,n,r){this.ranges=e,this.rangeIndex=t,this.sheetId=n,this.getRangeString=r}get value(){let e=this.ranges[this.rangeIndex];return this.getRangeString(e,this.sheetId)}},NL=class extends DL{static getters=[`isChartDefined`,`getChartDefinition`,`getChartType`,`getChartIds`,`getChart`,`getContextCreationChart`];charts={};createChart=gk(this.getters);validateChartDefinition=e=>vk(this,e.definition);adaptRanges(e){for(let[t,n]of Object.entries(this.charts))this.history.update(`charts`,t,n?.updateRanges(e))}allowDispatch(e){switch(e.type){case`CREATE_CHART`:return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartDuplicate));case`UPDATE_CHART`:return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartExists));default:return`Success`}}handle(e){switch(e.type){case`CREATE_CHART`:this.addFigure(e.id,e.sheetId,e.position,e.size),this.addChart(e.id,e.definition);break;case`UPDATE_CHART`:this.addChart(e.id,e.definition);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`chart`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.charts[n.id]?.copyForSheetId(e.sheetIdTo);i&&this.dispatch(`CREATE_CHART`,{id:r,position:{x:n.x,y:n.y},size:{width:n.width,height:n.height},definition:i.getDefinition(),sheetId:e.sheetIdTo})}break}case`DELETE_FIGURE`:this.history.update(`charts`,e.id,void 0);break;case`DELETE_SHEET`:for(let t of this.getChartIds(e.sheetId))this.history.update(`charts`,t,void 0);break}}getContextCreationChart(e){return this.charts[e]?.getContextCreation()}getChart(e){return this.charts[e]}getChartType(e){let t=this.charts[e]?.type;if(!t)throw Error(`Chart not defined.`);return t}isChartDefined(e){return e in this.charts&&this.charts!==void 0}getChartIds(e){return Object.entries(this.charts).filter(([,t])=>t?.sheetId===e).map(([e])=>e)}getChartDefinition(e){let t=this.charts[e]?.getDefinition();if(!t)throw Error(`There is no chart with the given figureId: ${e}`);return t}import(e){for(let t of e.sheets)if(t.figures)for(let e of t.figures)e.tag===`chart`&&(this.charts[e.id]=this.createChart(e.id,e.data,t.id))}export(e){if(e.sheets)for(let t of e.sheets){let e=this.getters.getFigures(t.id),n=[];for(let t of e){let e=t;if(e&&e.tag===`chart`){let t=this.charts[e.id]?.getDefinition();t&&(e.data=t,n.push(e))}else n.push(e)}t.figures=n}}addFigure(e,t,n={x:0,y:0},r={width:536,height:335}){if(this.getters.getFigure(t,e))return;let i={id:e,x:n.x,y:n.y,width:r.width,height:r.height,tag:`chart`};this.dispatch(`CREATE_FIGURE`,{sheetId:t,figure:i})}addChart(e,t){let n=this.getters.getFigureSheetId(e);n&&this.history.update(`charts`,e,this.createChart(e,t,n))}checkChartDuplicate(e){return this.getters.getFigureSheetId(e.id)?`DuplicatedChartId`:`Success`}checkChartExists(e){return this.isChartDefined(e.id)?`Success`:`ChartDoesNotExist`}};function PL(e){return e===``?NaN:Number(e)}var FL=class extends DL{static getters=[`getConditionalFormats`,`getRulesSelection`,`getRulesByCell`,`getAdaptedCfRanges`];cfRules={};loopThroughRangesOfSheet(e,t){for(let n of this.cfRules[e]){if(n.rule.type===`DataBarRule`&&n.rule.rangeValues){let r=t(n.rule.rangeValues);switch(r.changeType){case`REMOVE`:this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`rule`,`rangeValues`,void 0);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`rule`,`rangeValues`,r.range);break}}for(let r of n.ranges){let i=t(r);switch(i.changeType){case`REMOVE`:let t=n.ranges.slice();t.splice(n.ranges.indexOf(r),1),t.length>=1?this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,t):this.removeConditionalFormatting(n.id,e);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,n.ranges.indexOf(r),i.range);break}}}}adaptRanges(e,t){if(t)this.loopThroughRangesOfSheet(t,e);else for(let t of Object.keys(this.cfRules))this.loopThroughRangesOfSheet(t,e)}allowDispatch(e){switch(e.type){case`ADD_CONDITIONAL_FORMAT`:return this.checkValidations(e,this.checkCFRule,this.checkEmptyRange);case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:return this.checkValidPriorityChange(e.cfId,e.delta,e.sheetId)}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.cfRules[e.sheetId]=[];break;case`DUPLICATE_SHEET`:this.history.update(`cfRules`,e.sheetIdTo,[]);for(let t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case`DELETE_SHEET`:let t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update(`cfRules`,t);break;case`ADD_CONDITIONAL_FORMAT`:let n={...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))};this.addConditionalFormatting(n,e.sheetId);break;case`REMOVE_CONDITIONAL_FORMAT`:this.removeConditionalFormatting(e.id,e.sheetId);break;case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:this.changeCFPriority(e.cfId,e.delta,e.sheetId);break}}import(e){for(let t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map(e=>this.mapToConditionalFormatInternal(t.id,e))}export(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e)))}exportForExcel(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e,{useBoundedReference:!0})))}getConditionalFormats(e){return this.cfRules[e]?.map(t=>this.mapToConditionalFormat(e,t))||[]}getRulesSelection(e,t){let n=new Set;return t.forEach(t=>{this.getRulesByZone(e,t).forEach(e=>{n.add(e)})}),Array.from(n)}getRulesByZone(e,t){let n=new Set;for(let r=t.top;r<=t.bottom;r++)for(let i=t.left;i<=t.right;i++)this.getRulesByCell(e,i,r).forEach(e=>{n.add(e.id)});return n}getRulesByCell(e,t,n){let r=[];for(let i of this.cfRules[e])for(let e of i.ranges)fr(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(Qn));let s=Fn(o,r);return Fn([...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 ag[t.operator]?this.checkValidations(t,this.checkOperatorArgsNumber(2,[`Between`,`NotBetween`]),this.checkOperatorArgsNumber(1,[`BeginsWith`,`ContainsText`,`EndsWith`,`GreaterThan`,`GreaterThanOrEqual`,`LessThan`,`LessThanOrEqual`,`NotContains`,`Equal`,`NotEqual`]),this.checkOperatorArgsNumber(0,[`IsEmpty`,`IsNotEmpty`]),this.checkCFValues):`InvalidConditionalFormatType`;case`ColorScaleRule`:return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case`IconSetRule`:return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)));case`DataBarRule`:return`Success`}return`InvalidConditionalFormatType`}checkOperatorArgsNumber(e,t){if(e>2)throw Error(`Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.`);return n=>{if(t.includes(n.operator)){let t=[],r=e=>e===void 0||e===``;return e>=1&&r(n.values[0])&&t.push(`FirstArgMissing`),e>=2&&r(n.values[1])&&t.push(`SecondArgMissing`),t.length?t:`Success`}return`Success`}}checkNaN(e,t){if([`number`,`percentage`,`percentile`].includes(e.type)&&(e.value===``||isNaN(e.value)))switch(t){case`min`:return`MinNaN`;case`max`:return`MaxNaN`;case`mid`:return`MidNaN`;case`upperInflectionPoint`:return`ValueUpperInflectionNaN`;case`lowerInflectionPoint`:return`ValueLowerInflectionNaN`}return`Success`}checkFormulaCompilation(e,t){if(e.type!==`formula`)return`Success`;if(kE(e.value||``).isBadExpression)switch(t){case`min`:return`MinInvalidFormula`;case`max`:return`MaxInvalidFormula`;case`mid`:return`MidInvalidFormula`;case`upperInflectionPoint`:return`ValueUpperInvalidFormula`;case`lowerInflectionPoint`:return`ValueLowerInvalidFormula`}return`Success`}checkThresholds(e){return this.batchValidations(t=>e(t.minimum,`min`),t=>e(t.maximum,`max`),t=>t.midpoint?e(t.midpoint,`mid`):`Success`)}checkInflectionPoints(e){return this.batchValidations(t=>e(t.lowerInflectionPoint,`lowerInflectionPoint`),t=>e(t.upperInflectionPoint,`upperInflectionPoint`))}checkLowerBiggerThanUpper(e){let t=e.lowerInflectionPoint.value,n=e.upperInflectionPoint.value;return[`number`,`percentage`,`percentile`].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(n)?`LowerBiggerThanUpper`:`Success`}checkMinBiggerThanMax(e){let t=e.minimum.value,n=e.maximum.value;return[`number`,`percentage`,`percentile`].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&PL(t)>=PL(n)?`MinBiggerThanMax`:`Success`}checkMidBiggerThanMax(e){let t=e.midpoint?.value,n=e.maximum.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&PL(t)>=PL(n)?`MidBiggerThanMax`:`Success`}checkMinBiggerThanMid(e){let t=e.minimum.value,n=e.midpoint?.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&PL(t)>=PL(n)?`MinBiggerThanMid`:`Success`}checkCFValues(e){for(let t of e.values)if(t.startsWith(`=`)&&kE(t||``).isBadExpression)return`ValueCellIsInvalidFormula`;return`Success`}removeConditionalFormatting(e,t){let n=this.cfRules[t].findIndex(t=>t.id===e);if(n!==-1){let e=this.cfRules[t].slice();e.splice(n,1),this.history.update(`cfRules`,t,e)}}changeCFPriority(e,t,n){let r=this.cfRules[n].findIndex(t=>t.id===e),i=this.cfRules[n][r],a=r-t,o=[...this.cfRules[n]];o.splice(r,1),o.splice(a,0,i),this.history.update(`cfRules`,n,o)}},IL=class extends DL{static getters=[`cellHasListDataValidationIcon`,`getDataValidationRule`,`getDataValidationRules`,`getValidationRuleForCell`];rules={};adaptRanges(e,t){let n=t?[t]:Object.keys(this.rules);for(let t of n)this.loopThroughRangesOfSheet(t,e)}loopThroughRangesOfSheet(e,t){let n=this.rules[e];for(let r=n.length-1;r>=0;r--){let n=this.rules[e][r];for(let i=n.ranges.length-1;i>=0;i--){let a=n.ranges[i],o=t(a);switch(o.changeType){case`REMOVE`:if(n.ranges.length===1)this.removeDataValidationRule(e,n.id);else{let t=n.ranges.slice();t.splice(i,1),this.history.update(`rules`,e,r,`ranges`,t)}break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`rules`,e,r,`ranges`,i,o.range);break}}}}allowDispatch(e){switch(e.type){case`ADD_DATA_VALIDATION_RULE`:return this.getters.tryGetSheet(e.sheetId)?this.checkValidations(e,this.chainValidations(this.checkEmptyRange,this.checkCriterionTypeIsValid,this.checkCriterionHasValidNumberOfValues,this.checkCriterionValuesAreValid)):`InvalidSheetId`;case`REMOVE_DATA_VALIDATION_RULE`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;if(!this.rules[e.sheetId].find(t=>t.id===e.id))return`UnknownDataValidationRule`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`rules`,e.sheetId,[]);break;case`DUPLICATE_SHEET`:{let t=y(this.rules[e.sheetId]).map(t=>({...t,ranges:t.ranges.map(t=>Gs(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=Fn(e.target),n=e.sheetId;for(let e of t)for(let t=e.top;t<=e.bottom;t++)for(let r=e.left;r<=e.right;r++){let e=this.getValidationRuleForCell({sheetId:n,col:r,row:t});if(e&&(e.criterion.type===`isBoolean`||e.criterion.type===`isValueInList`&&!this.getters.getCell({sheetId:n,col:r,row:t})?.content)){let e=this.rules[n],i=[this.getters.getRangeFromSheetXC(n,w(r,t))],a=this.removeRangesFromRules(n,i,e);this.history.update(`rules`,n,a)}}}}}getDataValidationRules(e){return this.rules[e]}getDataValidationRule(e,t){return this.rules[e].find(e=>e.id===t)}getValidationRuleForCell({sheetId:e,col:t,row:n}){if(this.rules[e]){for(let r of this.rules[e])for(let e of r.ranges)if(fr(t,n,e.zone))return r}}cellHasListDataValidationIcon(e){let t=this.getValidationRuleForCell(e);return t?(t.criterion.type===`isValueInList`||t.criterion.type===`isValueInRange`)&&t.criterion.displayStyle===`arrow`:!1}addDataValidationRule(e,t){let n=this.rules[e];t.criterion.type===`isBoolean`?this.setCenterStyleToBooleanCells(t):t.criterion.type===`isValueInList`&&(t.criterion.values=Array.from(new Set(t.criterion.values)));let r=this.removeRangesFromRules(e,t.ranges,n,t.id),i=r.findIndex(e=>e.id===t.id);i===-1?this.history.update(`rules`,e,[...r,t]):(r[i]=t,this.history.update(`rules`,e,r))}removeRangesFromRules(e,t,n,r){n=y(n);for(let e of n)e.id!==r&&(e.ranges=this.getters.recomputeRanges(e.ranges,t));return n.filter(e=>e.ranges.length>0)}removeDataValidationRule(e,t){let n=this.rules[e].filter(e=>e.id!==t);this.history.update(`rules`,e,n)}setCenterStyleToBooleanCells(e){for(let t of Js(e.ranges)){let e=this.getters.getCell(t),n={...e?.style,align:e?.style?.align??`center`,verticalAlign:e?.style?.verticalAlign??`middle`};this.dispatch(`UPDATE_CELL`,{...t,style:n})}}checkEmptyRange(e){return e.ranges.length?`Success`:`EmptyRange`}import(e){for(let t of e.sheets)if(this.rules[t.id]=[],t.dataValidationRules)for(let e of t.dataValidationRules)this.rules[t.id].push({...e,ranges:e.ranges.map(e=>this.getters.getRangeFromSheetXC(t.id,e))})}export(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id])t.dataValidationRules.push({...e,ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id))})}}exportForExcel(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id]){let n={...y(e),ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id,{useBoundedReference:!0}))};e.criterion.type===`isValueInRange`&&(n.criterion.values=e.criterion.values.map(e=>{let n=this.getters.getRangeFromSheetXC(t.id,e);return this.getters.getRangeString(n,t.id,{useBoundedReference:!0,useFixedReference:!0})})),t.dataValidationRules.push(n)}}}checkCriterionTypeIsValid(e){return Q.contains(e.rule.criterion.type)?`Success`:`UnknownDataValidationCriterionType`}checkCriterionHasValidNumberOfValues(e){let t=e.rule.criterion,n=Q.get(t.type).numberOfValues(t);return n!==void 0&&t.values.length!==n?`InvalidNumberOfCriterionValues`:`Success`}checkCriterionValuesAreValid(e){let t=e.rule.criterion,n=Q.get(t.type);return t.values.some(e=>e.startsWith(`=`)?n.allowedValues===`onlyLiterals`:n.allowedValues===`onlyFormulas`?!0:!n.isCriterionValueValid(e))?`InvalidDataValidationCriterionValue`:`Success`}},LL=class extends DL{static getters=[`getFigures`,`getFigure`,`getFigureSheetId`];figures={};insertionOrders=[];allowDispatch(e){switch(e.type){case`CREATE_FIGURE`:return this.checkFigureDuplicate(e.figure.id);case`UPDATE_FIGURE`:case`DELETE_FIGURE`:return this.checkFigureExists(e.sheetId,e.id);default:return`Success`}}beforeHandle(e){switch(e.type){case`DELETE_SHEET`:this.getters.getFigures(e.sheetId).forEach(t=>{this.dispatch(`DELETE_FIGURE`,{id:t.id,sheetId:e.sheetId})});break}}handle(e){switch(e.type){case`CREATE_SHEET`:this.figures[e.sheetId]={};break;case`DELETE_SHEET`:this.deleteSheet(e.sheetId);break;case`CREATE_FIGURE`:this.addFigure(e.figure,e.sheetId);break;case`UPDATE_FIGURE`:let{type:t,sheetId:n,...r}=e,i=r;this.updateFigure(n,i);break;case`DELETE_FIGURE`:this.removeFigure(e.id,e.sheetId);break;case`REMOVE_COLUMNS_ROWS`:this.onRowColDelete(e.sheetId,e.dimension)}}onRowColDelete(e,t){t===`ROW`?this.onRowDeletion(e):this.onColDeletion(e)}onRowDeletion(e){let t=this.getters.getNumberRows(e),n=0;for(let r=0;r<t;r++)n+=this.getters.getUserRowSize(e,r)||23;let r=this.getters.getFigures(e);for(let t of r){let r=Math.min(t.y,n-t.height);r!==t.y&&this.dispatch(`UPDATE_FIGURE`,{sheetId:e,id:t.id,y:r})}}onColDeletion(e){let t=this.getters.getNumberCols(e),n=0;for(let r=0;r<t;r++)n+=this.getters.getColSize(e,r);let r=this.getters.getFigures(e);for(let t of r){let r=Math.min(t.x,n-t.width);r!==t.x&&this.dispatch(`UPDATE_FIGURE`,{sheetId:e,id:t.id,x:r})}}updateFigure(e,t){if(`id`in t)for(let[n,r]of Object.entries(t))switch(n){case`x`:case`y`:r!==void 0&&this.history.update(`figures`,e,t.id,n,Math.max(r,0));break;case`width`:case`height`:r!==void 0&&this.history.update(`figures`,e,t.id,n,r);break}}addFigure(e,t){this.history.update(`figures`,t,e.id,e),this.history.update(`insertionOrders`,this.insertionOrders.length,e.id)}deleteSheet(e){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>!this.figures[e]?.[t])),this.history.update(`figures`,e,void 0)}removeFigure(e,t){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>t!==e)),this.history.update(`figures`,t,e,void 0)}checkFigureExists(e,t){return this.figures[e]?.[t]===void 0?`FigureDoesNotExist`:`Success`}checkFigureDuplicate(e){return Object.values(this.figures).find(t=>t?.[e])?`DuplicatedFigureId`:`Success`}getFigures(e){let t=[];for(let n of this.insertionOrders){let r=this.figures[e]?.[n];r&&t.push(r)}return t}getFigure(e,t){return this.figures[e]?.[t]}getFigureSheetId(e){return Object.keys(this.figures).find(t=>this.figures[t]?.[e]!==void 0)}import(e){for(let t of e.sheets)for(let e of t.figures)this.addFigure(e,t.id)}export(e){for(let t of e.sheets)for(let e of this.getFigures(t.id))t.figures.push({...e,data:void 0})}exportForExcel(e){this.export(e)}},RL=class extends DL{static getters=[`getUserRowSize`,`getColSize`];sizes={};handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`sizes`,e.sheetId,{COL:Array(this.getters.getNumberCols(e.sheetId)).fill(void 0),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(void 0)});break;case`DUPLICATE_SHEET`:this.history.update(`sizes`,e.sheetIdTo,y(this.sizes[e.sheetId]));break;case`DELETE_SHEET`:let t={...this.sizes};delete t[e.sheetId],this.history.update(`sizes`,t);break;case`REMOVE_COLUMNS_ROWS`:{let t=this.sizes[e.sheetId][e.dimension],n=zt(t,e.elements);this.history.update(`sizes`,e.sheetId,e.dimension,n);break}case`ADD_COLUMNS_ROWS`:{let t=[...this.sizes[e.sheetId][e.dimension]],n=Ot(e.position,e.base),r=t[e.base];t=Bt(t,Array(e.quantity).fill(r),n),this.history.update(`sizes`,e.sheetId,e.dimension,t);break}case`RESIZE_COLUMNS_ROWS`:if(e.dimension===`ROW`)for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);else for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);break}}getColSize(e,t){return Math.round(this.sizes[e]?.COL[t]||96)}getUserRowSize(e,t){let n=this.sizes[e]?.ROW[t];return n?Math.round(n):void 0}import(e){for(let t of e.sheets){let e={COL:Array(t.colNumber).fill(void 0),ROW:Array(t.rowNumber).fill(void 0)};for(let[n,r]of Object.entries(t.rows))r.size&&(e.ROW[n]=r.size);for(let[n,r]of Object.entries(t.cols))r.size&&(e.COL[n]=r.size);this.sizes[t.id]=e}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e of x(0,this.getters.getNumberRows(n.id)))(t||this.sizes[n.id].ROW[e])&&(n.rows[e]={...n.rows[e],size:this.getUserRowSize(n.id,e)??23});n.cols===void 0&&(n.cols={});for(let e of x(0,this.getters.getNumberCols(n.id)))(t||this.sizes[n.id].COL[e])&&(n.cols[e]={...n.cols[e],size:this.getColSize(n.id,e)})}}},zL=class extends DL{static getters=[`checkElementsIncludeAllVisibleHeaders`,`getHiddenColsGroups`,`getHiddenRowsGroups`,`isHeaderHiddenByUser`,`isRowHiddenByUser`,`isColHiddenByUser`];hiddenHeaders={};allowDispatch(e){switch(e.type){case`HIDE_COLUMNS_ROWS`:{if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=e.dimension===`COL`?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),n=e.dimension===`COL`?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=n?`TooManyHiddenElements`:Kt(e.elements)<0||Gt(e.elements)>n?`InvalidHeaderIndex`:`Success`}case`REMOVE_COLUMNS_ROWS`:return this.getters.tryGetSheet(e.sheetId)?this.checkElementsIncludeAllVisibleHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`:`InvalidSheetId`}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:let t={COL:Array(this.getters.getNumberCols(e.sheetId)).fill(!1),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(!1)};this.history.update(`hiddenHeaders`,e.sheetId,t);break;case`DUPLICATE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetIdTo,y(this.hiddenHeaders[e.sheetId]));break;case`DELETE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetId,void 0);break;case`REMOVE_COLUMNS_ROWS`:{let t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(let n of[...e.elements].sort((e,t)=>t-e))t.splice(n,1);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t);break}case`ADD_COLUMNS_ROWS`:{let t=Ot(e.position,e.base),n=Bt([...this.hiddenHeaders[e.sheetId][e.dimension]],Array(e.quantity).fill(!1),t);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,n);break}case`HIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!0);break;case`UNHIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!1);break}}checkElementsIncludeAllVisibleHeaders(e,t,n){return At(n,this.getAllVisibleHeaders(e,t))}isHeaderHiddenByUser(e,t,n){return t===`COL`?this.isColHiddenByUser(e,n):this.isRowHiddenByUser(e,n)}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]||this.getters.isRowFolded(e,t)}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]||this.getters.isColFolded(e,t)}getHiddenColsGroups(e){let t=[[]],n=this.hiddenHeaders[e].COL;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getHiddenRowsGroups(e){let t=[[]],n=this.hiddenHeaders[e].ROW;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getAllVisibleHeaders(e,t){let n=x(0,this.getters.getNumberHeaders(e,t)),r=[];return this.getters.getHeaderGroups(e,t).forEach(e=>{e.isFolded&&r.push(...x(e.start,e.end+1))}),n.filter(n=>!this.hiddenHeaders[e][t][n]&&!r.includes(n))}import(e){for(let t of e.sheets){this.hiddenHeaders[t.id]={COL:[],ROW:[]};for(let e=0;e<t.rowNumber;e++)this.hiddenHeaders[t.id].ROW[e]=!!t.rows[e]?.isHidden;for(let e=0;e<t.colNumber;e++)this.hiddenHeaders[t.id].COL[e]=!!t.cols[e]?.isHidden}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e=0;e<this.getters.getNumberRows(n.id);e++)(t||this.hiddenHeaders[n.id].ROW[e])&&(n.rows[e]===void 0&&(n.rows[e]={}),n.rows[e].isHidden||=this.hiddenHeaders[n.id].ROW[e]);n.cols===void 0&&(n.cols={});for(let e=0;e<this.getters.getNumberCols(n.id);e++)(t||this.hiddenHeaders[n.id].COL[e])&&(n.cols[e]===void 0&&(n.cols[e]={}),n.cols[e].isHidden||=this.hiddenHeaders[n.id].COL[e])}}},BL=class extends DL{static getters=[`getImage`,`getImagePath`,`getImageSize`];fileStore;images={};syncedImages=new Set;constructor(e){super(e),this.fileStore=e.external.fileStore}allowDispatch(e){switch(e.type){case`CREATE_IMAGE`:return this.getters.getFigure(e.sheetId,e.figureId)?`InvalidFigureId`:`Success`;default:return`Success`}}handle(e){switch(e.type){case`CREATE_IMAGE`:this.addImage(e.figureId,e.sheetId,e.position,e.size),this.history.update(`images`,e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`image`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.getImage(n.id);if(i){let t={width:n.width,height:n.height};this.dispatch(`CREATE_IMAGE`,{sheetId:e.sheetIdTo,figureId:r,position:{x:n.x,y:n.y},size:t,definition:y(i)})}}break}case`DELETE_FIGURE`:this.history.update(`images`,e.sheetId,e.id,void 0);break;case`DELETE_SHEET`:this.history.update(`images`,e.sheetId,void 0);break}}garbageCollectExternalResources(){let e=new Set(this.getAllImages().map(e=>e.path));for(let t of this.syncedImages)e.has(t)||this.fileStore?.delete(t)}getImage(e){for(let t of Object.values(this.images))if(t&&t[e])return t[e];throw Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addImage(e,t,n,r){let i={id:e,x:n.x,y:n.y,width:r.width,height:r.height,tag:`image`};this.dispatch(`CREATE_FIGURE`,{sheetId:t,figure:i})}import(e){for(let t of e.sheets){let e=(t.figures||[]).filter(e=>e.tag===`image`);for(let n of e)this.history.update(`images`,t.id,n.id,n.data),this.syncedImages.add(n.data.path)}}export(e){for(let t of e.sheets){let e=t.figures.filter(e=>e.tag===`image`);for(let n of e)n.data=this.images[t.id]?.[n.id]}}exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let t of e)if(t?.tag===`image`){let e=this.getImage(t.id);e&&n.push({...t,data:y(e)})}t.images=[...t.images,...n]}}getAllImages(){let e=[];for(let t in this.images)e.push(...Object.values(this.images[t]||{}).filter(S));return e}},VL=class extends DL{static getters=[`isInMerge`,`isInSameMerge`,`isMergeHidden`,`getMainCellPosition`,`expandZone`,`doesIntersectMerge`,`doesColumnsHaveCommonMerges`,`doesRowsHaveCommonMerges`,`getMerges`,`getMerge`,`getMergesInZone`,`isSingleCellOrMerge`,`getSelectionRangeString`,`isMainCellPosition`];nextId=1;merges={};mergeCellMap={};allowDispatch(e){let t=`force`in e?!!e.force:!1;switch(e.type){case`ADD_MERGE`:return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case`UPDATE_CELL`:return this.checkMergedContentUpdate(e);case`REMOVE_MERGE`:return this.checkMergeExists(e);default:return`Success`}}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DELETE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DUPLICATE_SHEET`:let t=this.merges[e.sheetId];if(!t)break;for(let n of Object.values(t).filter(S))this.addMerge(e.sheetIdTo,n.zone);break;case`ADD_MERGE`:for(let t of e.target)this.addMerge(e.sheetId,t);break;case`REMOVE_MERGE`:for(let t of e.target)this.removeMerge(e.sheetId,t);break}}adaptRanges(e,t){let n=t?[t]:Object.keys(this.merges);for(let t of n)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map(t=>this.getMergeById(e,parseInt(t,10))).filter(S)}getMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e],i=r?t in r&&r[t]?.[n]:void 0;return i?this.getMergeById(e,i):void 0}getMergesInZone(e,t){let n=this.mergeCellMap[e];if(!n)return[];let r=new Set;for(let e=t.left;e<=t.right;e++)for(let i=t.top;i<=t.bottom;i++){let t=n[e]?.[i];t&&r.add(t)}return Array.from(r).map(t=>this.getMergeById(e,t)).filter(S)}getSelectionRangeString(e,t){let n=Ws.fromRange(e,this.getters),r=this.getters.expandZone(n.sheetId,n.zone),i=n.clone({zone:{...r,bottom:n.isFullCol?void 0:r.bottom,right:n.isFullRow?void 0:r.right}}),a=this.getters.getRangeString(i,t);if(this.isSingleCellOrMerge(n.sheetId,n.zone)){let{sheetName:e,xc:t}=Hs(a);return Us(e,t.split(`:`)[0])}return a}doesIntersectMerge(e,t){for(let n of this.getMerges(e))if(dr(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&&dr(n,o)&&(o=sr(n,o))}return ur(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:ur(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 ur(t,n);let{numberOfCols:r,numberOfRows:i}=mr(t);return r===1&&i===1}isMainCellPosition(e){return C(this.getMainCellPosition(e),e)}isMergeDestructive(e,t){let{left:n,right:r,top:i,bottom:a}=t;r=b(r,0,this.getters.getNumberCols(e)-1),a=b(a,0,this.getters.getNumberRows(e)-1);for(let t=i;t<=a;t++)for(let a=n;a<=r;a++)if(a!==n||t!==i){let n=this.getters.getCell({sheetId:e,col:a,row:t});if(n&&n.content!==``)return!0}return!1}getMergeById(e,t){let n=this.merges[e]?.[t];return n===void 0?void 0:UL(t,n)}checkDestructiveMerge({sheetId:e,target:t}){return this.getters.tryGetSheet(e)&&t.some(t=>this.isMergeDestructive(e,t))?`MergeIsDestructive`:`Success`}checkOverlap({target:e}){for(let t of e)for(let n of e)if(t!==n&&dr(t,n))return`MergeOverlap`;return`Success`}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return`Success`;let{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(e);for(let e of t)if(e.left<n&&e.right>=n||e.top<r&&e.bottom>=r)return`FrozenPaneOverlap`;return`Success`}checkMergedContentUpdate(e){let{col:t,row:n,content:r}=e;if(r===void 0)return`Success`;let{col:i,row:a}=this.getMainCellPosition(e);return i===t&&a===n?`Success`:`CellIsMerged`}checkMergeExists(e){let{sheetId:t,target:n}=e;for(let e of n){let{left:n,top:r}=e,i=this.getMerge({sheetId:t,col:n,row:r});if(i===void 0||!ur(e,i))return`InvalidTarget`}return`Success`}addMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t;if(r=b(r,0,this.getters.getNumberCols(e)-1),a=b(a,0,this.getters.getNumberRows(e)-1),w(n,i)===w(r,a))return;let o=this.getters.getCell({sheetId:e,col:n,row:i}),s=this.nextId++;this.history.update(`merges`,e,s,this.getters.getRangeFromSheetXC(e,nr({left:n,top:i,right:r,bottom:a})));let c=new Set;for(let t=i;t<=a;t++)for(let a=n;a<=r;a++){(a!==n||t!==i)&&this.dispatch(`UPDATE_CELL`,{sheetId:e,col:a,row:t,style:o?o.style:null,content:``});let r=this.getMerge({sheetId:e,col:a,row:t});r&&c.add(r.id),this.history.update(`mergeCellMap`,e,a,t,s)}for(let t of c){let{top:n,bottom:r,left:i,right:a}=this.getMergeById(e,t);for(let t=n;t<=r;t++)for(let n=i;n<=a;n++){let r={sheetId:e,col:n,row:t},i=this.getMerge(r);(!i||i.id!==s)&&(this.history.update(`mergeCellMap`,e,n,t,void 0),this.dispatch(`CLEAR_CELL`,r))}this.history.update(`merges`,e,t,void 0)}}removeMerge(e,t){let{left:n,top:r,bottom:i,right:a}=t,o=this.getMerge({sheetId:e,col:n,row:r});if(!(o===void 0||!ur(t,o))){this.history.update(`merges`,e,o.id,void 0);for(let t=r;t<=i;t++)for(let r=n;r<=a;r++)this.history.update(`mergeCellMap`,e,r,t,void 0)}}applyRangeChangeOnSheet(e,t){let n=Object.entries(this.merges[e]||{});for(let[r,i]of n)if(i){let n=i.zone,a=t(i);switch(a.changeType){case`NONE`:break;case`REMOVE`:this.removeMerge(e,n);break;default:let{numberOfCols:t,numberOfRows:i}=mr(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 vr(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,$n(n))}export(e){for(let t of e.sheets){let e=this.merges[t.id];e&&t.merges.push(...HL(e))}}exportForExcel(e){this.export(e)}};function HL(e){return Object.entries(e).map(([e,t])=>t?UL(parseInt(e,10),t):void 0).filter(S).map(e=>w(e.left,e.top)+`:`+w(e.right,e.bottom))}function UL(e,t){return{...t.zone,id:e}}var WL=class{getters;providers=[];isAdaptingRanges=!1;constructor(e){this.getters=e}static getters=[`extendRange`,`getRangeString`,`getRangeFromSheetXC`,`createAdaptedRanges`,`getRangeDataFromXc`,`getRangeDataFromZone`,`getRangeFromRangeData`,`getRangeFromZone`,`getRangesUnion`,`recomputeRanges`,`isRangeValid`,`removeRangesSheetPrefix`];allowDispatch(e){return e.type===`MOVE_RANGES`?e.target.length===1?`Success`:`InvalidZones`:`Success`}beforeHandle(e){}handle(e){if(this.isAdaptingRanges)throw Error(`Plugins cannot dispatch commands during adaptRanges phase`);switch(e.type){case`REMOVE_COLUMNS_ROWS`:{let t=e.dimension===`COL`?`left`:`top`,n=e.dimension===`COL`?`right`:`bottom`,r=e.dimension===`COL`?`columns`:`rows`,i=[...e.elements];i.sort((e,t)=>t-e);let a=ct(i);this.executeOnAllRanges(i=>{if(i.sheetId!==e.sheetId)return{changeType:`NONE`};let o=i,s=`NONE`;for(let e of a){let a=Kt(e),c=Gt(e);if(i.zone[t]<=a&&a<=i.zone[n]){let e=Math.min(i.zone[n],c)-a+1;s=`RESIZE`,o=this.createAdaptedRange(o,r,s,-e)}else if(i.zone[t]>=a&&i.zone[n]<=c)s=`REMOVE`,o=i.clone({...this.getInvalidRange()});else if(i.zone[t]<=c&&i.zone[n]>=c){let e=c-i.zone[t]+1;s=`RESIZE`,o=this.createAdaptedRange(o,r,s,-e),o=this.createAdaptedRange(o,r,`MOVE`,-(i.zone[t]-a))}else a<i.zone[t]&&(s=`MOVE`,o=this.createAdaptedRange(o,r,s,-(c-a+1)))}return s===`NONE`?{changeType:`NONE`}:{changeType:s,range:o}},e.sheetId);break}case`ADD_COLUMNS_ROWS`:{let t=e.dimension===`COL`?`left`:`top`,n=e.dimension===`COL`?`right`:`bottom`,r=e.dimension===`COL`?`columns`:`rows`;this.executeOnAllRanges(i=>{if(i.sheetId!==e.sheetId)return{changeType:`NONE`};if(e.position===`after`){if(i.zone[t]<=e.base&&e.base<i.zone[n])return{changeType:`RESIZE`,range:this.createAdaptedRange(i,r,`RESIZE`,e.quantity)};if(e.base<i.zone[t])return{changeType:`MOVE`,range:this.createAdaptedRange(i,r,`MOVE`,e.quantity)}}else{if(i.zone[t]<e.base&&e.base<=i.zone[n])return{changeType:`RESIZE`,range:this.createAdaptedRange(i,r,`RESIZE`,e.quantity)};if(e.base<=i.zone[t])return{changeType:`MOVE`,range:this.createAdaptedRange(i,r,`MOVE`,e.quantity)}}return{changeType:`NONE`}},e.sheetId);break}case`DELETE_SHEET`:this.executeOnAllRanges(t=>{if(t.sheetId!==e.sheetId)return{changeType:`NONE`};let n=this.getters.getSheetName(e.sheetId);return t=t.clone({...this.getInvalidRange(),invalidSheetName:n}),{changeType:`REMOVE`,range:t}},e.sheetId);break;case`RENAME_SHEET`:this.executeOnAllRanges(t=>{if(t.sheetId===e.sheetId)return{changeType:`CHANGE`,range:t};if(nc(t.invalidSheetName,e.name)){let n=e.sheetId;return{changeType:`CHANGE`,range:t.clone({sheetId:n,invalidSheetName:void 0})}}return{changeType:`NONE`}});break;case`MOVE_RANGES`:{let t=e.target[0];this.executeOnAllRanges(n=>{if(n.sheetId!==e.sheetId||!pr(n.zone,t))return{changeType:`NONE`};let r=e.targetSheetId,i=e.col-t.left,a=e.row-t.top,o=this.createAdaptedRange(n,`both`,`MOVE`,[i,a]),s=e.sheetId===r?o.prefixSheet:!0;return{changeType:`MOVE`,range:o.clone({sheetId:r,prefixSheet:s})}});break}}}finalize(){}verifyRangeRemoved(e){return t=>{let n=e(t);return n.changeType!==`NONE`&&!er(n.range.zone)?{range:n.range,changeType:`REMOVE`}:n}}createAdaptedRange(e,t,n,r){let i=br(e.unboundedZone,t,n,r);return e.clone({zone:i})}executeOnAllRanges(e,t){this.isAdaptingRanges=!0;let n=this.verifyRangeRemoved(e);for(let e of this.providers)e(n,t);this.isAdaptingRanges=!1}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,n,r){return e.map(e=>Ws.fromRange(e,this.getters)).map(e=>{if(!er(e.zone))return e;let i=e.prefixSheet?e.sheetId:r,a={...e.unboundedZone,left:e.isFullRow&&!e.unboundedZone.hasHeader?e.unboundedZone.left:e.unboundedZone.left+(e.parts[0].colFixed?0:t),right:e.isFullRow?e.unboundedZone.right:e.unboundedZone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:e.isFullCol&&!e.unboundedZone.hasHeader?e.unboundedZone.top:e.unboundedZone.top+(e.parts[0].rowFixed?0:n),bottom:e.isFullCol?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:n)};return e.clone({sheetId:i,zone:a}).orderZone()})}removeRangesSheetPrefix(e,t){return t.map(t=>{let n=Ws.fromRange(t,this.getters);return n.prefixSheet&&n.sheetId===e?n.clone({prefixSheet:!1}):n})}extendRange(e,t,n){let r=Ws.fromRange(e,this.getters),i=t===`COL`?r.zone.right+n:r.zone.right,a=t===`ROW`?r.zone.bottom+n:r.zone.bottom,o={left:r.zone.left,top:r.zone.top,right:r.isFullRow?void 0:i,bottom:r.isFullCol?void 0:a};return new Ws({...r,zone:o},this.getters.getSheetSize).orderZone()}getRangeFromSheetXC(e,t){if(!Is.test(t)||!this.getters.tryGetSheet(e))return new Ws({sheetId:``,zone:{left:-1,top:-1,right:-1,bottom:-1},parts:[],invalidXc:t,prefixSheet:!1},this.getters.getSheetSize);let n,r=t,i=!1;t.includes(`!`)&&({xc:r,sheetName:n}=Hs(t),n&&(i=!0));let a=Qn(r),o=Ws.getRangeParts(r,a),s=n&&!this.getters.getSheetIdByName(n)?n:void 0,c=this.getters.getSheetIdByName(n)||e;return new Ws({prefixSheet:i,zone:a,sheetId:c,invalidSheetName:s,parts:o},this.getters.getSheetSize).orderZone()}getRangeString(e,t,n={useBoundedReference:!1,useFixedReference:!1}){if(!e)return A.InvalidReference;if(e.invalidXc)return e.invalidXc;if(!this.getters.tryGetSheet(e.sheetId)||e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0||e.zone.left<0||e.zone.top<0)return A.InvalidReference;let r=Ws.fromRange(e,this.getters),i=r.sheetId!==t||r.invalidSheetName||r.prefixSheet,a=``;if(i&&(a=r.invalidSheetName?ot(r.invalidSheetName):ot(this.getters.getSheetName(r.sheetId))),i&&!a)return A.InvalidReference;let o=this.getRangePartString(r,0,n);return r.parts&&r.parts.length===2&&(r.zone.top!==r.zone.bottom||r.zone.left!==r.zone.right||r.parts[0].rowFixed||r.parts[0].colFixed||r.parts[1].rowFixed||r.parts[1].colFixed)&&(o+=`:`,o+=this.getRangePartString(r,1,n)),`${i?a+`!`:``}${o}`}getRangeDataFromXc(e,t){return this.getters.getRangeFromSheetXC(e,t).rangeData}getRangeDataFromZone(e,t){return t=this.getters.getUnboundedZone(e,t),{_sheetId:e,_zone:t}}getRangeFromZone(e,t){return new Ws({sheetId:e,zone:t,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}],prefixSheet:!1},this.getters.getSheetSize)}recomputeRanges(e,t){return Fn(e.map(e=>Ws.fromRange(e,this.getters).unboundedZone),t.map(e=>Ws.fromRange(e,this.getters).unboundedZone)).map(t=>this.getRangeFromZone(e[0].sheetId,t))}getRangeFromRangeData(e){return new Ws({prefixSheet:!1,zone:e._zone,sheetId:e._sheetId,invalidSheetName:void 0,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}]},this.getters.getSheetSize)}isRangeValid(e){if(!e)return!1;let{xc:t,sheetName:n}=Hs(e);return t.match(Is)!==null&&(!n||this.getters.getSheetIdByName(n)!==void 0)}getRangesUnion(e){let t=cr(...e.map(e=>Ws.fromRange(e,this.getters).unboundedZone));return this.getRangeFromZone(e[0].sheetId,t)}getRangePartString(e,t,n={useBoundedReference:!1,useFixedReference:!1}){let r=e.parts[t]?.colFixed||n.useFixedReference?`$`:``,i=Tn(t===0?e.zone.left:e.zone.right),a=e.parts[t]?.rowFixed||n.useFixedReference?`$`:``,o=String(t===0?e.zone.top+1:e.zone.bottom+1),s=``;return s=e.isFullCol&&!n.useBoundedReference?t===0&&e.unboundedZone.hasHeader?r+i+a+o:r+i:e.isFullRow&&!n.useBoundedReference?t===0&&e.unboundedZone.hasHeader?r+i+a+o:a+o:r+i+a+o,s}getInvalidRange(){return{parts:[],prefixSheet:!1,zone:{left:-1,top:-1,right:-1,bottom:-1},sheetId:``,invalidXc:A.InvalidReference}}},GL=class extends DL{static getters=`getSheetName.tryGetSheetName.getSheet.tryGetSheet.getSheetIdByName.getSheetIds.getVisibleSheetIds.isSheetVisible.doesHeaderExist.doesHeadersExist.getCell.getCellPosition.getColsZone.getRowCells.getRowsZone.getNumberCols.getNumberRows.getNumberHeaders.getGridLinesVisibility.getNextSheetName.getSheetSize.getSheetZone.getPaneDivisions.checkZonesExistInSheet.getCommandZones.getUnboundedZone.checkElementsIncludeAllNonFrozenHeaders.getDuplicateSheetName`.split(`.`);sheetIdsMapName={};orderedSheetIds=[];sheets={};cellPosition={};allowDispatch(e){let t=this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e);if(t!==`Success`)return t;switch(e.type){case`HIDE_SHEET`:return this.getVisibleSheetIds().length===1?`NotEnoughSheets`:`Success`;case`CREATE_SHEET`:return this.checkValidations(e,this.checkSheetName,this.checkSheetPosition);case`DUPLICATE_SHEET`:return this.sheets[e.sheetIdTo]?`DuplicatedSheetId`:this.orderedSheetIds.map(this.getSheetName.bind(this)).includes(e.sheetNameTo)?`DuplicatedSheetName`:`Success`;case`MOVE_SHEET`:try{let t=this.orderedSheetIds.findIndex(t=>t===e.sheetId);return this.findIndexOfTargetSheet(t,e.delta),`Success`}catch{return`WrongSheetMove`}case`RENAME_SHEET`:return this.isRenameAllowed(e);case`COLOR_SHEET`:return!e.color||tn(e.color)?`Success`:`InvalidColor`;case`DELETE_SHEET`:return this.getVisibleSheetIds().length>1?`Success`:`NotEnoughSheets`;case`ADD_COLUMNS_ROWS`:return this.doesHeaderExist(e.sheetId,e.dimension,e.base)?e.quantity<=0?`InvalidQuantity`:`Success`:`InvalidHeaderIndex`;case`REMOVE_COLUMNS_ROWS`:{let t=Kt(e.elements),n=Gt(e.elements);return t<0||!this.doesHeaderExist(e.sheetId,e.dimension,n)?`InvalidHeaderIndex`:this.checkElementsIncludeAllNonFrozenHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`}case`FREEZE_ROWS`:return this.checkValidations(e,this.checkRowFreezeQuantity,this.checkRowFreezeOverlapMerge);case`FREEZE_COLUMNS`:return this.checkValidations(e,this.checkColFreezeQuantity,this.checkColFreezeOverlapMerge);default:return`Success`}}handle(e){switch(e.type){case`SET_GRID_LINES_VISIBILITY`:this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);break;case`CREATE_SHEET`:let t=this.createSheet(e.sheetId,e.name||this.getNextSheetName(),e.cols||26,e.rows||100,e.position);this.history.update(`sheetIdsMapName`,t.name,t.id);break;case`MOVE_SHEET`:this.moveSheet(e.sheetId,e.delta);break;case`RENAME_SHEET`:this.renameSheet(this.sheets[e.sheetId],e.name);break;case`COLOR_SHEET`:this.history.update(`sheets`,e.sheetId,`color`,e.color);break;case`HIDE_SHEET`:this.hideSheet(e.sheetId);break;case`SHOW_SHEET`:this.showSheet(e.sheetId);break;case`DUPLICATE_SHEET`:this.duplicateSheet(e.sheetId,e.sheetIdTo,e.sheetNameTo);break;case`DELETE_SHEET`:this.deleteSheet(this.sheets[e.sheetId]);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case`UPDATE_CELL_POSITION`:this.updateCellPosition(e);break;case`FREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,e.quantity,`COL`);break;case`FREEZE_ROWS`:this.setPaneDivisions(e.sheetId,e.quantity,`ROW`);break;case`UNFREEZE_ROWS`:this.setPaneDivisions(e.sheetId,0,`ROW`);break;case`UNFREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,0,`COL`);break;case`UNFREEZE_COLUMNS_ROWS`:this.setPaneDivisions(e.sheetId,0,`COL`),this.setPaneDivisions(e.sheetId,0,`ROW`)}}import(e){for(let t of e.sheets)this.sheetIdsMapName[t.name]=t.id;for(let t of e.sheets){let e=t.name||T(`Sheet`)+(Object.keys(this.sheets).length+1),{colNumber:n,rowNumber:r}=this.getImportedSheetSize(t),i={id:t.id,name:e,numberOfCols:n,rows:Zs(r),areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,panes:{xSplit:t.panes?.xSplit||0,ySplit:t.panes?.ySplit||0},color:t.color};this.orderedSheetIds.push(i.id),this.sheets[i.id]=i}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(S).map(e=>{let t=this.sheets[e],n={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},styles:{},formats:{},borders:{},conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,color:t.color};return(t.panes.xSplit||t.panes.ySplit)&&(n.panes=t.panes),n})}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){let t=this.sheets[e];if(!t)throw Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){return this.tryGetSheet(e)?.name}getSheetIdByName(e){if(e){let t=it(e);for(let e in this.sheetIdsMapName)if(nc(e,t))return this.sheetIdsMapName[e]}}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}doesHeaderExist(e,t,n){return t===`COL`?n>=0&&n<this.getNumberCols(e):n>=0&&n<this.getNumberRows(e)}doesHeadersExist(e,t,n){return n.every(n=>this.doesHeaderExist(e,t,n))}getCell({sheetId:e,col:t,row:n}){let r=this.tryGetSheet(e)?.rows[n]?.cells[t];if(r!==void 0)return this.getters.getCellById(r)}getColsZone(e,t,n){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:n}}getRowCells(e,t){return Object.values(this.getSheet(e).rows[t]?.cells).filter(S)}getRowsZone(e,t,n){return{top:t,bottom:n,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){let t=this.cellPosition[e];if(!t)throw Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return t===`COL`?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e=`Sheet`){return ec(this.orderedSheetIds.map(this.getSheetName.bind(this)),e)}getSheetSize(e){return{numberOfRows:this.getNumberRows(e),numberOfCols:this.getNumberCols(e)}}getSheetZone(e){return{top:0,left:0,bottom:this.getNumberRows(e)-1,right:this.getNumberCols(e)-1}}getUnboundedZone(e,t){if(t.bottom===void 0||t.right===void 0)return t;let n=t.left===0&&t.right===this.getNumberCols(e)-1,r=t.top===0&&t.bottom===this.getNumberRows(e)-1;return{...t,bottom:r?void 0:t.bottom,right:n&&!r?void 0:t.right}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,n){let r={...this.getPaneDivisions(e)};n===`COL`?r.xSplit=t:n===`ROW`&&(r.ySplit=t),this.history.update(`sheets`,e,`panes`,r)}checkElementsIncludeAllNonFrozenHeaders(e,t,n){let r=this.getters.getPaneDivisions(e),i=t===`ROW`?r.ySplit:r.xSplit,a=this.getters.getNumberHeaders(e,t);return i?At(n,x(i,a)):!1}getCommandZones(e){let t=[];return`zone`in e&&t.push(e.zone),`target`in e&&t.push(...e.target),`ranges`in e&&t.push(...e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone)),`col`in e&&`row`in e&&t.push({top:e.row,left:e.col,bottom:e.row,right:e.col}),t}checkZonesExistInSheet(e,t){if(!t.every(er))return`InvalidRange`;if(t.length){let n=this.getSheetZone(e);return t.every(e=>pr(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:Zs(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(T(`There is not enough visible sheets`))}checkSheetName(e){let t=this.getters.tryGetSheetName(e.sheetId);if(t!==void 0&&e.name===t)return`UnchangedSheetName`;let{orderedSheetIds:n,sheets:r}=this,i=e.name&&e.name.trim().toLowerCase();return n.find(t=>nc(r[t]?.name,i)&&t!==e.sheetId)?`DuplicatedSheetName`:Ke.test(i)?`ForbiddenCharactersInSheetName`:`Success`}checkSheetPosition(e){let{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?`WrongSheetPosition`:`Success`}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkRowFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.top<e.quantity&&e.quantity<=n.bottom)return`MergeOverlap`;return`Success`}checkColFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.left<e.quantity&&e.quantity<=n.right)return`MergeOverlap`;return`Success`}isRenameAllowed(e){return e.name&&e.name.trim().toLowerCase()?this.checkSheetName(e):`MissingSheetName`}renameSheet(e,t){let n=e.name;this.history.update(`sheets`,e.id,`name`,t.trim());let r=Object.assign({},this.sheetIdsMapName);delete r[n],r[t]=e.id,this.history.update(`sheetIdsMapName`,r)}hideSheet(e){this.history.update(`sheets`,e,`isVisible`,!1)}showSheet(e){this.history.update(`sheets`,e,`isVisible`,!0)}duplicateSheet(e,t,n){let r=y(this.getSheet(e));r.id=t,r.name=n;for(let e=0;e<=r.numberOfCols;e++)for(let t=0;t<=r.rows.length;t++)r.rows[t]&&(r.rows[t].cells[e]=void 0);let i=this.orderedSheetIds.slice(),a=i.indexOf(e);i.splice(a+1,0,r.id),this.history.update(`orderedSheetIds`,i),this.history.update(`sheets`,Object.assign({},this.sheets,{[r.id]:r}));for(let t of Object.values(this.getters.getCells(e))){let{col:e,row:n}=this.getCellPosition(t.id);this.dispatch(`UPDATE_CELL`,{sheetId:r.id,col:e,row:n,content:t.content,format:t.format,style:t.style})}let o=Object.assign({},this.sheetIdsMapName);o[r.name]=r.id,this.history.update(`sheetIdsMapName`,o)}getDuplicateSheetName(e){return tc(e,this.orderedSheetIds.map(this.getSheetName.bind(this)))}deleteSheet(e){let t=e.name,n=Object.assign({},this.sheets);delete n[e.id],this.history.update(`sheets`,n);let r=this.orderedSheetIds.slice(),i=r.indexOf(e.id);r.splice(i,1),this.history.update(`orderedSheetIds`,r);let a=Object.assign({},this.sheetIdsMapName);delete a[t],this.history.update(`sheetIdsMapName`,a)}removeColumns(e,t){t.sort((e,t)=>t-e);for(let n of t)this.moveCellOnColumnsDeletion(e,n);let n=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,n-t.length);let r=t.filter(t=>t<e.panes.xSplit).length;r&&this.setPaneDivisions(e.id,e.panes.xSplit-r,`COL`)}removeRows(e,t){t.sort((e,t)=>t-e);for(let n of ct(t)){let t=n[n.length-1],r=n[0];this.moveCellOnRowsDeletion(e,t,r),this.updateRowsStructureOnDeletion(e,t,r)}let n=t.filter(t=>t<e.panes.ySplit).length;n&&this.setPaneDivisions(e.id,e.panes.ySplit-n,`ROW`)}addColumns(e,t,n,r){let i=n===`before`?t:t+1;this.moveCellsOnAddition(e,i,r,`columns`);let a=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,a+r),i<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+r,`COL`)}addRows(e,t,n,r){let i=n===`before`?t:t+1;this.addEmptyRows(e,r),this.moveCellsOnAddition(e,i,r,`rows`),i<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+r,`ROW`)}moveCellOnColumnsDeletion(e,t){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:t,top:0,right:t,bottom:e.rows.length-1}]});for(let n=0;n<e.rows.length;n++){let r=e.rows[n];for(let i in r.cells){let a=Number(i),o=r.cells[i];o&&a>t&&this.setNewPosition(o,e.id,a-1,n)}}}moveCellsOnAddition(e,t,n,r){let i=[];for(let a=0;a<e.rows.length;a++){let o=e.rows[a];if(r!==`rows`||a>=t)for(let s in o.cells){let c=Number(s),l=o.cells[s];l&&(r===`rows`||c>=t)&&i.push({sheetId:e.id,cellId:l,col:c+(r===`columns`?n:0),row:a+(r===`rows`?n:0),type:`UPDATE_CELL_POSITION`})}}for(let e of i.reverse())this.updateCellPosition(e)}moveCellOnRowsDeletion(e,t,n){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:0,top:t,right:this.getters.getNumberCols(e.id),bottom:n}]});let r=n-t+1;for(let t=0;t<e.rows.length;t++){let i=e.rows[t];if(t>n)for(let n in i.cells){let a=Number(n),o=i.cells[n];o&&this.setNewPosition(o,e.id,a,t-r)}}}updateRowsStructureOnDeletion(e,t,n){let r=[],i=e.rows.map(e=>e.cells).reverse();for(let a in e.rows){let e=Number(a);e>=t&&e<=n||r.push({cells:i.pop()})}this.history.update(`sheets`,e.id,`rows`,r)}addEmptyRows(e,t){let n=e.rows.slice();for(let e=0;e<t;e++)n.push({cells:{}});this.history.update(`sheets`,e.id,`rows`,n)}getImportedSheetSize(e){let t=Object.keys(e.cells).map(Pn),n=e.rowNumber,r=e.colNumber;for(let{col:e,row:i}of t)n=Math.max(n,i+1),r=Math.max(r,e+1);return{rowNumber:n,colNumber:r}}checkSheetExists(e){return e.type!==`CREATE_SHEET`&&`sheetId`in e&&this.sheets[e.sheetId]===void 0?`InvalidSheetId`:e.type===`CREATE_SHEET`&&this.sheets[e.sheetId]!==void 0?`DuplicatedSheetId`:`Success`}checkZonesAreInSheet(e){return`sheetId`in e?`ranges`in e&&e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkZonesExistInSheet(e.sheetId,this.getCommandZones(e)):`Success`}},KL=class extends DL{static getters=[`getCoreTable`,`getCoreTables`,`getCoreTableMatchingTopLeft`];tables={};insertionOrders={};adaptRanges(e,t){let n=t?[t]:this.getters.getSheetIds();for(let t of n)for(let n of this.getCoreTables(t))this.applyRangeChangeOnTable(t,n,e)}allowDispatch(e){switch(e.type){case`CREATE_TABLE`:if(e.ranges.some(t=>!this.getters.tryGetSheet(t._sheetId)||t._sheetId!==e.sheetId))return`InvalidSheetId`;let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone);return Or(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(dr(n,t))return`MergeInTable`}break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`tables`,e.sheetId,{}),this.history.update(`insertionOrders`,e.sheetId,[]);break;case`DELETE_SHEET`:{let t={...this.tables};delete t[e.sheetId],this.history.update(`tables`,t),this.history.update(`insertionOrders`,e.sheetId,void 0);break}case`DUPLICATE_SHEET`:{let t={};for(let n of this.getCoreTables(e.sheetId))t[n.id]=n.type===`dynamic`?this.copyDynamicTableForSheet(e.sheetIdTo,n):this.copyStaticTableForSheet(e.sheetIdTo,n);this.history.update(`tables`,e.sheetIdTo,t),this.history.update(`insertionOrders`,e.sheetIdTo,[...this.insertionOrders[e.sheetId]??[]]);break}case`CREATE_TABLE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e)),n=this.getters.getRangesUnion(t),r=this.getters.getMergesInZone(e.sheetId,n.zone);r.length&&this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:r});let i=this.uuidGenerator.smallUuid(),a=e.config||km,o=e.tableType===`dynamic`?this.createDynamicTable(i,n,a):this.createStaticTable(i,e.tableType,n,a);this.history.update(`tables`,e.sheetId,o.id,o),this.history.update(`insertionOrders`,e.sheetId,[...this.insertionOrders[e.sheetId]??[],o.id]);break}case`REMOVE_TABLE`:{let t={};for(let n of this.getCoreTables(e.sheetId))e.target.every(e=>!lr(n.range.zone,e))&&(t[n.id]=n);this.history.update(`tables`,e.sheetId,t),this.history.update(`insertionOrders`,e.sheetId,this.insertionOrders[e.sheetId]?.filter(e=>e in t));break}case`UPDATE_TABLE`:this.updateTable(e);break;case`UPDATE_CELL`:{let t=e.sheetId;for(let n of this.getCoreTables(t)){if(n.type===`dynamic`)continue;let r=this.canUpdateCellCmdExtendTable(e,n);r===`down`?this.extendTableDown(t,n):r===`right`&&this.extendTableRight(t,n)}break}case`DELETE_CONTENT`:{let t={...this.tables[e.sheetId]};for(let n in t){let r=t[n];r&&e.target.some(e=>pr(r.range.zone,e))&&this.dispatch(`REMOVE_TABLE`,{sheetId:e.sheetId,target:[r.range.zone]})}break}}}getCoreTables(e){let t=[];for(let n of this.insertionOrders[e]||[]){let r=this.tables[e][n];r&&t.push(r)}return t}getCoreTable({sheetId:e,col:t,row:n}){return this.getCoreTables(e).find(e=>fr(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter(e=>t.some(t=>dr(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 x(a.left,a.right+1)){let t={...a,left:e,right:e},o=this.uuidGenerator.smallUuid();i.push(this.createFilterFromZone(o,n.sheetId,t,r))}}return{id:e,range:n,filters:i,config:r,type:t}}createDynamicTable(e,t,n){let r=wr(t.zone);return{id:e,range:this.getters.getRangeFromZone(t.sheetId,r),config:n,type:`dynamic`}}updateTable(e){let t=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return;let n=e.newTableRange?this.getters.getRangeFromRangeData(e.newTableRange):void 0;if(n){let t=this.getters.getMergesInZone(e.sheetId,n.zone);this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:t})}let r=n||t.range,i=this.updateTableConfig(e.config,t.config),a=e.tableType??t.type;if(a===`dynamic`&&t.type!==`dynamic`||a!==`dynamic`&&t.type===`dynamic`){let n=a===`dynamic`?this.createDynamicTable(t.id,r,i):this.createStaticTable(t.id,a,r,i);this.history.update(`tables`,e.sheetId,t.id,n)}else{let n=t.type===`dynamic`?this.updateDynamicTable(t,r,i):this.updateStaticTable(t,r,i,a);this.history.update(`tables`,e.sheetId,t.id,n)}}updateStaticTable(e,t,n,r=e.type){if(r===`dynamic`)throw Error(`Cannot use updateStaticTable to update a dynamic table`);let i=t||e.range,a=i.zone,o=this.updateTableConfig(n,e.config),s=o||e.config,c=[];if(t||o&&`numberOfHeaders`in o)for(let t of x(a.left,a.right+1)){let n=a.top===e.range.zone.top?e.filters.find(e=>e.col===t):void 0,r={...a,left:t,right:t},o=n?.id||this.uuidGenerator.smallUuid();c.push(this.createFilterFromZone(o,i.sheetId,r,s))}return{...e,range:i,config:s,filters:c.length?c:e.filters,type:r}}updateDynamicTable(e,t,n){let r=t?this.getters.getRangeFromZone(t.sheetId,wr(t.zone)):e.range,i=n||e.config;return{...e,range:r,config:i}}updateTableConfig(e,t){if(!e)return t;let n={...t,...e};return e.numberOfHeaders===0?n.hasFilters=!1:e.hasFilters===!0&&(n.numberOfHeaders||=1),n}createFilterFromZone(e,t,n,r){return JF(e,this.getters.getRangeFromZone(t,n),r,this.getters.getRangeFromZone)}copyStaticTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone),r=t.filters.map(n=>{let r=this.getters.getRangeFromZone(e,n.rangeWithHeaders.zone);return JF(n.id,r,t.config,this.getters.getRangeFromZone)});return{id:t.id,range:n,filters:r,config:y(t.config),type:t.type}}copyDynamicTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone);return{id:t.id,range:n,config:y(t.config),type:`dynamic`}}applyRangeChangeOnTable(e,t,n){let r=n(t.range),i;switch(r.changeType){case`REMOVE`:this.history.update(`tables`,e,t.id,void 0);return;case`NONE`:return;default:i=r.range}if(t.type===`dynamic`){let n=this.updateDynamicTable(t,i);this.history.update(`tables`,e,t.id,n);return}let a=[];for(let e of t.filters){let r=n(e.rangeWithHeaders);switch(r.changeType){case`REMOVE`:continue;case`NONE`:a.push(e);break;default:let n=r.range,i=JF(e.id,n,t.config,this.getters.getRangeFromZone);a.push(i)}}let o=i.zone;if(a.length<mr(o).numberOfCols){for(let n=o.left;n<=o.right;n++)if(!a.find(e=>e.col===n)){let r=this.uuidGenerator.smallUuid(),i={...o,left:n,right:n};a.push(this.createFilterFromZone(r,e,i,t.config))}a.sort((e,t)=>e.col-t.col)}let s=this.createStaticTable(t.id,t.type,i,t.config,a);this.history.update(`tables`,e,t.id,s)}import(e){for(let t of e.sheets){let e=[];for(let n of t.tables||[]){let r=this.uuidGenerator.uuidv4(),i=n.config||km,a=this.getters.getRangeFromSheetXC(t.id,n.range),o=n.type||`static`,s=o===`dynamic`?this.createDynamicTable(r,a,i):this.createStaticTable(r,o,a,i);this.history.update(`tables`,t.id,s.id,s),e.push(s.id)}this.history.update(`insertionOrders`,t.id,e)}}export(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n={range:nr(e.range.zone),type:e.type};C(e.config,km)||(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=nr(e.range.zone);t.tables.push({range:n,filters:[],config:e.config})}}},qL=class extends DL{static getters=[`getHeaderGroups`,`getGroupsLayers`,`getVisibleGroupLayers`,`getHeaderGroup`,`getHeaderGroupsInZone`,`isGroupFolded`,`isRowFolded`,`isColFolded`];groups={};allowDispatch(e){switch(e.type){case`GROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;if(this.findGroupWithStartEnd(e.sheetId,e.dimension,t,n))return`HeaderGroupAlreadyExists`;break}case`UNGROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;break}case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUP`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);if(!t)return`UnknownHeaderGroup`;if(x(0,this.getters.getNumberHeaders(e.sheetId,e.dimension)).every(n=>n>=t.start&&n<=t.end||this.getters.isHeaderHiddenByUser(e.sheetId,e.dimension,n)))return`NotEnoughElements`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`groups`,e.sheetId,{ROW:[],COL:[]});break;case`GROUP_HEADERS`:this.groupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`UNGROUP_HEADERS`:this.unGroupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`DUPLICATE_SHEET`:{let t=y(this.groups[e.sheetId]);this.history.update(`groups`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.groups};delete t[e.sheetId],this.history.update(`groups`,t);break}case`ADD_COLUMNS_ROWS`:let t=Ot(e.position,e.base);this.moveGroupsOnHeaderInsertion(e.sheetId,e.dimension,t,e.quantity);break;case`REMOVE_COLUMNS_ROWS`:this.moveGroupsOnHeaderDeletion(e.sheetId,e.dimension,e.elements);break;case`UNFOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.unfoldHeaderGroup(e.sheetId,e.dimension,t);break}case`FOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.foldHeaderGroup(e.sheetId,e.dimension,t);break}case`UNFOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.unfoldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.foldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:{let t=e.type===`UNFOLD_HEADER_GROUPS_IN_ZONE`?`unfold`:`fold`,n=this.getGroupsLayers(e.sheetId,e.dimension);t===`fold`&&n.reverse();let r=n.flat(),i=e.dimension===`ROW`?e.zone.top:e.zone.left,a=e.dimension===`ROW`?e.zone.bottom:e.zone.right,o=new Set;for(let e=i;e<=a;e++){let n=r.filter(t=>t.start-1<=e&&e<=t.end);for(let e of n)if(!(t===`fold`&&e.isFolded||t===`unfold`&&!e.isFolded)){o.add(e);break}}for(let n of o)t===`unfold`?this.unfoldHeaderGroup(e.sheetId,e.dimension,n):this.foldHeaderGroup(e.sheetId,e.dimension,n);break}}}getHeaderGroups(e,t){return this.groups[e][t]}getHeaderGroup(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}getHeaderGroupsInZone(e,t,n){return this.getHeaderGroups(e,t).filter(e=>{let r=t===`ROW`?n.top:n.left,i=t===`ROW`?n.bottom:n.right;return this.doGroupOverlap(e,r,i)})}getGroupsLayers(e,t){let n=this.getHeaderGroups(e,t);return this.bricksFallingAlgorithm(n,0,0)}getVisibleGroupLayers(e,t){let n=this.getGroupsLayers(e,t);for(let r of n)for(let n=r.length-1;n>=0;n--){let i=r[n];i.start!==0&&x(i.start-1,i.end+1).every(n=>this.getters.isHeaderHiddenByUser(e,t,n))&&r.splice(n,1)}return n.filter(e=>e.length>0)}isGroupFolded(e,t,n,r){return this.getHeaderGroup(e,t,n,r)?.isFolded||!1}isRowFolded(e,t){return this.getters.getHeaderGroups(e,`ROW`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}isColFolded(e,t){return this.getters.getHeaderGroups(e,`COL`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}getGroupId(e){return`${e.start}-${e.end}}`}bricksFallingAlgorithm(e,t,n,r=0){let i={};for(let t of e)i[this.getGroupId(t)]=t.isFolded;let a={};for(let t of e)for(let e=t.start;e<=t.end;e++)a[e]=a[e]?a[e]+1:1;for(let e=t;e<=n;e++)a[e]=a[e]?a[e]+r:r;let o=Math.max(...Object.values(a),0),s=Array.from({length:o},()=>[]),c=Math.max(n,...e.map(e=>e.end)),l=Math.min(t,...e.map(e=>e.start));for(let e=l;e<=c;e++){let t=a[e]||0;for(let n=0;n<t;n++){let t=s[n].at(-1);if(t&&Lt([t.end,e]))t.end++;else{let t={start:e,end:e};s[n].push(t)}}}for(let e of s)for(let t of e)t.isFolded=i[this.getGroupId(t)];return s}groupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}unGroupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,-1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}moveGroupsOnHeaderInsertion(e,t,n,r){let i=this.groups[e][t];for(let a=0;a<i.length;a++){let o=i[a],[s,c]=Qs(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=$s(n,x(e.start,e.end+1));t.length!==0&&i.push({...e,start:Math.min(...t),end:Math.max(...t)})}this.history.update(`groups`,e,t,this.bricksFallingAlgorithm(i,0,0).flat())}doGroupOverlap(e,t,n){return e.start<=n&&e.end>=t}removeDuplicateGroups(e){let t={};for(let n of e)t[this.getGroupId(n)]=n;return Object.values(t)}findGroupWithStartEnd(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}foldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!0);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end<=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!0)}}unfoldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!1);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end>=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!1)}}getGroupIndex(e,t,n,r){let i=this.groups[e][t].findIndex(e=>e.start===n&&e.end===r);return i===-1?void 0:i}import(e){for(let t of e.sheets)if(this.groups[t.id]={ROW:[],COL:[]},t.headerGroups)for(let e of[`ROW`,`COL`])for(let n of t.headerGroups[e]||[])this.groups[t.id][e].push({...n})}export(e){for(let t of e.sheets)t.headerGroups=this.groups[t.id]}exportForExcel(e){for(let t of e.sheets)for(let e of[`ROW`,`COL`]){let n=this.getGroupsLayers(t.id,e);for(let r=0;r<n.length;r++){let i=n[r];for(let n of i){for(let i=n.start;i<=n.end;i++){let a=Af(t,e,i);a.outlineLevel=r+1,n.isFolded&&(a.isHidden=!0)}if(n.isFolded){let r=Af(t,e,n.end+1);r.collapsed=!0}}}}}},JL=class extends DL{static getters=[`getPivotCoreDefinition`,`getPivotDisplayName`,`getPivotId`,`getPivotFormulaId`,`getPivotIds`,`getMeasureCompiledFormula`,`getPivotName`,`isExistingPivot`,`getMeasureFullDependencies`];nextFormulaId=1;pivots={};formulaIds={};compiledMeasureFormulas={};allowDispatch(e){switch(e.type){case`ADD_PIVOT`:return this.checkDuplicatedMeasureIds(e.pivot);case`UPDATE_PIVOT`:return e.pivotId in this.pivots?C(e.pivot,this.pivots[e.pivotId]?.definition)?`NoChanges`:e.pivot.name===``?`EmptyName`:this.checkDuplicatedMeasureIds(e.pivot):`PivotIdNotFound`;case`RENAME_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;if(e.name===``)return`EmptyName`;break;case`REMOVE_PIVOT`:case`DUPLICATE_PIVOT`:case`INSERT_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;break;case`DUPLICATE_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`}return`Success`}handle(e){switch(e.type){case`ADD_PIVOT`:{let{pivotId:t,pivot:n}=e;this.addPivot(t,n);break}case`INSERT_PIVOT`:{let{sheetId:t,col:n,row:r,pivotId:i,table:a}=e,o={sheetId:t,col:n,row:r},{cols:s,rows:c,measures:l,fieldsType:u}=a,d=new hF(s,c,l,u||{}),f=this.getPivotFormulaId(i);this.insertPivot(o,f,d);break}case`RENAME_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,`name`,e.name);break;case`REMOVE_PIVOT`:{let t={...this.pivots};delete t[e.pivotId];let n=this.getPivotFormulaId(e.pivotId);this.history.update(`formulaIds`,n,void 0),this.history.update(`pivots`,t);break}case`DUPLICATE_PIVOT`:{let{pivotId:t,newPivotId:n}=e,r=y(this.getPivotCore(t).definition);r.name=e.duplicatedPivotName??r.name+` (copy)`,this.addPivot(n,r);break}case`UPDATE_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,y(e.pivot)),this.compileCalculatedMeasures(e.pivotId,e.pivot.measures);break}}adaptRanges(e){for(let t in this.pivots){let n=y(this.pivots[t]?.definition);if(!n)continue;let r=jF.get(n.type)?.adaptRanges?.(this.getters,n,e);r&&!C(n,r)&&this.history.update(`pivots`,t,`definition`,r)}for(let t in this.compiledMeasureFormulas)for(let n in this.compiledMeasureFormulas[t]){let r=this.pivots[t]?.definition.measures.find(e=>e.id===n);if(!r||!r.computedBy)continue;let i=r.computedBy.sheetId,a=this.compiledMeasureFormulas[t][n].formula,o=[];for(let t of a.dependencies){let n=e(t);n.changeType===`NONE`?o.push(t):o.push(n.range)}let s=this.getters.getFormulaString(i,a.tokens,o);s!==r.computedBy.formula&&this.replaceMeasureFormula(t,r,s)}}getPivotDisplayName(e){return`(#${this.getPivotFormulaId(e)}) ${this.getPivotName(e)}`}getPivotName(e){return this.getPivotCore(e).definition.name}getPivotCoreDefinition(e){return this.getPivotCore(e).definition}getPivotId(e){return this.formulaIds[e]}getPivotFormulaId(e){return this.getPivotCore(e).formulaId}getPivotIds(){return Object.keys(this.pivots)}isExistingPivot(e){return e in this.pivots}getMeasureCompiledFormula(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].formula}getMeasureFullDependencies(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].dependencies}addPivot(e,t,n=this.nextFormulaId.toString()){this.history.update(`pivots`,e,{definition:y(t),formulaId:n}),this.compileCalculatedMeasures(e,t.measures),this.history.update(`formulaIds`,n,e),this.history.update(`nextFormulaId`,this.nextFormulaId+1)}compileCalculatedMeasures(e,t){for(let n of t)if(n.computedBy){let t=this.compileMeasureFormula(n.computedBy.sheetId,n.computedBy.formula);this.history.update(`compiledMeasureFormulas`,e,n.id,`formula`,t)}for(let n of t)if(n.computedBy){let t=this.computeMeasureFullDependencies(e,n);this.history.update(`compiledMeasureFormulas`,e,n.id,`dependencies`,t)}}computeMeasureFullDependencies(e,t,n=new Set){let r=[],i=this.getPivotCoreDefinition(e),a=this.getMeasureCompiledFormula(e,t);n.add(t.id);for(let o of a.tokens){if(o.type!==`SYMBOL`)continue;let a=i.measures.find(e=>ot(e.id)===o.value&&t.id!==e.id);!a||n.has(a.id)||!a.computedBy||r.push(...this.computeMeasureFullDependencies(e,a,n))}return r.push(...a.dependencies.filter(e=>!e.invalidXc)),r}insertPivot(e,t,n){this.resizeSheet(e.sheetId,e,n);let r=n.getPivotCells();for(let n=0;n<r.length;n++)for(let i=0;i<r[n].length;i++){let a=r[n][i];this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col+n,row:e.row+i,content:Iu(t,a)})}}resizeSheet(e,{col:t,row:n},r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,quantity:s-l,position:`after`})}getPivotCore(e){let t=this.pivots[e];if(!t)throw Error(`Pivot with id ${e} not found`);return t}compileMeasureFormula(e,t){let n=kE(t),r=n.dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t));return{...n,dependencies:r}}replaceMeasureFormula(e,t,n){let r=this.pivots[e];if(!r)return;let i=r.definition.measures.indexOf(t);this.history.update(`pivots`,e,`definition`,`measures`,i,`computedBy`,{formula:n,sheetId:t.computedBy.sheetId}),this.compileCalculatedMeasures(e,r.definition.measures)}checkDuplicatedMeasureIds(e){let t=new Set(e.measures.map(e=>e.id));return e.measures.length===t.size?`Success`:`InvalidDefinition`}import(e){if(e.pivots)for(let[t,n]of Object.entries(e.pivots))this.addPivot(t,n,n.formulaId);this.history.update(`nextFormulaId`,e.pivotNextId||ku(this.pivots)+1)}export(e){e.pivots={};for(let t in this.pivots)e.pivots[t]={...this.getPivotCoreDefinition(t),formulaId:this.getPivotFormulaId(t)};e.pivotNextId=this.nextFormulaId}},YL=class extends DL{static getters=[`getLocale`];locale=O;allowDispatch(e){switch(e.type){case`UPDATE_LOCALE`:return tl(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===vl(e)&&(n=vl(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??O}export(e){e.settings={locale:this.locale}}},XL=class extends DL{allowDispatch(e){switch(e.type){case`ADD_PIVOT`:case`UPDATE_PIVOT`:let t=e.pivot;return this.checkDataSetValidity(t)}return`Success`}checkDataSetValidity(e){if(e.type===`SPREADSHEET`&&e.dataSet){let{zone:t,sheetId:n}=e.dataSet;return!n||!this.getters.tryGetSheet(n)||!t||!er(t)?`InvalidDataSet`:this.getters.checkZonesExistInSheet(n,[t])}return`Success`}},ZL=class extends DL{static getters=[`getNewCustomTableStyleName`,`getTableStyle`,`getTableStyles`,`isTableStyleEditable`];styles={};allowDispatch(e){switch(e.type){case`CREATE_TABLE`:case`UPDATE_TABLE`:if(e.config?.styleId&&!this.styles[e.config.styleId])return`InvalidTableConfig`;break;case`CREATE_TABLE_STYLE`:if(!Wm[e.templateName])return`InvalidTableStyle`;try{en(e.primaryColor)}catch{return`InvalidTableStyle`}break}return`Success`}handle(e){switch(e.type){case`CREATE_TABLE_STYLE`:let t=Gm(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:km.styleId}});break}}getTableStyle(e){if(!this.styles[e])throw Error(`Table style ${e} does not exist`);return this.styles[e]}getTableStyles(){return this.styles}getNewCustomTableStyleName(){let e=T(`Custom Table Style`),t=new Set(Object.values(this.styles).map(e=>e.displayName));if(!t.has(e))return e;let n=2;for(;t.has(`${e} ${n}`);)n++;return`${e} ${n}`}isTableStyleEditable(e){return!Um[e]}import(e){for(let e in Um)this.styles[e]=Um[e];for(let t in e.customTableStyles){let n=e.customTableStyles[t];this.styles[t]=Gm(n.displayName,n.templateName,n.primaryColor)}}export(e){let t={};for(let e in this.styles)Um[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}},$=class extends EL{static layers=[];getters;ui;selection;constructor({getters:e,stateObserver:t,dispatch:n,canDispatch:r,uiActions:i,selection:a}){super(t,n,r),this.getters=e,this.ui=i,this.selection=a}drawLayer(e,t){}};let QL=new h;QL.add(`pivots`,e=>{for(let t of e.getPivotIds())e.getPivot(t).markAsDirtyForEvaluation?.()});let $L=zT.mapping;function eR(e,t,n){return new tR(e,t,n).getParameters()}var tR=class{getters;computeCell;evalContext;rangeCache={};constructor(e,t,n){this.getters=t,this.computeCell=n,this.evalContext=Object.assign(Object.create($L),e,{getters:this.getters,locale:this.getters.getLocale()})}getParameters(){return{referenceDenormalizer:this.refFn.bind(this),ensureRange:this.range.bind(this),evalContext:this.evalContext}}refFn(e,t){let n=this.getRangeError(e);if(n)return n;if(t)return{value:Us(this.getters.getSheetName(e.sheetId),nr(e.zone))};let r={sheetId:e.sheetId,col:e.zone.left,row:e.zone.top};return this.computeCell(r)}range(e){let t=this.getRangeError(e);if(t)return[[t]];let n=e.sheetId,r=e.zone,i=lr(r,this.getters.getSheetZone(n));if(!i)return[[]];let{top:a,left:o,bottom:s,right:c}=r,l=`${n}-${a}-${o}-${s}-${c}`;if(l in this.rangeCache)return this.rangeCache[l];let u=i.bottom-i.top+1,d=i.right-i.left+1,f=Array(d);for(let e=i.left;e<=i.right;e++){let t=e-i.left;f[t]=Array(u);for(let r=i.top;r<=i.bottom;r++){let a=r-i.top;f[t][a]=this.computeCell({sheetId:n,col:e,row:r})}}return this.rangeCache[l]=f,f}getRangeError(e){if(!er(e.zone))return new aa;if(e.invalidSheetName)return new j(T(`Invalid sheet name: %s`,e.invalidSheetName))}},nR=d(c(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n||=self).RBush=r()})(e,function(){"use strict";function e(e,r,i,a,o){(function e(n,r,i,a,o){for(;a>i;){if(a-i>600){var s=a-i+1,c=r-i+1,l=Math.log(s),u=.5*Math.exp(2*l/3),d=.5*Math.sqrt(l*u*(s-u)/s)*(c-s/2<0?-1:1);e(n,r,Math.max(i,Math.floor(r-c*u/s+d)),Math.min(a,Math.floor(r+(s-c)*u/s+d)),o)}var f=n[r],p=i,m=a;for(t(n,i,r),o(n[a],f)>0&&t(n,i,a);p<m;){for(t(n,p,m),p++,m--;o(n[p],f)<0;)p++;for(;o(n[m],f)>0;)m--}o(n[i],f)===0?t(n,i,m):t(n,++m,a),m<=r&&(i=m+1),r<=m&&(a=m-1)}})(e,r,i||0,a||e.length-1,o||n)}function t(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function n(e,t){return e<t?-1:+(e>t)}var r=function(e){e===void 0&&(e=9),this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()};function i(e,t,n){if(!n)return t.indexOf(e);for(var r=0;r<t.length;r++)if(n(e,t[r]))return r;return-1}function a(e,t){o(e,0,e.children.length,t,e)}function o(e,t,n,r,i){i||=m(null),i.minX=1/0,i.minY=1/0,i.maxX=-1/0,i.maxY=-1/0;for(var a=t;a<n;a++){var o=e.children[a];s(i,e.leaf?r(o):o)}return i}function s(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function c(e,t){return e.minX-t.minX}function l(e,t){return e.minY-t.minY}function u(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function d(e){return e.maxX-e.minX+(e.maxY-e.minY)}function f(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function p(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function m(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function h(t,n,r,i,a){for(var o=[n,r];o.length;)if(!((r=o.pop())-(n=o.pop())<=i)){var s=n+Math.ceil((r-n)/i/2)*i;e(t,s,n,r,a),o.push(n,s,s,r)}}return r.prototype.all=function(){return this._all(this.data,[])},r.prototype.search=function(e){var t=this.data,n=[];if(!p(e,t))return n;for(var r=this.toBBox,i=[];t;){for(var a=0;a<t.children.length;a++){var o=t.children[a],s=t.leaf?r(o):o;p(e,s)&&(t.leaf?n.push(o):f(e,s)?this._all(o,n):i.push(o))}t=i.pop()}return n},r.prototype.collides=function(e){var t=this.data;if(!p(e,t))return!1;for(var n=[];t;){for(var r=0;r<t.children.length;r++){var i=t.children[r],a=t.leaf?this.toBBox(i):i;if(p(e,a)){if(t.leaf||f(e,a))return!0;n.push(i)}}t=n.pop()}return!1},r.prototype.load=function(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(var t=0;t<e.length;t++)this.insert(e[t]);return this}var n=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===n.height)this._splitRoot(this.data,n);else{if(this.data.height<n.height){var r=this.data;this.data=n,n=r}this._insert(n,this.data.height-n.height-1,!0)}else this.data=n;return this},r.prototype.insert=function(e){return e&&this._insert(e,this.data.height-1),this},r.prototype.clear=function(){return this.data=m([]),this},r.prototype.remove=function(e,t){if(!e)return this;for(var n,r,a,o=this.data,s=this.toBBox(e),c=[],l=[];o||c.length;){if(o||(o=c.pop(),r=c[c.length-1],n=l.pop(),a=!0),o.leaf){var u=i(e,o.children,t);if(u!==-1)return o.children.splice(u,1),c.push(o),this._condense(c),this}a||o.leaf||!f(o,s)?r?(n++,o=r.children[n],a=!1):o=null:(c.push(o),l.push(n),n=0,r=o,o=o.children[0])}return this},r.prototype.toBBox=function(e){return e},r.prototype.compareMinX=function(e,t){return e.minX-t.minX},r.prototype.compareMinY=function(e,t){return e.minY-t.minY},r.prototype.toJSON=function(){return this.data},r.prototype.fromJSON=function(e){return this.data=e,this},r.prototype._all=function(e,t){for(var n=[];e;)e.leaf?t.push.apply(t,e.children):n.push.apply(n,e.children),e=n.pop();return t},r.prototype._build=function(e,t,n,r){var i,o=n-t+1,s=this._maxEntries;if(o<=s)return a(i=m(e.slice(t,n+1)),this.toBBox),i;r||(r=Math.ceil(Math.log(o)/Math.log(s)),s=Math.ceil(o/s**(r-1))),(i=m([])).leaf=!1,i.height=r;var c=Math.ceil(o/s),l=c*Math.ceil(Math.sqrt(s));h(e,t,n,l,this.compareMinX);for(var u=t;u<=n;u+=l){var d=Math.min(u+l-1,n);h(e,u,d,c,this.compareMinY);for(var f=u;f<=d;f+=c){var p=Math.min(f+c-1,d);i.children.push(this._build(e,f,p,r-1))}}return a(i,this.toBBox),i},r.prototype._chooseSubtree=function(e,t,n,r){for(;r.push(t),!t.leaf&&r.length-1!==n;){for(var i=1/0,a=1/0,o=void 0,s=0;s<t.children.length;s++){var c=t.children[s],l=u(c),d=(f=e,p=c,(Math.max(p.maxX,f.maxX)-Math.min(p.minX,f.minX))*(Math.max(p.maxY,f.maxY)-Math.min(p.minY,f.minY))-l);d<a?(a=d,i=l<i?l:i,o=c):d===a&&l<i&&(i=l,o=c)}t=o||t.children[0]}var f,p;return t},r.prototype._insert=function(e,t,n){var r=n?e:this.toBBox(e),i=[],a=this._chooseSubtree(r,this.data,t,i);for(a.children.push(e),s(a,r);t>=0&&i[t].children.length>this._maxEntries;)this._split(i,t),t--;this._adjustParentBBoxes(r,i,t)},r.prototype._split=function(e,t){var n=e[t],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);var o=this._chooseSplitIndex(n,i,r),s=m(n.children.splice(o,n.children.length-o));s.height=n.height,s.leaf=n.leaf,a(n,this.toBBox),a(s,this.toBBox),t?e[t-1].children.push(s):this._splitRoot(n,s)},r.prototype._splitRoot=function(e,t){this.data=m([e,t]),this.data.height=e.height+1,this.data.leaf=!1,a(this.data,this.toBBox)},r.prototype._chooseSplitIndex=function(e,t,n){for(var r,i,a,s,c,l,d,f=1/0,p=1/0,m=t;m<=n-t;m++){var h=o(e,0,m,this.toBBox),g=o(e,m,n,this.toBBox),_=(i=h,a=g,s=void 0,c=void 0,l=void 0,d=void 0,s=Math.max(i.minX,a.minX),c=Math.max(i.minY,a.minY),l=Math.min(i.maxX,a.maxX),d=Math.min(i.maxY,a.maxY),Math.max(0,l-s)*Math.max(0,d-c)),v=u(h)+u(g);_<f?(f=_,r=m,p=v<p?v:p):_===f&&v<p&&(p=v,r=m)}return r||n-t},r.prototype._chooseSplitAxis=function(e,t,n){var r=e.leaf?this.compareMinX:c,i=e.leaf?this.compareMinY:l;this._allDistMargin(e,t,n,r)<this._allDistMargin(e,t,n,i)&&e.children.sort(r)},r.prototype._allDistMargin=function(e,t,n,r){e.children.sort(r);for(var i=this.toBBox,a=o(e,0,t,i),c=o(e,n-t,n,i),l=d(a)+d(c),u=t;u<n-t;u++){var f=e.children[u];s(a,e.leaf?i(f):f),l+=d(a)}for(var p=n-t-1;p>=t;p--){var m=e.children[p];s(c,e.leaf?i(m):m),l+=d(c)}return l},r.prototype._adjustParentBBoxes=function(e,t,n){for(var r=n;r>=0;r--)s(t[r],e)},r.prototype._condense=function(e){for(var t=e.length-1,n=void 0;t>=0;t--)e[t].children.length===0?t>0?(n=e[t-1].children).splice(n.indexOf(e[t]),1):this.clear():a(e[t],this.toBBox)},r})}))(),1),rR=class{rTrees={};constructor(e=[]){let t={};for(let n of e){let e=n.boundingBox.sheetId;t[e]||(t[e]=[]),t[e].push(n)}for(let e in t)this.rTrees[e]=new iR,this.rTrees[e].load(t[e])}insert(e){let t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new iR),this.rTrees[t].insert(e)}search({zone:e,sheetId:t}){return this.rTrees[t]?this.rTrees[t].search({minX:e.left,minY:e.top,maxX:e.right,maxY:e.bottom}):[]}remove(e){let t=e.boundingBox.sheetId;this.rTrees[t]&&this.rTrees[t].remove(e,this.rtreeItemComparer)}rtreeItemComparer(e,t){return e.boundingBox.sheetId===t.boundingBox.sheetId&&e.boundingBox?.zone.left===t.boundingBox.zone.left&&e.boundingBox?.zone.top===t.boundingBox.zone.top&&e.boundingBox?.zone.right===t.boundingBox.zone.right&&e.boundingBox?.zone.bottom===t.boundingBox.zone.bottom&&C(e.data,t.data)}},iR=class extends nR.default{toBBox({boundingBox:e}){let t=e.zone;return{minX:t.left,minY:t.top,maxX:t.right,maxY:t.bottom}}compareMinX(e,t){return e.boundingBox.zone.left-t.boundingBox.zone.left}compareMinY(e,t){return e.boundingBox.zone.top-t.boundingBox.zone.top}},aR=class{createEmptyPositionSet;dependencies=new kL;rTree;constructor(e,t=[]){this.createEmptyPositionSet=e,this.rTree=new rR(t)}removeAllDependencies(e){let t=this.dependencies.get(e);if(t){for(let e of t)this.rTree.remove(e);this.dependencies.delete(e)}}addDependencies(e,t){let n=t.map(({sheetId:t,zone:n})=>({data:e,boundingBox:{zone:n,sheetId:t}}));for(let e of n)this.rTree.insert(e);let r=this.dependencies.get(e);r?r.push(...n):this.dependencies.set(e,n)}getCellsDependingOn(e,t){let n=this.createEmptyPositionSet(),r=Array.from(e).reverse();for(;r.length>0;){let e=r.pop(),i=e.zone,a=e.sheetId;for(let e=i.left;e<=i.right;e++)for(let t=i.top;t<=i.bottom;t++)n.add({sheetId:a,col:e,row:t});let o=this.rTree.search(e).map(e=>e.data),s={};for(let e of o)!n.has(e)&&!t.has(e)&&(s[e.sheetId]||(s[e.sheetId]=[]),s[e.sheetId].push(E(e)));for(let e in s){let t=Fn(s[e],[]);r.push(...t.map(t=>({sheetId:e,zone:t})))}}for(let t of e){let e=t.zone,r=t.sheetId;for(let t=e.left;t<=e.right;t++)for(let i=e.top;i<=e.bottom;i++)n.delete({sheetId:r,col:t,row:i})}return n}},oR=class extends Uint32Array{columnOffset=0;cols=0;rows=0;static create(e,t){let n=sR(t),r=e<<n>>5,i=new this(r+1);return i.columnOffset=n,i.cols=t,i.rows=e,i}getValue(e){let[t,n]=this.getCoordinates(e);return this[t]>>n&1}setValue(e,t){let[n,r]=this.getCoordinates(e),i=(this[n]>>r&1)==0&&t===1;return this[n]=this[n]&~(1<<r)|t<<r,i}isEmpty(){return!this.some(e=>e!==0)}fillAllPositions(){this.fill(-1>>>0)}clear(){this.fill(0)}getCoordinates(e){let{row:t,col:n}=e,r=(t<<this.columnOffset)+n,i=r>>5;return[i,r-(i<<5)]}};function sR(e){return e===0?-1/0:e<0?NaN:32-Math.clz32(--e)}var cR=class{sheets={};insertions=[];maxSize=0;constructor(e){for(let t in e){let n=e[t].cols,r=e[t].rows;this.maxSize+=n*r,this.sheets[t]=oR.create(r,n)}}add(e){this.sheets[e.sheetId].setValue(e,1)&&this.insertions.push(e)}addMany(e){for(let t of e)this.add(t)}delete(e){this.sheets[e.sheetId].setValue(e,0)}deleteMany(e){for(let t of e)this.delete(t)}has(e){return this.sheets[e.sheetId].getValue(e)===1}clear(){let e=[...this];this.insertions=[];for(let e in this.sheets)this.sheets[e].clear();return e}isEmpty(){if(this.insertions.length===0)return!0;for(let e in this.sheets)if(!this.sheets[e].isEmpty())return!1;return!0}fillAllPositions(){this.insertions=Array(this.maxSize);let e=0;for(let t in this.sheets){let n=this.sheets[t];n.fillAllPositions();for(let r=0;r<n.rows;r++)for(let i=0;i<n.cols;i++)this.insertions[e++]={sheetId:t,row:r,col:i}}}*[Symbol.iterator](){for(let e of this.insertions)this.sheets[e.sheetId].getValue(e)===1&&(yield e)}},lR=class{resultsToArrayFormulas=new rR;arrayFormulasToResults=new kL;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map(e=>e.data)||uR}getArrayResultZone(e){return this.arrayFormulasToResults.get(e)}removeNode(e){let t=this.arrayFormulasToResults.get(e);t&&(this.resultsToArrayFormulas.remove({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.delete(e))}addRelation({arrayFormulaPosition:e,resultZone:t}){this.resultsToArrayFormulas.insert({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.set(e,t)}isArrayFormula(e){return this.arrayFormulasToResults.has(e)}};let uR=[],dR=Object.freeze(_s(new ia)),fR=Object.freeze(_s({value:null}));var pR=class{context;getters;compilationParams;evaluatedCells=new kL;formulaDependencies=Et(new aR(this.createEmptyPositionSet.bind(this)));blockedArrayFormulas=new cR({});spreadingRelations=new lR;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=eR(this.context,this.getters,this.computeAndSave.bind(this))}getEvaluatedCell(e){return this.evaluatedCells.get(e)||fR}getSpreadZone(e,t={ignoreSpillError:!1}){let n=this.spreadingRelations.getArrayResultZone(e);if(!n)return;let r=this.evaluatedCells.get(e);return r?.type===`error`&&!(t.ignoreSpillError&&r?.value===A.SpilledBlocked)?E(e):sr(E(e),n)}getEvaluatedPositions(){return this.evaluatedCells.keys()}getEvaluatedPositionsInSheet(e){return this.evaluatedCells.keysForSheet(e)}getArrayFormulaSpreadingOn(e){if(this.getEvaluatedCell(e).type===`empty`)return;let t=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e.sheetId,E(e));return Array.from(t).find(e=>!this.blockedArrayFormulas.has(e))}isArrayFormulaSpillBlocked(e){return this.blockedArrayFormulas.has(e)}updateDependencies(e){this.formulaDependencies().removeAllDependencies(e);let t=this.getDirectDependencies(e);this.formulaDependencies().addDependencies(e,t)}addDependencies(e,t){this.formulaDependencies().addDependencies(e,t);for(let e of t)this.compilationParams.ensureRange(e)}updateCompilationParameters(e){this.compilationParams=eR(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.__originCellPosition=e,this.compilationParams.evalContext.lookupCaches=this.compilationParams.evalContext.lookupCaches||{forwardSearch:new Map,reverseSearch:new Map}}updateCompilationParametersForGridEvaluation(){this.compilationParams=eR(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.updateDependencies=this.updateDependencies.bind(this),this.compilationParams.evalContext.addDependencies=this.addDependencies.bind(this),this.compilationParams.evalContext.lookupCaches={forwardSearch:new Map,reverseSearch:new Map}}createEmptyPositionSet(){let e={};for(let t of this.getters.getSheetIds())e[t]={rows:this.getters.getNumberRows(t),cols:this.getters.getNumberCols(t)};return new cR(e)}evaluateCells(e){let t=performance.now(),n=this.createEmptyPositionSet();n.addMany(e);let r=this.getArrayFormulasImpactedByChangesOf(e);n.addMany(this.getCellsDependingOn(e)),n.addMany(r),n.addMany(this.getCellsDependingOn(r)),this.evaluate(n),console.debug(`evaluate Cells`,performance.now()-t,`ms`)}getArrayFormulasImpactedByChangesOf(e){let t=this.createEmptyPositionSet();for(let n of e){let e=this.getters.getCell(n)?.content,r=this.getArrayFormulaSpreadingOn(n);r!==void 0&&t.add(r),e||t.add(n)}let n=_r(t);for(let e in n)for(let r of n[e])t.addMany(this.getArrayFormulasBlockedBy(e,r));return t}buildDependencyGraph(){this.blockedArrayFormulas=this.createEmptyPositionSet(),this.spreadingRelations=new lR,this.formulaDependencies=Et(()=>{let e=[...this.getAllCells()].flatMap(e=>this.getDirectDependencies(e).filter(e=>!e.invalidSheetName&&!e.invalidXc).map(t=>({data:e,boundingBox:{zone:t.zone,sheetId:t.sheetId}})));return new aR(this.createEmptyPositionSet.bind(this),e)})}evaluateAllCells(){let e=performance.now();this.evaluatedCells=new kL,this.evaluate(this.getAllCells()),console.debug(`evaluate all cells`,performance.now()-e,`ms`)}evaluateFormulaResult(e,t,n){let r=kE(t),i=r.dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t));return this.updateCompilationParameters(n),this.evaluateCompiledFormula(e,{...r,dependencies:i})}evaluateCompiledFormula(e,t,n){try{let r=gR(t,this.compilationParams,e,this.buildSafeGetSymbolValue(n),this.compilationParams.evalContext.__originCellPosition);return k(r)?Na(r,hR):hR(r)}catch(e){return VT(e,``)}}getAllCells(){let e=this.createEmptyPositionSet();return e.fillAllPositions(),e}getArrayFormulasBlockedBy(e,t){let n=this.createEmptyPositionSet(),r=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e,t);n.addMany(r);let i=[...r].filter(e=>!this.blockedArrayFormulas.has(e));return i.length&&n.deleteMany(i),n.addMany(this.getCellsDependingOn(n)),n}nextPositionsToUpdate=new cR({});cellsBeingComputed=new Set;symbolsBeingComputed=new Set;evaluate(e){this.cellsBeingComputed=new Set,this.nextPositionsToUpdate=e;let t=0;for(;!this.nextPositionsToUpdate.isEmpty()&&t++<30;){this.updateCompilationParametersForGridEvaluation();let e=this.nextPositionsToUpdate.clear();for(let t=0;t<e.length;++t)this.evaluatedCells.delete(e[t]);for(let t=0;t<e.length;++t){let n=e[t];if(this.nextPositionsToUpdate.has(n))continue;let r=this.computeCell(n);r!==fR&&this.evaluatedCells.set(n,r)}QL.getAll().forEach(e=>e(this.getters))}t>=30&&console.warn(`Maximum iteration reached while evaluating cells`)}computeCell(e){let t=this.evaluatedCells.get(e);if(t)return t;this.blockedArrayFormulas.has(e)||this.invalidateSpreading(e),this.spreadingRelations.isArrayFormula(e)&&this.spreadingRelations.removeNode(e);let n=this.getters.getCell(e);if(n===void 0)return fR;let r=n.id,i={format:n.format,locale:this.getters.getLocale()};try{return this.cellsBeingComputed.has(r)?dR:(this.cellsBeingComputed.add(r),n.isFormula?this.computeFormulaCell(e,n):hs(n,i))}catch(e){return e.value=e?.value||A.GenericError,e.message=e?.message||WT,_s(e)}finally{this.cellsBeingComputed.delete(r)}}computeAndSave(e){let t=this.computeCell(e);return this.evaluatedCells.has(e)||this.evaluatedCells.set(e,t),t}computeFormulaCell(e,t){let n=gR(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e);if(!k(n))return _s(hR(n),this.getters.getLocale(),t);this.assertSheetHasEnoughSpaceToSpreadFormulaResult(e,n);let r=n.length,i=n[0].length;if(i===0)return _s({value:0},this.getters.getLocale(),t);if(i===1&&r===1)return _s(hR(n[0][0]),this.getters.getLocale(),t);let a={top:e.row,bottom:e.row+i-1,left:e.col,right:e.col+r-1};return this.spreadingRelations.addRelation({resultZone:a,arrayFormulaPosition:e}),this.assertNoMergedCellsInSpreadZone(e,n),mR(r,i,this.checkCollision(e)),mR(r,i,this.spreadValues(e,n)),this.invalidatePositionsDependingOnSpread(e.sheetId,a),_s(hR(n[0][0]),this.getters.getLocale(),t)}invalidatePositionsDependingOnSpread(e,t){let n=this.formulaDependencies().getCellsDependingOn(gr(t).map(t=>({sheetId:e,zone:t})),this.nextPositionsToUpdate);n.delete({sheetId:e,col:t.left,row:t.top}),this.nextPositionsToUpdate.addMany(n)}assertSheetHasEnoughSpaceToSpreadFormulaResult({sheetId:e,col:t,row:n},r){let i=this.getters.getNumberCols(e),a=this.getters.getNumberRows(e),o=t+r.length<=i,s=n+r[0].length<=a;if(!(o&&s))throw o?new ca(T(`Result couldn't be automatically expanded. Please insert more rows.`)):s?new ca(T(`Result couldn't be automatically expanded. Please insert more columns.`)):new ca(T(`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 ca(T(`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 ca(T(`Array result was not expanded because it would overwrite data in %s.`,w(o.col,o.row)));this.blockedArrayFormulas.delete(e)}}spreadValues({sheetId:e,col:t,row:n},r){return(i,a)=>{let o={sheetId:e,col:i+t,row:a+n},s=this.getters.getCell(o),c=_s(hR(r[i][a]),this.getters.getLocale(),s);this.evaluatedCells.set(o,c)}}invalidateSpreading(e){let t=this.spreadingRelations.getArrayResultZone(e);if(!t)return;for(let n=t.left;n<=t.right;n++)for(let r=t.top;r<=t.bottom;r++){let t={sheetId:e.sheetId,col:n,row:r};this.getters.getCell(t)?.content||this.evaluatedCells.delete(t)}let n=e.sheetId;this.invalidatePositionsDependingOnSpread(n,t),this.nextPositionsToUpdate.addMany(this.getArrayFormulasBlockedBy(n,t))}buildSafeGetSymbolValue(e){return t=>{if(this.symbolsBeingComputed.has(t))return dR;this.symbolsBeingComputed.add(t);try{return e?.(t)||new ra(T(`Invalid formula`))}finally{this.symbolsBeingComputed.delete(t)}}}getDirectDependencies(e){let t=this.getters.getCell(e);return t?.isFormula?t.compiledFormula.dependencies:[]}getCellsDependingOn(e){let t=[],n=_r(e);for(let e in n)t.push(...n[e].map(t=>({sheetId:e,zone:t})));return this.formulaDependencies().getCellsDependingOn(t,this.nextPositionsToUpdate)}};function mR(e,t,n){for(let r=0;r<e;++r)for(let e=0;e<t;++e)r===0&&e===0||n(r,e)}function hR(e){return e.value===null||e.value===void 0?{...e,value:0}:e}function gR(e,t,n,r,i){let a=t.evalContext,o=a.__originCellPosition,s=a.__originSheetId;a.__originCellPosition=i,a.__originSheetId=n;let c=e.execute(e.dependencies,t.referenceDenormalizer,t.ensureRange,r,a);return a.__originCellPosition=o,a.__originSheetId=s,c}var _R=class extends ${static getters=[`evaluateFormula`,`evaluateFormulaResult`,`evaluateCompiledFormula`,`getCorrespondingFormulaCell`,`getRangeFormattedValues`,`getRangeValues`,`getRangeFormats`,`getEvaluatedCell`,`getEvaluatedCells`,`getEvaluatedCellsInZone`,`getEvaluatedCellsPositions`,`getSpreadZone`,`getArrayFormulaSpreadingOn`,`isArrayFormulaSpillBlocked`,`isEmpty`];shouldRebuildDependenciesGraph=!0;evaluator;positionsToUpdate=[];constructor(e){super(e),this.evaluator=new pR(e.custom,this.getters)}beforeHandle(e){(zi.has(e.type)||Vi.has(e.type))&&(this.shouldRebuildDependenciesGraph=!0)}handle(e){switch(e.type){case`UPDATE_CELL`:if(!(`content`in e||`format`in e)||this.shouldRebuildDependenciesGraph)return;let t={sheetId:e.sheetId,row:e.row,col:e.col};this.positionsToUpdate.push(t),`content`in e&&this.evaluator.updateDependencies(t);break;case`EVALUATE_CELLS`:this.evaluator.evaluateAllCells();break}}finalize(){this.shouldRebuildDependenciesGraph?(this.evaluator.buildDependencyGraph(),this.evaluator.evaluateAllCells(),this.shouldRebuildDependenciesGraph=!1):this.positionsToUpdate.length&&this.evaluator.evaluateCells(this.positionsToUpdate),this.positionsToUpdate=[]}evaluateFormula(e,t,n){let r=this.evaluateFormulaResult(e,t,n);return k(r)?Na(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 vr(t).map(({col:t,row:n})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}))}getSpreadZone(e,t={ignoreSpillError:!1}){return this.evaluator.getSpreadZone(e,t)}getArrayFormulaSpreadingOn(e){return this.evaluator.getArrayFormulaSpreadingOn(e)}isArrayFormulaSpillBlocked(e){return this.evaluator.isArrayFormulaSpillBlocked(e)}isEmpty(e,t){return vr(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 vr(r).reduce((e,r)=>{let{col:i,row:a}=r;return!this.getters.isColHidden(n,i)&&!this.getters.isRowHidden(n,a)&&e.push(t({sheetId:n,...r})),e},[])}exportForExcel(e){for(let t of e.sheets)t.formulaSpillRanges={};for(let t of this.evaluator.getEvaluatedPositions()){let n=this.evaluator.getEvaluatedCell(t),r=w(t.col,t.row),i=n.value,a=!1,o,s,c=!0,l=e.sheets.find(e=>e.id===t.sheetId),u=this.getCorrespondingFormulaCell(t);if(u){let e=this.getters.getCell(t);c=LE(u.compiledFormula.tokens),a=c&&e?.content===u.content,c||i!==``&&(o=(i??``).toString(),s=n.format)}let d=l.cells[r]||{},f=s?Fr(s,e.formats):d.format,p;p=c&&a&&u instanceof jL?u.contentWithFixedReferences:c?d.content:o,l.cells[r]={...d,value:i,isFormula:a,content:p,format:f};let m=this.getSpreadZone(t);m&&(l.formulaSpillRanges[r]=this.getters.getRangeString(this.getters.getRangeFromZone(t.sheetId,m),t.sheetId))}}getCorrespondingFormulaCell(e){let t=this.getters.getCell(e);if(t&&t.isFormula)return t.compiledFormula.isBadExpression?void 0:t;if(t&&t.content)return;let n=this.getArrayFormulaSpreadingOn(e);if(n===void 0)return;let r=this.getters.getCell(n);if(r?.isFormula)return r}};let vR=/"(#[0-9a-fA-F]{6})"/g;function yR(e){let t=[{leadColor:an(255,0,0),colors:[]},{leadColor:an(255,128,0),colors:[]},{leadColor:an(128,128,0),colors:[]},{leadColor:an(128,255,0),colors:[]},{leadColor:an(0,255,0),colors:[]},{leadColor:an(0,255,128),colors:[]},{leadColor:an(0,255,255),colors:[]},{leadColor:an(0,127,255),colors:[]},{leadColor:an(0,0,255),colors:[]},{leadColor:an(127,0,255),colors:[]},{leadColor:an(128,0,128),colors:[]},{leadColor:an(255,0,128),colors:[]}];for(let n of e.map(ln)){let e=500,r=0;t.forEach((t,i)=>{let a=bR(n,t.leadColor);e>a&&(e=a,r=i)}),t[r].colors.push(n)}return t.map(e=>e.colors.sort((e,t)=>dn(e).s-dn(t).s)).flat().map(cn)}function bR(e,t){return Math.sqrt((e.r-t.r)**2+(e.g-t.g)**2+(e.b-t.b)**2)}var xR=class extends ${customColors={};shouldUpdateColors=!0;static getters=[`getCustomColors`];constructor(e){super(e),this.tryToAddColors(e.customColors??[])}handle(e){switch(e.type){case`START`:for(let e of this.getters.getSheetIds())for(let t of this.getters.getChartIds(e))this.tryToAddColors(this.getChartColors(t));break;case`UPDATE_CHART`:case`CREATE_CHART`:this.tryToAddColors(this.getChartColors(e.id));break;case`COLOR_SHEET`:e.color&&this.tryToAddColors([e.color]);break;case`UPDATE_CELL`:case`ADD_CONDITIONAL_FORMAT`:case`SET_BORDER`:case`SET_ZONE_BORDERS`:case`SET_FORMATTING`:case`CREATE_TABLE`:case`UPDATE_TABLE`:this.history.update(`shouldUpdateColors`,!0);break}}finalize(){this.shouldUpdateColors&&(this.history.update(`shouldUpdateColors`,!1),this.tryToAddColors(this.computeCustomColors()))}getCustomColors(){return yR(Object.keys(this.customColors))}computeCustomColors(){let e=[];for(let t of this.getters.getSheetIds())e=e.concat(this.getSheetColors(t),this.getColorsFromCells(t),this.getFormattingColors(t),this.getTableColors(t));return[...new Set([...e])]}getSheetColors(e){let t=this.getters.getSheet(e);return t.color?[t.color]:[]}getColorsFromCells(e){let t=Object.values(this.getters.getCells(e)),n=new Set;for(let e of t)e.style?.textColor&&n.add(e.style.textColor),e.style?.fillColor&&n.add(e.style.fillColor);for(let t of this.getters.getBordersColors(e))n.add(t);return[...n]}getFormattingColors(e){let t=this.getters.getConditionalFormats(e),n=[];for(let e of t){let t=e.rule;t.type===`CellIsRule`?(n.push(t.style.textColor),n.push(t.style.fillColor)):t.type===`ColorScaleRule`&&(n.push($t(t.minimum.color)),n.push(t.midpoint?$t(t.midpoint.color):void 0),n.push($t(t.maximum.color)))}return n.filter(S)}getChartColors(e){let t=this.getters.getChart(e);return t===void 0?[]:[...JSON.stringify(t.getDefinition()).matchAll(vR)].map(e=>e[1])}getTableColors(e){return this.getters.getTables(e).flatMap(e=>{let t=e.config,n=this.getters.getTableStyle(t.styleId);return[this.getTableStyleElementColors(n.wholeTable),t.numberOfHeaders>0?this.getTableStyleElementColors(n.headerRow):[],t.totalRow?this.getTableStyleElementColors(n.totalRow):[],t.bandedColumns?this.getTableStyleElementColors(n.firstColumnStripe):[],t.bandedColumns?this.getTableStyleElementColors(n.secondColumnStripe):[],t.bandedRows?this.getTableStyleElementColors(n.firstRowStripe):[],t.bandedRows?this.getTableStyleElementColors(n.secondRowStripe):[],t.firstColumn?this.getTableStyleElementColors(n.firstColumn):[],t.lastColumn?this.getTableStyleElementColors(n.lastColumn):[]].flat()})}getTableStyleElementColors(e){return e?[e.style?.fillColor,e.style?.textColor,e.border?.bottom?.color,e.border?.top?.color,e.border?.left?.color,e.border?.right?.color,e.border?.horizontal?.color,e.border?.vertical?.color].filter(S):[]}tryToAddColors(e){for(let t of e){if(!tn(t))continue;let e=en(t);t&&!Ne.includes(e)&&this.history.update(`customColors`,e,!0)}}},SR=class extends ${static getters=[`getChartRuntime`,`getStyleOfSingleCellChart`];charts={};createRuntimeChart=_k(this.getters);handle(e){if(zi.has(e.type)||Hi.has(e.type)||Bi.has(e.type))for(let e in this.charts)this.charts[e]=void 0;switch(e.type){case`UPDATE_CHART`:case`CREATE_CHART`:case`DELETE_FIGURE`:this.charts[e.id]=void 0;break;case`DELETE_SHEET`:for(let e in this.charts)this.getters.isChartDefined(e)||(this.charts[e]=void 0);break}}getChartRuntime(e){if(!this.charts[e]){let t=this.getters.getChart(e);if(!t)throw Error(`No chart for the given id: ${e}`);this.charts[e]=this.createRuntimeChart(t)}return this.charts[e]}getStyleOfSingleCellChart(e,t){if(e)return{background:e,fontColor: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)}}exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let r of e){if(!r||r.tag!==`chart`)continue;let e=r.id,i=this.getters.getChart(e)?.getDefinitionForExcel();if(i)n.push({...r,data:i});else{if(!this.getters.getChart(e))continue;let n=this.getters.getChartType(e),i=r_(this.getters.getChartRuntime(e),r,n);i&&t.images.push({...r,tag:`image`,data:{mimetype:`image/png`,path:i,size:{width:r.width,height:r.height}}})}}t.charts=n}}},CR=class extends ${static getters=[`getConditionalIcon`,`getCellConditionalFormatStyle`,`getConditionalDataBar`];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(zi.has(e.type)||Hi.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e))&&(this.isStale=!0)}finalize(){if(this.isStale){for(let e of this.getters.getSheetIds())this.computedStyles[e]=Et(()=>this.getComputedStyles(e)),this.computedIcons[e]=Et(()=>this.getComputedIcons(e)),this.computedDataBars[e]=Et(()=>this.getComputedDataBars(e));this.isStale=!1}}getCellConditionalFormatStyle(e){let{sheetId:t,col:n,row:r}=e,i=this.computedStyles[t]();return i&&i[n]?.[r]}getConditionalIcon({sheetId:e,col:t,row:n}){let r=this.computedIcons[e]();return r&&r[t]?.[n]}getConditionalDataBar({sheetId:e,col:t,row:n}){let r=this.computedDataBars[e]();return r&&r[t]?.[n]}getComputedStyles(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())switch(n.rule.type){case`ColorScaleRule`:for(let r of n.ranges)this.applyColorScale(e,r,n.rule,t);break;case`CellIsRule`:let r=n.rule.values.map(e=>e.startsWith(`=`)?kE(e):void 0);for(let i of n.ranges){let a=this.getters.getRangeFromSheetXC(e,i).zone;for(let i=a.top;i<=a.bottom;i++)for(let o=a.left;o<=a.right;o++){let s=this.rulePredicate[n.rule.type],c={sheetId:e,col:o,row:i},l=n.rule.values.map((t,n)=>{let s=r[n];return s?this.getters.getTranslatedCellFormula(e,o-a.left,i-a.top,s.tokens):t});s&&s(c,{...n.rule,values:l})&&(t[o]||(t[o]=[]),t[o][i]=Object.assign(t[o]?.[i]||{},n.rule.style))}}break}return t}getComputedIcons(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`IconSetRule`)for(let r of n.ranges)this.applyIcon(e,r,n.rule,t);return t}getComputedDataBars(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`DataBarRule`)for(let r of n.ranges)this.applyDataBar(e,r,n.rule,t);return t}parsePoint(e,t,n,r){let i=this.getters.getEvaluatedCellsInZone(e,this.getters.getRangeFromSheetXC(e,t).zone).filter(e=>e.type===`number`).map(e=>e.value);switch(n.type){case`value`:return r===`max`?Gt(i):Kt(i);case`number`:return Number(n.value);case`percentage`:let t=Kt(i);return t+(Gt(i)-t)*Number(n.value)/100;case`percentile`:return Mi(i,Number(n.value)/100,!0);case`formula`:let a=n.value&&this.getters.evaluateFormula(e,n.value);return typeof a==`number`?a:null;default:return null}}applyIcon(e,t,n,r){let i=this.parsePoint(e,t,n.lowerInflectionPoint),a=this.parsePoint(e,t,n.upperInflectionPoint);if(i===null||a===null||i>a)return;let o=this.getters.getRangeFromSheetXC(e,t).zone,s=[n.icons.upper,n.icons.middle,n.icons.lower];for(let t=o.top;t<=o.bottom;t++)for(let c=o.left;c<=o.right;c++){let o=this.getters.getEvaluatedCell({sheetId:e,col:c,row:t});if(o.type!==`number`)continue;let l=this.computeIcon(o.value,a,n.upperInflectionPoint.operator,i,n.lowerInflectionPoint.operator,s);r[c]||(r[c]=[]),r[c][t]=l}}computeIcon(e,t,n,r,i,a){return n===`ge`&&e>=t||n===`gt`&&e>t?a[0]:i===`ge`&&e>=r||i===`gt`&&e>r?a[1]:a[2]}applyDataBar(e,t,n,r){let i=this.getters.getRangeFromSheetXC(e,n.rangeValues||t),a=Gt(this.getters.getEvaluatedCellsInZone(e,i.zone).filter(e=>e.type===`number`).map(e=>e.value));if(a<=0)return;let o=n.color,s=this.getters.getRangeFromSheetXC(e,t).zone,c=i.zone;for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let i=n-s.left+c.left,l=t-s.top+c.top,u=this.getters.getEvaluatedCell({sheetId:e,col:i,row:l});!fr(i,l,c)||u.type!==`number`||u.value<=0||(r[n]||(r[n]=[]),r[n][t]={color:$t(o),percentage:u.value*100/a})}}applyColorScale(e,t,n,r){let i=this.parsePoint(e,t,n.minimum,`min`),a=n.midpoint?this.parsePoint(e,t,n.midpoint):null,o=this.parsePoint(e,t,n.maximum,`max`);if(i===null||o===null||i>=o||a!==null&&(i>=a||a>=o))return;let s=this.getters.getRangeFromSheetXC(e,t).zone,c=[];n.midpoint&&a!==null?(c.push({minValue:i,minColor:n.minimum.color,colorDiffUnit:this.computeColorDiffUnits(i,a,n.minimum.color,n.midpoint.color)}),c.push({minValue:a,minColor:n.midpoint.color,colorDiffUnit:this.computeColorDiffUnits(a,o,n.midpoint.color,n.maximum.color)})):c.push({minValue:i,minColor:n.minimum.color,colorDiffUnit:this.computeColorDiffUnits(i,o,n.minimum.color,n.maximum.color)});for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let s=this.getters.getEvaluatedCell({sheetId:e,col:n,row:t});if(s.type===`number`){let e=b(s.value,i,o),l;l=c.length===2&&a!==null?e<=a?this.colorCell(e,c[0].minValue,c[0].minColor,c[0].colorDiffUnit):this.colorCell(e,c[1].minValue,c[1].minColor,c[1].colorDiffUnit):this.colorCell(e,c[0].minValue,c[0].minColor,c[0].colorDiffUnit),r[n]||(r[n]=[]),r[n][t]=r[n]?.[t]||{},r[n][t].fillColor=$t(l)}}}computeColorDiffUnits(e,t,n,r){let i=t-e,a=(n>>16)%256-(r>>16)%256,o=(n>>8)%256-(r>>8)%256,s=n%256-r%256;return[a/i,o/i,s/i]}colorCell(e,t,n,r){let[i,a,o]=r,s=Math.round((n>>16)%256-i*(e-t)),c=Math.round((n>>8)%256-a*(e-t)),l=Math.round(n%256-o*(e-t));return s<<16|c<<8|l}rulePredicate={CellIsRule:(e,t)=>{let n=this.getters.getEvaluatedCell(e);if(n.type===`error`)return!1;let[r,i]=t.values.map(t=>t.startsWith(`=`)?this.getters.evaluateFormula(e.sheetId,t)??``:gs(t,O));if(k(r)||k(i))return!1;let a=n.value??``;switch(r??=``,i??=``,t.operator){case`IsEmpty`:return a.toString().trim()===``;case`IsNotEmpty`:return a.toString().trim()!==``;case`BeginsWith`:return r===``?!1:a.toString().startsWith(r.toString());case`EndsWith`:return r===``?!1:a.toString().endsWith(r.toString());case`Between`:return a>=r&&a<=i;case`NotBetween`:return!(a>=r&&a<=i);case`ContainsText`:return a.toString().indexOf(r.toString())>-1;case`NotContains`:return!a||a.toString().indexOf(r.toString())===-1;case`GreaterThan`:return a>r;case`GreaterThanOrEqual`:return a>=r;case`LessThan`:return a<r;case`LessThanOrEqual`:return a<=r;case`NotEqual`:return r===``?!1:a!==r;case`Equal`:return r===``?!0:a===r;default:console.warn(T(`Not implemented operator %s for kind of conditional formatting: %s`,t.operator,t.type))}return!1}}};let wR={isValid:!0};var TR=class extends ${static getters=[`getDataValidationInvalidCriterionValueMessage`,`getInvalidDataValidationMessage`,`getValidationResultForCellValue`,`isCellValidCheckbox`,`isDataValidationInvalid`];validationResults={};handle(e){if(zi.has(e.type)||e.type===`EVALUATE_CELLS`||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)){this.validationResults={};return}switch(e.type){case`ADD_DATA_VALIDATION_RULE`:case`REMOVE_DATA_VALIDATION_RULE`:delete this.validationResults[e.sheetId];break}}isDataValidationInvalid(e){return!this.getValidationResultForCell(e).isValid}getInvalidDataValidationMessage(e){let t=this.getValidationResultForCell(e);return t.isValid?void 0:t.error}getDataValidationInvalidCriterionValueMessage(e,t){let n=Q.get(e);return t.startsWith(`=`)?n.allowedValues===`onlyLiterals`?T(`The value must not be a formula`):void 0:n.allowedValues===`onlyFormulas`?T(`The value must be a formula`):n.isCriterionValueValid(t)?void 0:n.criterionValueErrorString}isCellValidCheckbox(e){if(!this.getters.isMainCellPosition(e))return!1;let t=this.getters.getValidationRuleForCell(e);return!t||t.criterion.type!==`isBoolean`?!1:this.getValidationResultForCell(e).isValid}getValidationResultForCellValue(e,t){let n=this.getters.getValidationRuleForCell(t);if(!n)return wR;let r=this.getRuleErrorForCellValue(e,t,n);return r?{error:r,rule:n,isValid:!1}:wR}getValidationResultForCell(e){let{col:t,row:n,sheetId:r}=e;return this.validationResults[r]||(this.validationResults[r]=this.computeSheetValidationResults(r)),this.validationResults[r][t]?.[n]?.()||wR}computeSheetValidationResults(e){let t={},n=this.getters.getDataValidationRules(e).map(e=>e.ranges);for(let e of Js(n.flat())){let{col:n,row:r}=e;t[n]||(t[n]=[]),t[n][r]=Et(()=>{let t=this.getters.getEvaluatedCell(e);return t.type===`empty`?wR:this.getValidationResultForCellValue(t.value,e)})}return t}getRuleErrorForCellValue(e,t,n){let{sheetId:r}=t,i=n.criterion,a=Q.get(i.type),o=this.getCellOffsetInRule(t,n),s=this.getEvaluatedCriterionValues(r,o,i),c={...i,values:s};if(!a.isValueValid(e,c,this.getters,r))return a.getErrorString(c,this.getters,r)}getCellOffsetInRule(e,t){let n=t.ranges.find(t=>fr(e.col,e.row,t.zone));if(!n)throw Error(`The cell is not in any range of the rule`);return{col:e.col-n.zone.left,row:e.row-n.zone.top}}getEvaluatedCriterionValues(e,t,n){return n.values.map(n=>{if(!n.startsWith(`=`))return n;let r=kE(n),i=this.getters.getTranslatedCellFormula(e,t.col,t.row,r.tokens),a=this.getters.evaluateFormula(e,i);return a&&!k(a)?a.toString():``})}},ER=class extends ${static getters=[`canCreateDynamicTableOnZones`,`doesZonesContainFilter`,`getFilter`,`getFilters`,`getTable`,`getTables`,`getTablesOverlappingZones`,`getFilterId`,`getFilterHeaders`,`isFilterHeader`];tables={};handle(e){if(zi.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;dr(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=>fr(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getTables(e).filter(e=>t.some(t=>dr(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(!Or(t))return!1;let n=sr(...t),r={col:n.left,row:n.top,sheetId:e},i=this.getters.getArrayFormulaSpreadingOn(r);return i?C(i,r)&&Dr(n)===1?!0:C(n,this.getters.getSpreadZone(i)):!1}coreTableToTable(e,t){if(t.type!==`dynamic`)return t;let n=t.range.zone,r={sheetId:e,col:n.left,row:n.top},i=this.getters.getSpreadZone(r)??t.range.zone,a=this.getters.getRangeFromZone(e,i),o=this.getDynamicTableFilters(e,t,i);return{id:t.id,range:a,filters:o,config:t.config}}getDynamicTableFilters(e,t,n){let r=[],{top:i,bottom:a,left:o,right:s}=n;for(let n=o;n<=s;n++){let s=n-o,c={left:n,right:n,top:i,bottom:a},l=JF(this.getDynamicTableFilterId(t.id,s),this.getters.getRangeFromZone(e,c),t.config,this.getters.getRangeFromZone);r.push(l)}return r}getDynamicTableFilterId(e,t){return e+`_`+t}isTableExcelExportable(e,t){return t.type===`dynamic`?!1:!vr(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=$n(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 vr(s.range.zone)){let r={sheetId:t.id,...n},i=this.getters.getCellComputedStyle(r),a=this.getters.getCellComputedBorder(r),o=w(n.col,n.row),s=t.cells?.[o]||{value:``,isFormula:!1};if(t.cells[o]||(t.cells[o]=s),!St(i)){let n=Fr(i,e.styles);t.styles[o]=n,s.style=n}if(a){let n=Fr(a,e.borders);t.borders[o]=n,s.border=n}}}t.tables=n}}},DR=class extends ${static getters=[`getRowSize`,`getHeaderSize`];tallestCellInRow={};ctx=document.createElement(`canvas`).getContext(`2d`);beforeHandle(e){switch(e.type){case`ADD_COLUMNS_ROWS`:if(e.dimension===`COL`)return;let t=Ot(e.position,e.base),n=Array(e.quantity).fill(void 0),r=Bt(this.tallestCellInRow[e.sheetId],n,t);this.history.update(`tallestCellInRow`,e.sheetId,r);break}}handle(e){switch(e.type){case`START`:case`UPDATE_LOCALE`:for(let e of this.getters.getSheetIds())this.initializeSheet(e);break;case`CREATE_SHEET`:this.initializeSheet(e.sheetId);break;case`DUPLICATE_SHEET`:{let t=y(this.tallestCellInRow[e.sheetId]);this.history.update(`tallestCellInRow`,e.sheetIdTo,t);break}case`DELETE_SHEET`:let t={...this.tallestCellInRow};delete t[e.sheetId],this.history.update(`tallestCellInRow`,t);break;case`REMOVE_COLUMNS_ROWS`:{if(e.dimension===`COL`)return;let t=zt(this.tallestCellInRow[e.sheetId],e.elements);this.history.update(`tallestCellInRow`,e.sheetId,t);break}case`RESIZE_COLUMNS_ROWS`:{let t=e.sheetId;if(e.dimension===`ROW`)for(let n of e.elements){let e=this.getRowTallestCell(t,n);this.history.update(`tallestCellInRow`,t,n,e)}else for(let n of x(0,this.getters.getNumberRows(t)))for(let r of e.elements)this.updateRowSizeForCellChange(t,n,r)}break;case`UPDATE_CELL`:this.updateRowSizeForCellChange(e.sheetId,e.row,e.col);break;case`ADD_MERGE`:case`REMOVE_MERGE`:for(let t of e.target)for(let n of vr(t))this.updateRowSizeForCellChange(e.sheetId,n.row,n.col)}}getRowSize(e,t){return Math.round(this.getters.getUserRowSize(e,t)??this.tallestCellInRow[e][t]?.size??23)}getHeaderSize(e,t,n){return this.getters.isHeaderHidden(e,t,n)?0:t===`ROW`?this.getRowSize(e,n):this.getters.getColSize(e,n)}updateRowSizeForCellChange(e,t,n){let r=this.tallestCellInRow[e]?.[t];if(r?.cell.col===n){let n=this.getRowTallestCell(e,t);this.history.update(`tallestCellInRow`,e,t,n)}let i=this.getCellHeight({sheetId:e,col:n,row:t});if(!(i<=23)&&(!r&&i>23||r&&i>r.size)){let r={cell:{sheetId:e,col:n,row:t},size:i};this.history.update(`tallestCellInRow`,e,t,r)}}initializeSheet(e){let t=[];for(let n=0;n<this.getters.getNumberRows(e);n++){let r=this.getRowTallestCell(e,n);t.push(r)}this.history.update(`tallestCellInRow`,e,t)}getCellHeight(e){if(this.isInMultiRowMerge(e))return 23;let t=this.getters.getCell(e),n=this.getters.getColSize(e.sheetId,e.col);return ic(this.ctx,t,this.getters.getLocale(),n)}isInMultiRowMerge(e){let t=this.getters.getMerge(e);return!!t&&t.bottom!==t.top}getRowTallestCell(e,t){if(this.getters.getUserRowSize(e,t)!==void 0)return;let n=this.getters.getRowCells(e,t),r=0,i;for(let e=0;e<n.length;e++){let t=this.getters.getCellById(n[e]);if(!t)continue;let a=this.getters.getCellPosition(t.id),o=this.getCellHeight(a);o>r&&o>23&&(r=o,i={cell:a,size:o})}if(i&&i.size>23)return i}};let OR=`0.00%`;function kR(e){class t extends e{getters;pivotId;cache={};rankAsc={};rankDesc={};runningTotal={};runningTotalInPercent={};constructor(e,t,n){super(t,n),this.getters=n.getters,this.pivotId=e}markAsDirtyForEvaluation(){this.cache={},this.rankAsc={},this.rankDesc={},this.runningTotal={},this.runningTotalInPercent={},super.markAsDirtyForEvaluation?.()}getPivotCellValueAndFormat(e,t){return this.getMeasureDisplayValue(e,t)}_getPivotCellValueAndFormat(e,t){let n=`${e}-${t.map(e=>e.field+`=`+e.value).join(`,`)}`;if(this.cache[n])return this.cache[n];let r=this.getMeasure(e),i=r.computedBy?this.computeMeasure(r,t):super.getPivotCellValueAndFormat(e,t);return r.format?this.cache[n]={...i,format:r.format}:this.cache[n]=i,this.cache[n]}computeMeasure(e,t){if(!e.computedBy)return{value:0};let{columns:n,rows:r}=super.definition;if(e.aggregator&&n.length+r.length!==t.length){let n=this.getValuesToAggregate(e,t),r=Ou[e.aggregator];if(!r)return{value:0};try{return r([n],this.getters.getLocale())}catch(t){return VT(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}=Yl(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new oa:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}if(r.find(t=>t.nameWithGranularity===e)){let{rowDomain:n}=Yl(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new oa:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}return this.getPivotCellValueAndFormat(e,t)});return k(a)?a[0][0]:a}getValuesToAggregate(e,t){let{rowDomain:n,colDomain:r}=Yl(this,t),i=this.getTableStructure(),a=[];if(r.length===0&&n.length<this.definition.rows.length&&this.definition.rows.length&&this.definition.columns.length){let t=this.treeToLeafDomains(i.getColTree()),r=this.getSubTreeMatchingDomain(i.getRowTree(),n),o=this.treeToLeafDomains(r);for(let r of t)for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t).concat(r)));return a}else if(n.length===this.definition.rows.length&&r.length===0){let t=i.getColTree(),o=this.getSubTreeMatchingDomain(t,r),s=this.treeToLeafDomains(o,r);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else if(n.length===this.definition.rows.length&&r.length&&r.length<this.definition.columns.length){let t=this.getSubTreeMatchingDomain(i.getColTree(),r),o=this.treeToLeafDomains(t,r);for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else{let t=i.getRowTree(),o=this.getSubTreeMatchingDomain(t,n),s=this.treeToLeafDomains(o,n);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,t.concat(r)));return a}}getSubTreeMatchingDomain(e,t,n=0){if(n>t.length)return[];if(t.length===n)return e;for(let r of e){let e=Lu(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:T(`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 VT(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:OR}}asPercentOfRowTotal(e,t,n){let r=this.getRowTotal(t.id,n);return r===0?{value:A.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:OR}}asPercentOfColumnTotal(e,t,n){let r=this.getColumnTotal(t.id,n);return r===0?{value:A.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:OR}}asPercentOfParentRowTotal(e,t,n){let r=ql(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:OR}}asPercentOfParentColumnTotal(e,t,n){let r=Jl(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:OR}}asPercentOfParentTotal(e,t,n,r){let{fieldNameWithGranularity:i}=r;if(!i)return e;if(!ru(i,n))return{value:``};let a=tu(this,i,n),o=this._getPivotCellValueAndFormat(t.id,a),s=this.measureValueToNumber(o);return s===0?{value:``}:{value:this.measureValueToNumber(e)/s,format:OR}}asIndex(e,t,n){let r=this.measureValueToNumber(e),i=this.getRowTotal(t.id,n),a=this.getColumnTotal(t.id,n),o=this.getGrandTotal(t.id);return i===0||a===0?{value: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}=Yl(this,n),u=ou(l),d=ou(c);return{value:s[u]?.[d]??``,format:i===`running_total`?e.format:OR}}asPercentOf(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!ru(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:OR}:s===void 0?{value:A.NullError}:{value:s/o,format:OR}}asDifferenceFrom(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!ru(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(!ru(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:OR}}asRank(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;if(!ru(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}=Yl(this,n),u=ou(l),d=ou(c);return{value:s[u]?.[d]??``}}computeRank(e,t,n){let r={},i=iu(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=Fa(o));for(let s of o){let o=ou(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=>ru(t,e.rowDomain)),l=Object.groupBy(c,e=>cu(e.rowDomain,t));for(let e in l)l[e]=Jt(l[e]||[],e=>e.value).filter(e=>e.value!==void 0).sort((e,t)=>n===`asc`?e.value-t.value:t.value-e.value);r[o]={};for(let e of c){let n=ou(Xl(this,i,e.domain)),a=l[cu(e.rowDomain,t)];if(!a)continue;let s=a.findIndex(t=>t.value===e.value);s!==-1&&(r[o][n]=s+1)}}return i===`row`?r:Yt(r)}computeRunningTotal(e,t,n){let r={},i=iu(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=Fa(o));for(let s of o){let o=ou(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=>ru(t,e.rowDomain));for(let e of l){let n=ou(e.rowDomain),i=lu(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=ou(n),a=lu(n,t),s=r[o][i]||0,l=c[a];r[o][i]=l?s/l:void 0}}return i===`row`?r:Yt(r)}getGrandTotal(e){let t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){let n=Yl(this,t).rowDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}getColumnTotal(e,t){let n=Yl(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)`?au(this,t,n,r):nu(t,n,r);if(C(i,t))return`sameValue`;if(!i||!Ql(this,i))throw new oa;let a=this._getPivotCellValueAndFormat(e.id,i);return this.strictMeasureValueToNumber(a)}getPivotValueCells(e){return this.getTableStructure().getPivotCells().map(t=>t.filter(t=>t.type===`VALUE`&&t.measure===e)).filter(e=>e.length>0)}measureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(!e.value)return 0;throw Error(`Value ${e.value} is not a number`)}strictMeasureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(e.value)throw Error(`Value ${e.value} is not a number`)}}return t}let AR=[`ADD_PIVOT`,`UPDATE_PIVOT`,`REMOVE_PIVOT`];function jR(e){return AR.includes(e.type)}var MR=class extends ${static getters=[`getPivot`,`getFirstPivotFunction`,`getPivotIdFromPosition`,`getPivotIdsFromPosition`,`getPivotCellFromPosition`,`generateNewCalculatedMeasureName`,`isPivotUnused`,`isSpillPivotFormula`];pivots={};unusedPivots;custom;constructor(e){super(e),this.custom=e.custom}beforeHandle(e){switch(e.type){case`START`:for(let e of this.getters.getPivotIds())this.setupPivot(e)}}handle(e){if(zi.has(e.type))for(let e of this.getters.getPivotIds())this.setupPivot(e,{recreate:!0});switch(e.type){case`REFRESH_PIVOT`:this.refreshPivot(e.id);break;case`ADD_PIVOT`:this.unusedPivots?.push(e.pivotId),this.setupPivot(e.pivotId);break;case`DUPLICATE_PIVOT`:this.unusedPivots?.push(e.newPivotId),this.setupPivot(e.newPivotId);break;case`UPDATE_PIVOT`:this.setupPivot(e.pivotId,{recreate:!0});break;case`DELETE_SHEET`:case`UPDATE_CELL`:this.unusedPivots=void 0;break;case`UNDO`:case`REDO`:{this.unusedPivots=void 0;let t=e.commands.filter(jR);for(let e of t){let t=e.pivotId;this.getters.isExistingPivot(t)&&this.setupPivot(t,{recreate:!0})}break}case`UPDATE_LOCALE`:kF();break}}getPivotIdFromPosition(e){return this.getPivotIdsFromPosition(e)[0]}getPivotIdsFromPosition(e){let t=this.getters.getCorrespondingFormulaCell(e);return t&&t.isFormula?this.getPivotIdsFromFormula(e.sheetId,t.compiledFormula):[]}getPivotIdsFromFormula(e,t){return this.getPivotFunctions(e,t.tokens).map(e=>{let t=e.args[0]?.toString();return t&&this.getters.getPivotId(t)}).filter(S)}isSpillPivotFormula(e){let t=this.getters.getCorrespondingFormulaCell(e);return t&&t.isFormula?this.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens)?.functionName===`PIVOT`:!1}getPivotFunctions(e,t){let n=qE(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=xC(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||JE(t.compiledFormula.tokens)===0)return gF;let n=this.getters.getCellPosition(t.id),r=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(!r)return gF;let{functionName:i,args:a}=r,o=a[0];if(!o)return gF;let s=this.getters.getPivotId(o.toString());if(!s)return gF;let c=this.getPivot(s);if(!c.isValid()||i===`PIVOT`&&!t.content.replaceAll(` `,``).toUpperCase().startsWith(`=PIVOT`))return gF;try{if(i===`PIVOT`){let t=Dl(a[2]),r=t===void 0?!0:L(t),i=Dl(a[3]),o=i===void 0?!0:L(i),s=c.getTableStructure().getPivotCells(r,o),l=e.col-n.col,u=e.row-n.row;return s[l][u]}let t=e.row-n.row,r=e.col-n.col;if(a=a.map(e=>k(e)?e[r][t]:e),i===`PIVOT.HEADER`&&a.at(-2)===`measure`)return{type:`MEASURE_HEADER`,domain:c.parseArgsToPivotDomain(a.slice(1,-2).map(e=>({value:e}))),measure:a.at(-1)?.toString()||``};if(i===`PIVOT.HEADER`)return{type:`HEADER`,domain:c.parseArgsToPivotDomain(a.slice(1).map(e=>({value:e})))};let[o,...s]=a.slice(1);return{type:`VALUE`,domain:c.parseArgsToPivotDomain(s.map(e=>({value:e}))),measure:o?.toString()||``}}catch{return gF}}generateNewCalculatedMeasureName(e){let t=e.map(e=>e.fieldName),n=1,r=T(`Calculated measure %s`,n);for(;t.includes(r);)n++,r=T(`Calculated measure %s`,n);return r}getPivot(e){if(!this.getters.isExistingPivot(e))throw Error(`pivot ${e} not found`);return this.pivots[e]}isPivotUnused(e){return this._getUnusedPivots().includes(e)}refreshPivot(e){this.getters.getPivot(e).init({reload:!0})}setupPivot(e,{recreate:t}={recreate:!1}){let n=y(this.getters.getPivotCoreDefinition(e));if(e in this.pivots)t&&this.pivots[e].onDefinitionChange(n);else{let t=kR(jF.get(n.type).ui);this.pivots[e]=new t(e,this.custom,{definition:n,getters:this.getters})}}_getUnusedPivots(){if(this.unusedPivots!==void 0)return this.unusedPivots;let e=new Set(this.getters.getPivotIds());for(let t of this.getters.getSheetIds())for(let n in this.getters.getCells(t)){let t=this.getters.getCellPosition(n),r=this.getPivotIdsFromPosition(t);for(let t of r)if(e.delete(t),!e.size)return this.unusedPivots=[],[]}for(let t of this.getters.getPivotIds()){let n=this.getters.getPivotCoreDefinition(t);for(let r of n.measures)if(r.computedBy){let{sheetId:n}=r.computedBy,i=this.getters.getMeasureCompiledFormula(t,r),a=this.getPivotIdsFromFormula(n,i);for(let t of a)if(e.delete(t),!e.size)return this.unusedPivots=[],[]}}return this.unusedPivots=[...e],this.unusedPivots}},NR=class{cells;getters;index=0;direction;constructor(e,t,n){this.cells=e,this.getters=t,this.direction=n}next(){let e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:n,tooltip:r}=eD.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:n,tooltip:r,origin:{col:e.data.col,row:e.data.row}}}},PR=class extends ${static layers=[`Autofill`];static getters=[`getAutofillTooltip`];autofillZone;steps;lastCellSelected={};direction;tooltip;allowDispatch(e){switch(e.type){case`AUTOFILL_SELECT`:let t=this.getters.getActiveSheetId();return this.lastCellSelected.col=e.col===-1?this.lastCellSelected.col:b(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=e.row===-1?this.lastCellSelected.row:b(e.row,0,this.getters.getNumberRows(t)),this.lastCellSelected.col!==void 0&&this.lastCellSelected.row!==void 0?`Success`:`InvalidAutofillSelection`}return`Success`}handle(e){switch(e.type){case`AUTOFILL`:this.autofill(!0);break;case`AUTOFILL_SELECT`:this.select(e.col,e.row);break;case`AUTOFILL_AUTO`:this.autofillAuto();break}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||this.direction===void 0){this.tooltip=void 0;return}let t=this.getters.getSelectedZone(),n=this.autofillZone,r=[];switch(this.direction){case`down`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.top;n<=t.bottom;n++)i.push(w(e,n));let a=this.createGenerator(i);for(let t=n.top;t<=n.bottom;t++)r.push(this.computeNewCell(a,e,t))}break;case`up`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.bottom;n>=t.top;n--)i.push(w(e,n));let a=this.createGenerator(i);for(let t=n.bottom;t>=n.top;t--)r.push(this.computeNewCell(a,e,t))}break;case`left`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.right;n>=t.left;n--)i.push(w(n,e));let a=this.createGenerator(i);for(let t=n.right;t>=n.left;t--)r.push(this.computeNewCell(a,t,e))}break;case`right`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.left;n<=t.right;n++)i.push(w(n,e));let a=this.createGenerator(i);for(let t=n.left;t<=n.right;t++)r.push(this.computeNewCell(a,t,e))}break}if(e){let e={},t={},n={},i=this.getters.getActiveSheetId();for(let a of r)this.collectBordersData(a,e),this.autofillMerge(i,a),this.autofillCell(i,a),this.collectConditionalFormatsData(i,a,t),this.collectDataValidationsData(i,a,n);this.autofillBorders(i,e),this.autofillConditionalFormats(i,t),this.autofillDataValidations(i,n),this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0}}collectBordersData(e,t){let n=JSON.stringify(e.border);n in t||(t[n]=[]),t[n].push(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=w(a,o);for(let e of s)e.id in n||(n[e.id]=[]),n[e.id].push(c)}collectDataValidationsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s={sheetId:e,col:r,row:i},c=this.getters.getValidationRuleForCell(s);c&&(c.id in n||(n[c.id]=[]),n[c.id].push(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:Fn(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($n),[]);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=Fn(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(fr(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=tD.getAll().sort((e,t)=>e.sequence-t.sequence).find(n=>n.condition(e,t));return n&&this.direction&&n.generateRule(e,t,this.direction)}createGenerator(e){let t=[],n=[],r=this.getters.getActiveSheetId();for(let t of e){let{col:e,row:i}=Pn(t),a=this.getters.getCell({sheetId:r,col:e,row:i});n.push({col:e,row:i,cell:a,sheetId:r})}let i=n.map(e=>e.cell);for(let e of n){let n={type:`COPY_MODIFIER`};e&&e.cell&&(n=this.getRule(e.cell,i)||n);let r=this.getters.getCellBorder(e)||void 0;t.push({data:{...e,border:r},rule:n})}return new NR(t,this.getters,this.direction)}saveZone(e,t,n,r){this.autofillZone={top:e,bottom:t,left:n,right:r}}getDirection(e,t){let n=this.getters.getSelectedZone(),r={up:{number:n.top-t,value:`up`},down:{number:t-n.bottom,value:`down`},left:{number:n.left-e,value:`left`},right:{number:e-n.right,value:`right`}};if(Object.values(r).map(e=>+(e.number>0)).reduce((e,t)=>e+t)===1)return Object.values(r).find(e=>+(e.number>0)).value;let i=r.up.number>0?`up`:`down`,a=r.left.number>0?`left`:`right`;return Math.abs(r[i].number)>=Math.abs(r[a].number)?r[i].value:r[a].value}autofillMerge(e,t){let{originCol:n,originRow:r,col:i,row:a}=t,o={sheetId:e,col:i,row:a},s={sheetId:e,col:n,row:r};if(this.getters.isInMerge(o)&&!this.getters.isInMerge(s)){let t=this.getters.getMerge(o);t&&this.dispatch(`REMOVE_MERGE`,{sheetId:e,target:[t]})}let c=this.getters.getMerge(s);c?.left===n&&c?.top===r&&this.dispatch(`ADD_MERGE`,{sheetId:e,target:[{top:a,bottom:a+c.bottom-c.top,left:i,right:i+c.right-c.left}]})}drawLayer(e){if(!this.autofillZone)return;let{ctx:t,thinLineWidth:n}=e,{x:r,y:i,width:a,height:o}=this.getters.getVisibleRect(this.autofillZone);a>0&&o>0&&(t.strokeStyle=`black`,t.lineWidth=n,t.setLineDash([3]),t.strokeRect(r,i,a,o),t.setLineDash([]))}},FR=class extends ${static getters=[`getAutomaticSums`];handle(e){switch(e.type){case`SUM_SELECTION`:let e=this.getters.getActiveSheetId(),{zones:t,anchor:n}=this.getters.getSelection();for(let r of t){let t=this.getAutomaticSums(e,r,n.cell);this.dispatchCellUpdates(e,t)}break}}getAutomaticSums(e,t,n){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,n):this.sumData(e,t)}sumData(e,t){let n=this.dimensionsToSum(e,t),r=this.sumDimensions(e,t,n).filter(({zone:t})=>!this.getters.isEmpty(e,t));return n.has(`ROW`)&&n.has(`COL`)&&r.push(this.sumTotal(t)),r}sumAdjacentData(e,t,n){let{col:r,row:i}=fr(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)||hr(sr(a,t))?[{position:{col:r,row:i},zone:a}]:this.sumDimensions(e,sr(a,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,n){let r=this.getters.getSheet(e),i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.findSuitableZoneToSum(r,i.col,i.row);if(a)return this.getters.expandZone(e,a)}findSuitableZoneToSum(e,t,n){let r=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:n-1}),i=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:n});if(this.isNumber(i)&&!this.isNumber(r))return this.findHorizontalZone(e,t,n);let a=this.findVerticalZone(e,t,n);if(this.isZoneValid(a))return a;let o=this.findHorizontalZone(e,t,n);if(this.isZoneValid(o))return o}findVerticalZone(e,t,n){let r={top:0,bottom:n-1,left:t,right:t},i=this.reduceZoneStart(e,r,r.bottom);return{...r,top:i}}findHorizontalZone(e,t,n){let r={top:n,bottom:n,left:0,right:t-1},i=this.reduceZoneStart(e,r,r.right);return{...r,left:i}}reduceZoneStart(e,t,n){let r=this.getters.getEvaluatedCellsInZone(e.id,t),i=x(n,-1,-1),a=Gt(i.filter(e=>r[e]&&!r[e].isAutoSummable)),o=ct(i.filter(e=>this.isNumber(r[e])))[0]||[];return Gt(o)<a?1/0:Kt(o)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===`number`&&!(e.format&&Ko(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 hr(t)?(n.add(mr(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)},vr(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)},vr(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`))}};wN.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],qR),wN.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],qR),wN.addTransformation(`ADD_COLUMNS_ROWS`,[`CREATE_CHART`,`UPDATE_CHART`],VR),wN.addTransformation(`REMOVE_COLUMNS_ROWS`,[`CREATE_CHART`,`UPDATE_CHART`],VR),wN.addTransformation(`DELETE_SHEET`,[`MOVE_RANGES`],zR),wN.addTransformation(`DELETE_FIGURE`,[`UPDATE_FIGURE`,`UPDATE_CHART`],BR),wN.addTransformation(`CREATE_SHEET`,[`CREATE_SHEET`],HR),wN.addTransformation(`ADD_MERGE`,[`ADD_MERGE`,`REMOVE_MERGE`],UR),wN.addTransformation(`ADD_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],WR),wN.addTransformation(`REMOVE_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],WR),wN.addTransformation(`ADD_COLUMNS_ROWS`,[`UPDATE_TABLE`],GR),wN.addTransformation(`REMOVE_COLUMNS_ROWS`,[`UPDATE_TABLE`],GR),wN.addTransformation(`REMOVE_TABLE_STYLE`,[`CREATE_TABLE`,`UPDATE_TABLE`],KR),wN.addTransformation(`ADD_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],JR),wN.addTransformation(`REMOVE_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],JR),wN.addTransformation(`REMOVE_PIVOT`,[`RENAME_PIVOT`,`DUPLICATE_PIVOT`,`INSERT_PIVOT`,`UPDATE_PIVOT`],RR),wN.addTransformation(`DELETE_SHEET`,[`ADD_PIVOT`,`UPDATE_PIVOT`],LR),wN.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],IR),wN.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],IR);function IR(e,t){if(e.pivot.type!==`SPREADSHEET`||e.pivot.dataSet?.sheetId!==t.sheetId)return e;let n=nd(e.pivot.dataSet.zone,t),r=n?{...e.pivot.dataSet,zone:n}:void 0;return{...e,pivot:{...e.pivot,dataSet:r}}}function LR(e,t){return e.pivot.type===`SPREADSHEET`&&e.pivot.dataSet?.sheetId===t.sheetId?{...e,pivot:{...e.pivot,dataSet:void 0}}:e}function RR(e,t){if(e.pivotId!==t.pivotId)return e}function zR(e,t){let n=t.sheetId;if(!(e.targetSheetId===n||e.sheetId===n))return e}function BR(e,t){if(e.id!==t.id)return e}function VR(e,t){return{...e,definition:yk(e.definition,t)}}function HR(e,t){return e.sheetId===t.sheetId&&(e={...e,sheetId:`${e.sheetId}~`}),e.name===t.name?{...e,name:e.name?.match(/\d+/)?e.name.replace(/\d+/,e=>(parseInt(e)+1).toString()):`${e.name}~`,position:e.position+1}:e}function UR(e,t){if(e.sheetId!==t.sheetId)return e;let n=[];for(let r of e.target)t.target.every(e=>!dr(r,e))&&n.push(r);if(n.length)return{...e,target:n}}function WR(e,t){if(e.sheetId!==t.sheetId||(e.type===`FREEZE_COLUMNS`?`COL`:`ROW`)!==t.dimension)return e;let n=e.quantity;if(t.type===`REMOVE_COLUMNS_ROWS`){let e=[...t.elements].sort((e,t)=>t-e);for(let t of e)n>t&&n--}if(t.type===`ADD_COLUMNS_ROWS`){let e=t.position===`before`?t.base-1:t.base;n=n>e?n+t.quantity:n}return n>0?{...e,quantity:n}:void 0}function GR(e,t){if(e.sheetId!==t.sheetId)return e;let n=nd(e.zone,t);if(!n)return;let r=e.newTableRange?rd(e.newTableRange,t):void 0;return{...e,newTableRange:r,zone:n}}function KR(e,t){return e.config?.styleId===t.tableStyleId?{...e,config:{...e.config,styleId:km.styleId}}:e}function qR(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n;if(t.type===`REMOVE_COLUMNS_ROWS`?n=$s(t.elements,[e.base])[0]:t.type===`ADD_COLUMNS_ROWS`&&(n=Qs(Ot(t.position,t.base),t.quantity,[e.base])[0]),n!==void 0)return{...e,base:n}}function JR(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n=x(e.start,e.end+1),r=[];if(t.type===`REMOVE_COLUMNS_ROWS`?r=$s(t.elements,n):t.type===`ADD_COLUMNS_ROWS`&&(r=Qs(Ot(t.position,t.base),t.quantity,n)),r.length!==0)return{...e,start:Math.min(...r),end:Math.max(...r)}}let YR=[{match:Ni,fn:$R},{match:Fi,fn:ez},{match:Ri,fn:tz},{match:Li,fn:iz},{match:Pi,fn:rz},{match:Ii,fn:nz}];function XR(e,t){let n=wN.getTransformation(e.type,t.type);return n?n(e,t):QR(e,t)}function ZR(e,t){let n=[...e],r=new Set(wN.getKeys());for(let e of t)r.has(e.type)&&(n=n.reduce((t,n)=>{let r=XR(n,e);return r&&t.push(r),t},[]));return n}function QR(e,t){for(let{match:n,fn:r}of YR)if(n(e)){let n=r(e,t);if(n===`SKIP_TRANSFORMATION`)continue;if(n===`IGNORE_COMMAND`)return;e=n}return e}function $R(e,t){if(!(`sheetId`in t))return e;let n=t.type===`DELETE_SHEET`&&t.sheetId;return e.sheetId===n?`IGNORE_COMMAND`:e.type===`CREATE_SHEET`||t.type===`CREATE_SHEET`||e.sheetId!==t.sheetId?e:`SKIP_TRANSFORMATION`}function ez(e,t){let n=$R(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=[];for(let n of e.target){let e=nd(n,t);e&&r.push(e)}return r.length?{...e,target:r}:`IGNORE_COMMAND`}function tz(e,t){let n=$R(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=nd(e.zone,t);return r?{...e,zone:r}:`IGNORE_COMMAND`}function nz(e,t){if(!(`sheetId`in t))return e;let n=e.ranges.map(e=>rd(e,t)).filter(S);return n.length?{...e,ranges:n}:`IGNORE_COMMAND`}function rz(e,t){let n=$R(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;if(t.type!==`ADD_COLUMNS_ROWS`&&t.type!==`REMOVE_COLUMNS_ROWS`)return`SKIP_TRANSFORMATION`;if(t.dimension!==e.dimension)return e;let r=[];return t.type===`REMOVE_COLUMNS_ROWS`?r=$s(t.elements,e.elements):t.type===`ADD_COLUMNS_ROWS`&&(r=Qs(Ot(t.position,t.base),t.quantity,e.elements)),r.length===0?`IGNORE_COMMAND`:{...e,elements:r}}function iz(e,t){let n=$R(e,t);return n===`SKIP_TRANSFORMATION`?t.type===`ADD_COLUMNS_ROWS`||t.type===`REMOVE_COLUMNS_ROWS`?az(e,t):t.type===`ADD_MERGE`?oz(e,t):`SKIP_TRANSFORMATION`:n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e}function az(e,t){let n=t.dimension===`COL`?`col`:`row`,r=e[n];if(t.type===`REMOVE_COLUMNS_ROWS`){let e=[...t.elements].sort((e,t)=>t-e);if(e.includes(r))return`IGNORE_COMMAND`;for(let t of e)r>=t&&r--}return t.type===`ADD_COLUMNS_ROWS`&&(r>t.base||r===t.base&&t.position===`before`)&&(r+=t.quantity),{...e,[n]:r}}function oz(e,t){for(let n of t.target)if(!(e.col===n.left&&e.row===n.top)&&fr(e.col,e.row,n))return`IGNORE_COMMAND`;return e}var sz=class{rootCommand;timestamp;id;clientId;_commands=[];_changes=[];constructor(e,t,n,r,i,a){this.rootCommand=r,this.timestamp=a,this.id=e,this.clientId=t,this._commands=[...n],this._changes=i?[...i]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}},cz=class extends Error{},lz=class extends id{revisions;transportService;serverRevisionId;clients={};clientId=`local`;debouncedMove;pendingMessages=[];waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;uuidGenerator=new Tc;lastLocalOperation;constructor(e,t,n=Ve){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=n,this.debouncedMove=Ct(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,n){if(!t.length||!n.length||!this.canApplyOptimisticUpdate())return;let r=new sz(this.uuidGenerator.uuidv4(),this.clientId,t,e,n,Date.now());this.revisions.append(r.id,r),e.type!==`REQUEST_REDO`&&(this.lastLocalOperation=r),this.trigger(`new-local-state-update`,{id:r.id}),this.sendUpdateMessage({type:`REMOTE_REVISION`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:r.id,clientId:r.clientId,commands:r.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_UNDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_REDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}move(e){this.debouncedMove(e)}join(e){e?(this.clients[e.id]=e,this.clientId=e.id):(this.clients.local={id:`local`,name:`local`},this.clientId=`local`),this.transportService.onNewMessage(this.clientId,this.onMessageReceived.bind(this))}loadInitialMessages(e){let t=performance.now(),n=e.reduce((e,t)=>e+(t.type===`REMOTE_REVISION`?t.commands.length:1),0);this.isReplayingInitialRevisions=!0;for(let t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1,console.debug(`Replayed`,n,`commands in`,performance.now()-t,`ms`)}async leave(e){e&&Object.keys(this.clients).length===1&&this.lastRevisionMessage&&this.lastRevisionMessage?.type!==`SNAPSHOT_CREATED`&&await this.snapshot(e()),delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.transportService.sendMessage({type:`CLIENT_LEFT`,clientId:this.clientId,version:1})}async snapshot(e){if(this.pendingMessages.length!==0)return;let t=this.uuidGenerator.uuidv4();await this.transportService.sendMessage({type:`SNAPSHOT`,nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getClient(){let e=this.clients[this.clientId];if(!e)throw new cz(`The client left the session`);return e}getConnectedClients(){return new Set(Object.values(this.clients).filter(S))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return this.pendingMessages.length===0}getLastLocalNonEmptyRevision(){return this.lastLocalOperation}_move(e){if(!this.clients[this.clientId])return;let t=this.clients[this.clientId]?.position;if(t?.col===e.col&&t.row===e.row&&t.sheetId===e.sheetId)return;let n=t?`CLIENT_MOVED`:`CLIENT_JOINED`,r=this.getClient();this.clients[this.clientId]={...r,position:e},this.transportService.sendMessage({type:n,version:1,client:{...r,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e)){if(this.isWrongServerRevisionId(e)){this.trigger(`unexpected-revision-id`);return}switch(e.type){case`CLIENT_MOVED`:this.onClientMoved(e);break;case`CLIENT_JOINED`:this.onClientJoined(e);break;case`CLIENT_LEFT`:this.onClientLeft(e);break;case`REVISION_REDONE`:this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger(`revision-redone`,{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case`REVISION_UNDONE`:this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger(`revision-undone`,{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case`REMOTE_REVISION`:let{clientId:t,commands:n,timestamp:r}=e,i=new sz(e.nextRevisionId,t,n,void 0,void 0,r);if(i.clientId!==this.clientId){this.revisions.insert(i.id,i,e.serverRevisionId);let t=this.pendingMessages.filter(e=>e.type===`REMOTE_REVISION`).map(e=>e.commands).flat();this.trigger(`remote-revision-received`,{commands:ZR(n,t)})}break;case`SNAPSHOT_CREATED`:{let t=new sz(e.nextRevisionId,`server`,[],void 0,void 0,Date.now());this.revisions.insert(t.id,t,e.serverRevisionId),this.dropPendingHistoryMessages(),this.trigger(`snapshot`),this.lastLocalOperation=void 0;break}}this.acknowledge(e),this.trigger(`collaborative-event-received`)}}onClientMoved(e){e.client.id!==this.clientId&&(this.clients[e.client.id]=e.client)}onClientJoined(e){if(e.client.id!==this.clientId){this.clients[e.client.id]=e.client;let t=this.clients[this.clientId];if(t){let{position:e}=t;e&&this.transportService.sendMessage({type:`CLIENT_MOVED`,version:1,client:{...t,position:e}})}}}onClientLeft(e){e.clientId!==this.clientId&&delete this.clients[e.clientId]}sendUpdateMessage(e){this.pendingMessages.push(e),!this.waitingAck&&this.sendPendingMessage()}sendPendingMessage(){let e=this.pendingMessages[0];if(e){if(e.type===`REMOTE_REVISION`){let t=this.revisions.get(e.nextRevisionId);t.commands.length===0&&(this.revisions.rebase(t.id),t=this.revisions.get(e.nextRevisionId)),e={...e,clientId:t.clientId,commands:t.commands}}if(this.isReplayingInitialRevisions)throw Error(`Trying to send a new revision while replaying initial revision. This can lead to endless dispatches every time the spreadsheet is open.
|
|
1897
|
+
`;var TL=class extends t.Component{static template=`o_spreadsheet.PivotHTMLRenderer`;static components={Checkbox:EN};static props={pivotId:String,onCellClicked:Function};pivot=this.env.model.getters.getPivot(this.props.pivotId);data={columns:[],rows:[],values:[]};state=(0,t.useState)({showMissingValuesOnly:!1});setup(){let e=this.pivot.getTableStructure(),t=this.env.model.getters.getPivotFormulaId(this.props.pivotId);this.data={columns:this._buildColHeaders(t,e),rows:this._buildRowHeaders(t,e),values:this._buildValues(t,e)}}get tracker(){return this.env.model.getters.getPivotPresenceTracker(this.props.pivotId)}getTableData(){if(!this.state.showMissingValuesOnly)return this.data;let e=this.getColumnsIndexes(),t=this.getRowsIndexes();return{columns:this.buildColumnsMissing(e),rows:this.buildRowsMissing(t),values:this.buildValuesMissing(e,t)}}addRecursiveRow(e){let t=this.pivot.getTableStructure().rows,n=[...t[e].values];if(n.length<=1)return[e];n.pop();let r=t.findIndex(e=>JSON.stringify(e.values)===JSON.stringify(n));return[e].concat(this.addRecursiveRow(r))}buildColumnsMissing(e){let t=[];for(let e of this.data.columns){let n=[];for(let t in e)for(let r=0;r<e[t].span;r++)n.push(parseInt(t,10));t.push(n)}for(let n=t[t.length-1].length;n>=0;n--)if(!e.includes(n))for(let e of t)e.splice(n,1);let n=[];for(let e in t){let r=[],i,a=1;for(let n=0;n<t[e].length;n++)i===t[e][n]?a++:(i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),i=t[e][n],a=1);i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),n.push(r)}return n}buildRowsMissing(e){return e.map(e=>this.data.rows[e])}buildValuesMissing(e,t){let n=e.map(()=>[]);for(let r of t)for(let t in e)n[t].push(this.data.values[e[t]][r]);return n}getColumnsIndexes(){let e=new Set;for(let t=0;t<this.data.columns.length;t++){let n=[];for(let e=0;e<this.data.columns[t].length;e++)for(let r=0;r<this.data.columns[t][e].span;r++)n.push(this.data.columns[t][e]);for(let t=0;t<n.length;t++)n[t].isMissing&&e.add(t)}for(let t=0;t<this.data.columns[this.data.columns.length-1].length;t++)this.data.values[t].find(e=>e.isMissing)&&e.add(t);return Array.from(e).sort((e,t)=>e-t)}getRowsIndexes(){let e=new Set;for(let t=0;t<this.data.rows.length;t++){this.data.rows[t].isMissing&&e.add(t);for(let n of this.data.values)n[t].isMissing&&this.addRecursiveRow(t).forEach(t=>e.add(t))}return Array.from(e).sort((e,t)=>e-t)}_buildColHeaders(e,t){let n=[];for(let r of t.columns){let t=[];for(let n of r){let r=[];for(let e=0;e<n.fields.length;e++)r.push({value:n.fields[e]},{value:n.values[e]});let i=this.pivot.parseArgsToPivotDomain(r),a=this.env.model.getters.getLocale();if(i.at(-1)?.field===`measure`){let{value:r,format:o}=this.pivot.getPivotMeasureValue(F(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${Pu(e,i).join(`,`)})`,value:B(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}else{let{value:r,format:o}=this.pivot.getPivotHeaderValueAndFormat(i);t.push({formula:`=PIVOT.HEADER(${Pu(e,i).join(`,`)})`,value:B(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}}n.push(t)}let r=n[n.length-1];return n[n.length-1]=r.map(e=>(e.isMissing||(e.style=`color: #756f6f;`),e)),n}_buildRowHeaders(e,t){let n=[];for(let r of t.rows){let t=[];for(let e=0;e<r.fields.length;e++)t.push({value:r.fields[e]},{value:r.values[e]});let i=this.pivot.parseArgsToPivotDomain(t),{value:a,format:o}=this.pivot.getPivotHeaderValueAndFormat(i),s=this.env.model.getters.getLocale(),c={formula:`=PIVOT.HEADER(${Pu(e,i).join(`,`)})`,value:B(a,{format:o,locale:s}),isMissing:!this.tracker?.isHeaderPresent(i)};r.indent>1&&(c.style=`padding-left: ${r.indent-10}px`),n.push(c)}return n}_buildValues(e,t){let n=[];for(let r of t.columns.at(-1)||[]){let i=[],a=F(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(${Pu(e,o,a).join(`,`)})`,value:B(s,{format:c,locale:l}),isMissing:!this.tracker?.isValuePresent(a,o)})}n.push(i)}return n}},EL=class{static getters=[];history;dispatch;canDispatch;constructor(e,t,n){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}}),this.dispatch=t,this.canDispatch=n}exportForExcel(e){}allowDispatch(e){return`Success`}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map(e=>e.call(this,t)).flat()}chainValidations(...e){return t=>{for(let n of e){let e=n.call(this,t);Array.isArray(e)||(e=[e]);let r=e.filter(e=>e!==`Success`);if(r.length)return r}return`Success`}}checkValidations(e,...t){return this.batchValidations(...t)(e)}},DL=class extends EL{getters;uuidGenerator;constructor({getters:e,stateObserver:t,range:n,dispatch:r,canDispatch:i,uuidGenerator:a}){super(t,r,i),n.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.uuidGenerator=a}import(e){}export(e){}adaptRanges(e,t){}garbageCollectExternalResources(){}},OL=class extends DL{static getters=[`getCellBorder`,`getBordersColors`];borders={};allowDispatch(e){switch(e.type){case`SET_BORDER`:return this.checkBordersUnchanged(e);default:return`Success`}}handle(e){switch(e.type){case`ADD_MERGE`:for(let t of e.target)this.addBordersToMerge(e.sheetId,t);break;case`DUPLICATE_SHEET`:let t=this.borders[e.sheetId];if(t){let n=t.slice().map(e=>e?.slice().map(e=>({...e})));this.history.update(`borders`,e.sheetIdTo,n)}break;case`DELETE_SHEET`:let n={...this.borders};delete n[e.sheetId],this.history.update(`borders`,n);break;case`SET_BORDER`:this.setBorder(e.sheetId,e.col,e.row,e.border);break;case`SET_BORDERS_ON_TARGET`:for(let t of e.target)for(let n=t.top;n<=t.bottom;n++)for(let r=t.left;r<=t.right;r++)this.setBorder(e.sheetId,r,n,e.border);break;case`SET_ZONE_BORDERS`:if(e.border){let t=e.target.map(t=>this.getters.expandZone(e.sheetId,t));this.setBorders(e.sheetId,t,e.border.position,e.border.color===``?void 0:{style:e.border.style||Be.style,color:e.border.color||Be.color})}break;case`CLEAR_FORMATTING`:this.clearBorders(e.sheetId,e.target);break;case`REMOVE_COLUMNS_ROWS`:let r=[...e.elements].sort((e,t)=>t-e);for(let t of ct(r))if(e.dimension===`COL`){if(t[0]>=this.getters.getNumberCols(e.sheetId))for(let n=0;n<this.getters.getNumberRows(e.sheetId);n++)this.history.update(`borders`,e.sheetId,t[0]+1,n,`vertical`,void 0);if(t[t.length-1]===0)for(let t=0;t<this.getters.getNumberRows(e.sheetId);t++)this.history.update(`borders`,e.sheetId,0,t,`vertical`,void 0);let n=this.getters.getColsZone(e.sheetId,t[t.length-1]+1,t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersHorizontally(e.sheetId,t[0]+1,-t.length)}else{if(t[0]>=this.getters.getNumberRows(e.sheetId))for(let n=0;n<this.getters.getNumberCols(e.sheetId);n++)this.history.update(`borders`,e.sheetId,n,t[0]+1,`horizontal`,void 0);if(t[t.length-1]===0)for(let t=0;t<this.getters.getNumberCols(e.sheetId);t++)this.history.update(`borders`,e.sheetId,t,0,`horizontal`,void 0);let n=this.getters.getRowsZone(e.sheetId,t[t.length-1]+1,t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersVertically(e.sheetId,t[0]+1,-t.length)}break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumns(e):this.handleAddRows(e);break}}handleAddColumns(e){let t,n;e.position===`before`?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity,{moveFirstLeftBorder:!0}),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity,{moveFirstLeftBorder:!1}),t=e.base,n=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,n)}handleAddRows(e){let t,n;e.position===`before`?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity,{moveFirstTopBorder:!0}),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity,{moveFirstTopBorder:!1}),t=e.base,n=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,n)}getCellBorder({sheetId:e,col:t,row:n}){let r={top:this.borders[e]?.[t]?.[n]?.horizontal,bottom:this.borders[e]?.[t]?.[n+1]?.horizontal,left:this.borders[e]?.[t]?.[n]?.vertical,right:this.borders[e]?.[t+1]?.[n]?.vertical};return!r.bottom&&!r.left&&!r.right&&!r.top?null:r}getBordersColors(e){let t=[],n=this.borders[e];if(n)for(let e of n.filter(S))for(let n of e)n?.horizontal&&t.push(n.horizontal.color),n?.vertical&&t.push(n.vertical.color);return t}ensureColumnBorderContinuity(e,t,n){let r=x(t+1,n);for(let i=0;i<this.getters.getNumberRows(e);i++){let a=this.getCellBorder({sheetId:e,col:t,row:i}),o=this.getCellBorder({sheetId:e,col:n,row:i});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,n,i,t)}}}ensureRowBorderContinuity(e,t,n){let r=x(t+1,n);for(let i=0;i<this.getters.getNumberCols(e);i++){let a=this.getCellBorder({sheetId:e,col:i,row:t}),o=this.getCellBorder({sheetId:e,col:i,row:n});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,i,n,t)}}}getCommonSides(e,t){let n={};for(let r of[`top`,`bottom`,`left`,`right`])e[r]&&C(e[r],t[r])&&(n[r]=e[r]);return n}getColumnsWithBorders(e){let t=this.borders[e];return t?Object.keys(t).map(e=>parseInt(e,10)):[]}getRowsWithBorders(e){let t=this.borders[e]?.filter(S);if(!t)return[];let n=new Set;for(let e of t)for(let t in e)n.add(parseInt(t,10));return Array.from(n)}getRowsRange(e){return this.borders[e]?x(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,n,{moveFirstLeftBorder:r}={}){this.borders[e]&&(n<0&&this.moveBordersOfColumn(e,t,n,`vertical`,{destructive:!1}),this.getColumnsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(i=>{(i===t&&r||i!==t)&&this.moveBordersOfColumn(e,i,n,`vertical`),this.moveBordersOfColumn(e,i,n,`horizontal`)}))}shiftBordersVertically(e,t,n,{moveFirstTopBorder:r}={}){this.borders[e]&&(n<0&&this.moveBordersOfRow(e,t,n,`horizontal`,{destructive:!1}),this.getRowsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(i=>{(i===t&&r||i!==t)&&this.moveBordersOfRow(e,i,n,`horizontal`),this.moveBordersOfRow(e,i,n,`vertical`)}))}moveBordersOfRow(e,t,n,r,{destructive:i}={destructive:!0}){let a=this.borders[e];a&&this.getColumnsWithBorders(e).forEach(o=>{let s=a[o]?.[t+n]?.[r],c=a[o]?.[t]?.[r];this.history.update(`borders`,e,o,t+n,r,i?c:c||s),this.history.update(`borders`,e,o,t,r,void 0)})}moveBordersOfColumn(e,t,n,r,{destructive:i}={destructive:!0}){let a=this.borders[e];a&&this.getRowsRange(e).forEach(o=>{let s=a[t+n]?.[o]?.[r],c=a[t]?.[o]?.[r];this.history.update(`borders`,e,t+n,o,r,i?c:c||s),this.history.update(`borders`,e,t,o,r,void 0)})}setBorder(e,t,n,r,i=!0){(i||!this.borders?.[e]?.[t]?.[n]?.vertical)&&this.history.update(`borders`,e,t,n,`vertical`,r?.left),(i||!this.borders?.[e]?.[t]?.[n]?.horizontal)&&this.history.update(`borders`,e,t,n,`horizontal`,r?.top),(i||!this.borders?.[e]?.[t+1]?.[n]?.vertical)&&this.history.update(`borders`,e,t+1,n,`vertical`,r?.right),(i||!this.borders?.[e]?.[t]?.[n+1]?.horizontal)&&this.history.update(`borders`,e,t,n+1,`horizontal`,r?.bottom)}clearBorders(e,t){for(let n of Fn(t)){for(let t=n.top;t<=n.bottom;t++){this.history.update(`borders`,e,n.right+1,t,`vertical`,void 0);for(let r=n.left;r<=n.right;r++)this.history.update(`borders`,e,r,t,void 0)}for(let t=n.left;t<=n.right;t++)this.history.update(`borders`,e,t,n.bottom+1,`horizontal`,void 0)}}clearInsideBorders(e,t){for(let n of t)for(let t=n.top;t<=n.bottom;t++)for(let r=n.left;r<=n.right;r++)this.history.update(`borders`,e,r,t,void 0)}addBorder(e,t,n,r){this.setBorder(e,t,n,{...this.getCellBorder({sheetId:e,col:t,row:n}),...r})}setBorders(e,t,n,r){if(n===`clear`)return this.clearBorders(e,t);for(let i of Fn(t)){if(n===`h`||n===`hv`||n===`all`)for(let t=i.top+1;t<=i.bottom;t++)for(let n=i.left;n<=i.right;n++)this.addBorder(e,n,t,{top:r});if(n===`v`||n===`hv`||n===`all`)for(let t=i.top;t<=i.bottom;t++)for(let n=i.left+1;n<=i.right;n++)this.addBorder(e,n,t,{left:r});if(n===`left`||n===`all`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.left,t,{left:r});if(n===`right`||n===`all`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.right+1,t,{left:r});if(n===`top`||n===`all`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.top,{top:r});if(n===`bottom`||n===`all`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.bottom+1,{top:r})}}addBordersToMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t,o=this.getCellBorder({sheetId:e,col:n,row:i}),s=this.getCellBorder({sheetId:e,col:r,row:a});this.clearBorders(e,[t]),o?.top&&this.setBorders(e,[{...t,bottom:i}],`top`,o.top),o?.left&&this.setBorders(e,[{...t,right:n}],`left`,o.left),s?.bottom?this.setBorders(e,[{...t,top:a}],`bottom`,s.bottom):o?.bottom&&this.setBorders(e,[{...t,top:a}],`bottom`,o.bottom),s?.right?this.setBorders(e,[{...t,left:r}],`right`,s.right):o?.right&&this.setBorders(e,[{...t,left:r}],`right`,o.right)}checkBordersUnchanged(e){let t=this.getCellBorder(e),n=!e.border?.bottom&&!e.border?.left&&!e.border?.right&&!e.border?.top;return!t&&n||C(t,e.border)?`NoChanges`:`Success`}import(e){if(Object.keys(e.borders||{}).length)for(let t of e.sheets)for(let n in t.borders){let r=t.borders[n],i=e.borders[r],a=$n(n);for(let e=a.top;e<=a.bottom;e++)for(let n=a.left;n<=a.right;n++)this.setBorder(t.id,n,e,i,!1)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,$n(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=Fr(a,t),s={sheetId:n.id,col:r,row:i};e[o]??=[],e[o].push(s)}}n.borders=Ir(e)}e.borders=t}exportForExcel(e){for(let t of e.sheets)for(let n=0;n<t.colNumber;n++)for(let r=0;r<t.rowNumber;r++){let i=this.getCellBorder({sheetId:t.id,col:n,row:r});if(i){let a=w(n,r);t.cells[a]??={},t.cells[a].border=Fr(i,e.borders)}}}},kL=class{map={};set({sheetId:e,col:t,row:n},r){let i=this.map;i[e]||(i[e]={}),i[e][t]||(i[e][t]={}),i[e][t][n]=r}get({sheetId:e,col:t,row:n}){return this.map[e]?.[t]?.[n]}getSheet(e){return this.map[e]}has({sheetId:e,col:t,row:n}){return this.map[e]?.[t]?.[n]!==void 0}delete({sheetId:e,col:t,row:n}){delete this.map[e]?.[t]?.[n]}keys(){let e=this.map,t=[];for(let n in e)for(let r in e[n])for(let i in e[n][r])t.push({sheetId:n,col:parseInt(r),row:parseInt(i)});return t}keysForSheet(e){let t=this.map[e];if(!t)return[];let n=[];for(let r in t)for(let i in t[r])n.push({sheetId:e,col:parseInt(r),row:parseInt(i)});return n}},AL=class extends DL{static getters=[`zoneToXC`,`getCells`,`getTranslatedCellFormula`,`getCellStyle`,`getCellById`,`getFormulaString`,`getFormulaMovedInSheet`];nextId=1;cells={};adaptRanges(e,t){for(let n of Object.keys(this.cells))for(let r of Object.values(this.cells[n]||{}))if(r.isFormula){for(let i of r.compiledFormula.dependencies)if(!t||i.sheetId===t){let t=e(i);t.changeType!==`NONE`&&this.history.update(`cells`,n,r.id,`compiledFormula`,`dependencies`,r.compiledFormula.dependencies.indexOf(i),t.range)}}}allowDispatch(e){switch(e.type){case`UPDATE_CELL`:return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessUpdateCell);case`CLEAR_CELL`:return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessClearCell);case`UPDATE_CELL_POSITION`:return!e.cellId||this.cells[e.sheetId]?.[e.cellId]?`Success`:`InvalidCellId`;default:return`Success`}}handle(e){switch(e.type){case`SET_FORMATTING`:`style`in e&&this.setStyle(e.sheetId,e.target,e.style),`format`in e&&e.format!==void 0&&this.setFormatter(e.sheetId,e.target,e.format);break;case`CLEAR_FORMATTING`:this.clearFormatting(e.sheetId,e.target);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case`UPDATE_CELL`:this.updateCell(e.sheetId,e.col,e.row,e);break;case`CLEAR_CELL`:this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col,row:e.row,content:``,style:null,format:``});break;case`CLEAR_CELLS`:this.clearCells(e.sheetId,e.target);break;case`DELETE_CONTENT`:this.clearZones(e.sheetId,e.target);break;case`DELETE_SHEET`:this.history.update(`cells`,e.sheetId,void 0)}}clearZones(e,t){for(let n of Fn(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.getters.getCell({sheetId:e,col:t,row:r})&&this.dispatch(`UPDATE_CELL`,{sheetId:e,content:``,col:t,row:r})}setFormatter(e,t,n){for(let r of Fn(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 Fn(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,style:null,format:``})}clearCells(e,t){for(let n of t)for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,content:``,style:null,format:``})}handleAddColumnsRows(e,t){let n,r;e.position===`before`?(n=x(e.base,e.base+e.quantity),r=e.base+e.quantity):(n=x(e.base+1,e.base+e.quantity+1),r=e.base),t(e.sheetId,r,n)}import(e){for(let t of e.sheets){let n=t.id,r=new kL;for(let e in t.cells)if(t.cells[e]?.content){let{col:n,row:i}=Pn(e),a={sheetId:t.id,col:n,row:i};r.set(a,{content:t.cells[e]?.content})}for(let[e,i]of[[`style`,t.styles],[`format`,t.formats]])for(let t in i){let a=i[t],o=$n(t);for(let t=o.top;t<=o.bottom;t++)for(let i=o.left;i<=o.right;i++){let o={sheetId:n,col:i,row:t},s=r.get(o);s?s[e]=a:r.set(o,{[e]:a})}}for(let i of r.keysForSheet(n)){let n=r.get(i);if(n?.content||n?.format||n?.style){let r=this.importCell(t.id,n?.content,n?.style?e.styles[n?.style]:void 0,n?.format?e.formats[n?.format]:void 0);this.history.update(`cells`,t.id,r.id,r),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:r.id,...i})}}}}export(e){let t={},n={};for(let r of e.sheets){let e=[],i=[],a={},o=Object.keys(this.cells[r.id]||{}).map(e=>this.getters.getCellPosition(e)).sort((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col);for(let r of o){let o=this.getters.getCell(r),s=w(r.col,r.row),c=this.extractCustomStyle(o);if(Object.keys(c).length){let n=Fr(c,t);e[n]??=[],e[n].push(r)}if(o.format){let e=Fr(o.format,n);i[e]??=[],i[e].push(r)}o.content&&(a[s]={content:o.content})}r.styles=Ir(e),r.formats=Ir(i),r.cells=a}e.styles=t,e.formats=n}importCell(e,t,n,r){let i=this.getNextUid();return this.createCell(i,t||``,r,n,e)}exportForExcel(e){this.export(e);for(let t of e.sheets)for(let n in this.getters.getCells(t.id)){let{col:r,row:i}=this.getters.getCellPosition(n),a=w(r,i),o=this.getCellById(n);t.cells[a]??={},o?.format&&(t.cells[a].format=Fr(o.format,e.formats)),o?.style&&(t.cells[a]??={},t.cells[a].style=Fr(this.extractCustomStyle(o),e.styles))}let t=[];for(let n in e.formats||[])ps(e.formats[n])||(t.push(n),delete e.formats[n]);if(t.length)for(let n of e.sheets)for(let e in n.cells){let r=n.cells[e],i=r?.format;i&&t.includes(i.toString())&&delete r.format}}extractCustomStyle(e){let t={...e.style},n=ki(e.content,O)?Fe:Pe;for(let r in t)(r!==`align`||!e.isFormula)&&t[r]===n[r]&&delete t[r];return t}getCells(e){return this.cells[e]||{}}getCellById(e){let t=this.getters.getCellPosition(e);return this.cells[t.sheetId][e]}getFormulaString(e,t,n,r=!1){if(!n.length)return Tt(t.map(e=>e.value));let i=0;return Tt(t.map(t=>{if(t.type===`REFERENCE`){let t=n[i++];return this.getters.getRangeString(t,e,{useBoundedReference:r})}return t.value}))}getTranslatedCellFormula(e,t,n,r){let i=this.getters.createAdaptedRanges(AE(r).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),t,n,e);return this.getFormulaString(e,r,i)}getFormulaMovedInSheet(e,t,n){let r=AE(n).dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t)),i=this.getters.removeRangesSheetPrefix(t,r);return this.getFormulaString(t,n,i)}getCellStyle(e){return this.getters.getCell(e)?.style||{}}zoneToXC(e,t,n=[{colFixed:!1,rowFixed:!1}]){t=this.getters.expandZone(e,t);let r=w(t.left,t.top,n[0]),i=w(t.right,t.bottom,n.length>1?n[1]:n[0]),a=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),o=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),s=a.col===o.col&&a.row===o.row;return r!==i&&!s?r+`:`+i:r}setStyle(e,t,n){for(let r of Fn(t))for(let t=r.left;t<=r.right;t++)for(let i=r.top;i<=r.bottom;i++){let r=this.getters.getCell({sheetId:e,col:t,row:i});this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:i,style:n?{...r?.style,...n}:void 0})}}copyColumnStyle(e,t,n){for(let r=0;r<this.getters.getNumberRows(e);r++){let i=this.getFormat(e,t,r);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,...i})}}copyRowStyle(e,t,n){for(let r=0;r<this.getters.getNumberCols(e);r++){let i=this.getFormat(e,r,t);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:r,row:t,...i})}}getFormat(e,t,n){let r={},i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.getters.getCell(i);return a&&(a.style&&(r.style=a.style),a.format&&(r.format=a.format)),r}getNextUid(){let e=this.nextId.toString();return this.history.update(`nextId`,this.nextId+1),e}updateCell(e,t,n,r){let i=this.getters.getCell({sheetId:e,col:t,row:n}),a=r.content!==void 0||`formula`in r,o=a?It(r?.content||void 0):i?.content||``,s;s=r.style===void 0?i?i.style:void 0:r.style||void 0;let c=r.format===void 0?i&&i.format:r.format;if((a&&!o&&!r.formula||!a&&(!i||i.content===``))&&!s&&!c){i&&(this.history.update(`cells`,e,i.id,void 0),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:void 0,col:t,row:n,sheetId:e}));return}let l=i?.id||this.getNextUid(),u=this.createCell(l,o,c,s,e);this.history.update(`cells`,e,u.id,u),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:u.id,col:t,row:n,sheetId:e})}createCell(e,t,n,r,i){return t.startsWith(`=`)?this.createFormulaCell(e,t,n,r,i):this.createLiteralCell(e,t,n,r)}createLiteralCell(e,t,n,r){let i=this.getters.getLocale(),a=gs(t,i);return n||=typeof a==`number`?Zo(t,i)||Qo(t):void 0,!ms(n)&&!N(t)&&(t=F(a)),{id:e,content:t,style:r,format:n,isFormula:!1,parsedValue:a}}createFormulaCell(e,t,n,r,i){let a=kE(t);return a.dependencies.length?this.createFormulaCellWithDependencies(e,a,n,r,i):{id:e,content:t,style:r,format:n,isFormula:!0,compiledFormula:{...a,dependencies:[]}}}createFormulaCellWithDependencies(e,t,n,r,i){let a=[];for(let e of t.dependencies)a.push(this.getters.getRangeFromSheetXC(i,e));return new jL(e,t,n,r,a,i,this.getters.getRangeString)}checkCellOutOfSheet(e){let{sheetId:t,col:n,row:r}=e;return this.getters.tryGetSheet(t)?fr(n,r,this.getters.getSheetZone(t))?`Success`:`TargetOutOfSheet`:`InvalidSheetId`}checkUselessClearCell(e){let t=this.getters.getCell(e);return!t||!t.content&&!t.style&&!t.format?`NoChanges`:`Success`}checkUselessUpdateCell(e){let t=this.getters.getCell(e),n=`content`in e||`formula`in e,r=`style`in e,i=`format`in e;return(!n||t?.content===e.content)&&(!r||C(t?.style,e.style))&&(!i||t?.format===e.format)?`NoChanges`:`Success`}},jL=class{id;format;style;sheetId;getRangeString;isFormula=!0;compiledFormula;constructor(e,t,n,r,i,a,o){this.id=e,this.format=n,this.style=r,this.sheetId=a,this.getRangeString=o;let s=0,c=t.tokens.map(e=>e.type===`REFERENCE`?new ML(i,s++,this.sheetId,this.getRangeString):e);this.compiledFormula={...t,dependencies:i,tokens:c}}get content(){return Tt(this.compiledFormula.tokens.map(e=>e.value))}get contentWithFixedReferences(){let e=0;return Tt(this.compiledFormula.tokens.map(t=>{if(t.type===`REFERENCE`){let t=e++;return this.getRangeString(this.compiledFormula.dependencies[t],this.sheetId,{useBoundedReference:!0})}return t.value}))}},ML=class{ranges;rangeIndex;sheetId;getRangeString;type=`REFERENCE`;constructor(e,t,n,r){this.ranges=e,this.rangeIndex=t,this.sheetId=n,this.getRangeString=r}get value(){let e=this.ranges[this.rangeIndex];return this.getRangeString(e,this.sheetId)}},NL=class extends DL{static getters=[`isChartDefined`,`getChartDefinition`,`getChartType`,`getChartIds`,`getChart`,`getContextCreationChart`];charts={};createChart=gk(this.getters);validateChartDefinition=e=>vk(this,e.definition);adaptRanges(e){for(let[t,n]of Object.entries(this.charts))this.history.update(`charts`,t,n?.updateRanges(e))}allowDispatch(e){switch(e.type){case`CREATE_CHART`:return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartDuplicate));case`UPDATE_CHART`:return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartExists));default:return`Success`}}handle(e){switch(e.type){case`CREATE_CHART`:this.addFigure(e.id,e.sheetId,e.position,e.size),this.addChart(e.id,e.definition);break;case`UPDATE_CHART`:this.addChart(e.id,e.definition);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`chart`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.charts[n.id]?.copyForSheetId(e.sheetIdTo);i&&this.dispatch(`CREATE_CHART`,{id:r,position:{x:n.x,y:n.y},size:{width:n.width,height:n.height},definition:i.getDefinition(),sheetId:e.sheetIdTo})}break}case`DELETE_FIGURE`:this.history.update(`charts`,e.id,void 0);break;case`DELETE_SHEET`:for(let t of this.getChartIds(e.sheetId))this.history.update(`charts`,t,void 0);break}}getContextCreationChart(e){return this.charts[e]?.getContextCreation()}getChart(e){return this.charts[e]}getChartType(e){let t=this.charts[e]?.type;if(!t)throw Error(`Chart not defined.`);return t}isChartDefined(e){return e in this.charts&&this.charts!==void 0}getChartIds(e){return Object.entries(this.charts).filter(([,t])=>t?.sheetId===e).map(([e])=>e)}getChartDefinition(e){let t=this.charts[e]?.getDefinition();if(!t)throw Error(`There is no chart with the given figureId: ${e}`);return t}import(e){for(let t of e.sheets)if(t.figures)for(let e of t.figures)e.tag===`chart`&&(this.charts[e.id]=this.createChart(e.id,e.data,t.id))}export(e){if(e.sheets)for(let t of e.sheets){let e=this.getters.getFigures(t.id),n=[];for(let t of e){let e=t;if(e&&e.tag===`chart`){let t=this.charts[e.id]?.getDefinition();t&&(e.data=t,n.push(e))}else n.push(e)}t.figures=n}}addFigure(e,t,n={x:0,y:0},r={width:536,height:335}){if(this.getters.getFigure(t,e))return;let i={id:e,x:n.x,y:n.y,width:r.width,height:r.height,tag:`chart`};this.dispatch(`CREATE_FIGURE`,{sheetId:t,figure:i})}addChart(e,t){let n=this.getters.getFigureSheetId(e);n&&this.history.update(`charts`,e,this.createChart(e,t,n))}checkChartDuplicate(e){return this.getters.getFigureSheetId(e.id)?`DuplicatedChartId`:`Success`}checkChartExists(e){return this.isChartDefined(e.id)?`Success`:`ChartDoesNotExist`}};function PL(e){return e===``?NaN:Number(e)}var FL=class extends DL{static getters=[`getConditionalFormats`,`getRulesSelection`,`getRulesByCell`,`getAdaptedCfRanges`];cfRules={};loopThroughRangesOfSheet(e,t){for(let n of this.cfRules[e]){if(n.rule.type===`DataBarRule`&&n.rule.rangeValues){let r=t(n.rule.rangeValues);switch(r.changeType){case`REMOVE`:this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`rule`,`rangeValues`,void 0);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`rule`,`rangeValues`,r.range);break}}for(let r of n.ranges){let i=t(r);switch(i.changeType){case`REMOVE`:let t=n.ranges.slice();t.splice(n.ranges.indexOf(r),1),t.length>=1?this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,t):this.removeConditionalFormatting(n.id,e);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,n.ranges.indexOf(r),i.range);break}}}}adaptRanges(e,t){if(t)this.loopThroughRangesOfSheet(t,e);else for(let t of Object.keys(this.cfRules))this.loopThroughRangesOfSheet(t,e)}allowDispatch(e){switch(e.type){case`ADD_CONDITIONAL_FORMAT`:return this.checkValidations(e,this.checkCFRule,this.checkEmptyRange);case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:return this.checkValidPriorityChange(e.cfId,e.delta,e.sheetId)}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.cfRules[e.sheetId]=[];break;case`DUPLICATE_SHEET`:this.history.update(`cfRules`,e.sheetIdTo,[]);for(let t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case`DELETE_SHEET`:let t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update(`cfRules`,t);break;case`ADD_CONDITIONAL_FORMAT`:let n={...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))};this.addConditionalFormatting(n,e.sheetId);break;case`REMOVE_CONDITIONAL_FORMAT`:this.removeConditionalFormatting(e.id,e.sheetId);break;case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:this.changeCFPriority(e.cfId,e.delta,e.sheetId);break}}import(e){for(let t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map(e=>this.mapToConditionalFormatInternal(t.id,e))}export(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e)))}exportForExcel(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e,{useBoundedReference:!0})))}getConditionalFormats(e){return this.cfRules[e]?.map(t=>this.mapToConditionalFormat(e,t))||[]}getRulesSelection(e,t){let n=new Set;return t.forEach(t=>{this.getRulesByZone(e,t).forEach(e=>{n.add(e)})}),Array.from(n)}getRulesByZone(e,t){let n=new Set;for(let r=t.top;r<=t.bottom;r++)for(let i=t.left;i<=t.right;i++)this.getRulesByCell(e,i,r).forEach(e=>{n.add(e.id)});return n}getRulesByCell(e,t,n){let r=[];for(let i of this.cfRules[e])for(let e of i.ranges)fr(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(Qn));let s=Fn(o,r);return Fn([...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 ag[t.operator]?this.checkValidations(t,this.checkOperatorArgsNumber(2,[`Between`,`NotBetween`]),this.checkOperatorArgsNumber(1,[`BeginsWith`,`ContainsText`,`EndsWith`,`GreaterThan`,`GreaterThanOrEqual`,`LessThan`,`LessThanOrEqual`,`NotContains`,`Equal`,`NotEqual`]),this.checkOperatorArgsNumber(0,[`IsEmpty`,`IsNotEmpty`]),this.checkCFValues):`InvalidConditionalFormatType`;case`ColorScaleRule`:return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case`IconSetRule`:return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)));case`DataBarRule`:return`Success`}return`InvalidConditionalFormatType`}checkOperatorArgsNumber(e,t){if(e>2)throw Error(`Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.`);return n=>{if(t.includes(n.operator)){let t=[],r=e=>e===void 0||e===``;return e>=1&&r(n.values[0])&&t.push(`FirstArgMissing`),e>=2&&r(n.values[1])&&t.push(`SecondArgMissing`),t.length?t:`Success`}return`Success`}}checkNaN(e,t){if([`number`,`percentage`,`percentile`].includes(e.type)&&(e.value===``||isNaN(e.value)))switch(t){case`min`:return`MinNaN`;case`max`:return`MaxNaN`;case`mid`:return`MidNaN`;case`upperInflectionPoint`:return`ValueUpperInflectionNaN`;case`lowerInflectionPoint`:return`ValueLowerInflectionNaN`}return`Success`}checkFormulaCompilation(e,t){if(e.type!==`formula`)return`Success`;if(kE(e.value||``).isBadExpression)switch(t){case`min`:return`MinInvalidFormula`;case`max`:return`MaxInvalidFormula`;case`mid`:return`MidInvalidFormula`;case`upperInflectionPoint`:return`ValueUpperInvalidFormula`;case`lowerInflectionPoint`:return`ValueLowerInvalidFormula`}return`Success`}checkThresholds(e){return this.batchValidations(t=>e(t.minimum,`min`),t=>e(t.maximum,`max`),t=>t.midpoint?e(t.midpoint,`mid`):`Success`)}checkInflectionPoints(e){return this.batchValidations(t=>e(t.lowerInflectionPoint,`lowerInflectionPoint`),t=>e(t.upperInflectionPoint,`upperInflectionPoint`))}checkLowerBiggerThanUpper(e){let t=e.lowerInflectionPoint.value,n=e.upperInflectionPoint.value;return[`number`,`percentage`,`percentile`].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(n)?`LowerBiggerThanUpper`:`Success`}checkMinBiggerThanMax(e){let t=e.minimum.value,n=e.maximum.value;return[`number`,`percentage`,`percentile`].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&PL(t)>=PL(n)?`MinBiggerThanMax`:`Success`}checkMidBiggerThanMax(e){let t=e.midpoint?.value,n=e.maximum.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&PL(t)>=PL(n)?`MidBiggerThanMax`:`Success`}checkMinBiggerThanMid(e){let t=e.minimum.value,n=e.midpoint?.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&PL(t)>=PL(n)?`MinBiggerThanMid`:`Success`}checkCFValues(e){for(let t of e.values)if(t.startsWith(`=`)&&kE(t||``).isBadExpression)return`ValueCellIsInvalidFormula`;return`Success`}removeConditionalFormatting(e,t){let n=this.cfRules[t].findIndex(t=>t.id===e);if(n!==-1){let e=this.cfRules[t].slice();e.splice(n,1),this.history.update(`cfRules`,t,e)}}changeCFPriority(e,t,n){let r=this.cfRules[n].findIndex(t=>t.id===e),i=this.cfRules[n][r],a=r-t,o=[...this.cfRules[n]];o.splice(r,1),o.splice(a,0,i),this.history.update(`cfRules`,n,o)}},IL=class extends DL{static getters=[`cellHasListDataValidationIcon`,`getDataValidationRule`,`getDataValidationRules`,`getValidationRuleForCell`];rules={};adaptRanges(e,t){let n=t?[t]:Object.keys(this.rules);for(let t of n)this.loopThroughRangesOfSheet(t,e)}loopThroughRangesOfSheet(e,t){let n=this.rules[e];for(let r=n.length-1;r>=0;r--){let n=this.rules[e][r];for(let i=n.ranges.length-1;i>=0;i--){let a=n.ranges[i],o=t(a);switch(o.changeType){case`REMOVE`:if(n.ranges.length===1)this.removeDataValidationRule(e,n.id);else{let t=n.ranges.slice();t.splice(i,1),this.history.update(`rules`,e,r,`ranges`,t)}break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`rules`,e,r,`ranges`,i,o.range);break}}}}allowDispatch(e){switch(e.type){case`ADD_DATA_VALIDATION_RULE`:return this.getters.tryGetSheet(e.sheetId)?this.checkValidations(e,this.chainValidations(this.checkEmptyRange,this.checkCriterionTypeIsValid,this.checkCriterionHasValidNumberOfValues,this.checkCriterionValuesAreValid)):`InvalidSheetId`;case`REMOVE_DATA_VALIDATION_RULE`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;if(!this.rules[e.sheetId].find(t=>t.id===e.id))return`UnknownDataValidationRule`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`rules`,e.sheetId,[]);break;case`DUPLICATE_SHEET`:{let t=y(this.rules[e.sheetId]).map(t=>({...t,ranges:t.ranges.map(t=>Gs(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=Fn(e.target),n=e.sheetId;for(let e of t)for(let t=e.top;t<=e.bottom;t++)for(let r=e.left;r<=e.right;r++){let e=this.getValidationRuleForCell({sheetId:n,col:r,row:t});if(e&&(e.criterion.type===`isBoolean`||e.criterion.type===`isValueInList`&&!this.getters.getCell({sheetId:n,col:r,row:t})?.content)){let e=this.rules[n],i=[this.getters.getRangeFromSheetXC(n,w(r,t))],a=this.removeRangesFromRules(n,i,e);this.history.update(`rules`,n,a)}}}}}getDataValidationRules(e){return this.rules[e]}getDataValidationRule(e,t){return this.rules[e].find(e=>e.id===t)}getValidationRuleForCell({sheetId:e,col:t,row:n}){if(this.rules[e]){for(let r of this.rules[e])for(let e of r.ranges)if(fr(t,n,e.zone))return r}}cellHasListDataValidationIcon(e){let t=this.getValidationRuleForCell(e);return t?(t.criterion.type===`isValueInList`||t.criterion.type===`isValueInRange`)&&t.criterion.displayStyle===`arrow`:!1}addDataValidationRule(e,t){let n=this.rules[e];t.criterion.type===`isBoolean`?this.setCenterStyleToBooleanCells(t):t.criterion.type===`isValueInList`&&(t.criterion.values=Array.from(new Set(t.criterion.values)));let r=this.removeRangesFromRules(e,t.ranges,n,t.id),i=r.findIndex(e=>e.id===t.id);i===-1?this.history.update(`rules`,e,[...r,t]):(r[i]=t,this.history.update(`rules`,e,r))}removeRangesFromRules(e,t,n,r){n=y(n);for(let e of n)e.id!==r&&(e.ranges=this.getters.recomputeRanges(e.ranges,t));return n.filter(e=>e.ranges.length>0)}removeDataValidationRule(e,t){let n=this.rules[e].filter(e=>e.id!==t);this.history.update(`rules`,e,n)}setCenterStyleToBooleanCells(e){for(let t of Js(e.ranges)){let e=this.getters.getCell(t),n={...e?.style,align:e?.style?.align??`center`,verticalAlign:e?.style?.verticalAlign??`middle`};this.dispatch(`UPDATE_CELL`,{...t,style:n})}}checkEmptyRange(e){return e.ranges.length?`Success`:`EmptyRange`}import(e){for(let t of e.sheets)if(this.rules[t.id]=[],t.dataValidationRules)for(let e of t.dataValidationRules)this.rules[t.id].push({...e,ranges:e.ranges.map(e=>this.getters.getRangeFromSheetXC(t.id,e))})}export(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id])t.dataValidationRules.push({...e,ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id))})}}exportForExcel(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id]){let n={...y(e),ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id,{useBoundedReference:!0}))};e.criterion.type===`isValueInRange`&&(n.criterion.values=e.criterion.values.map(e=>{let n=this.getters.getRangeFromSheetXC(t.id,e);return this.getters.getRangeString(n,t.id,{useBoundedReference:!0,useFixedReference:!0})})),t.dataValidationRules.push(n)}}}checkCriterionTypeIsValid(e){return Q.contains(e.rule.criterion.type)?`Success`:`UnknownDataValidationCriterionType`}checkCriterionHasValidNumberOfValues(e){let t=e.rule.criterion,n=Q.get(t.type).numberOfValues(t);return n!==void 0&&t.values.length!==n?`InvalidNumberOfCriterionValues`:`Success`}checkCriterionValuesAreValid(e){let t=e.rule.criterion,n=Q.get(t.type);return t.values.some(e=>e.startsWith(`=`)?n.allowedValues===`onlyLiterals`:n.allowedValues===`onlyFormulas`?!0:!n.isCriterionValueValid(e))?`InvalidDataValidationCriterionValue`:`Success`}},LL=class extends DL{static getters=[`getFigures`,`getFigure`,`getFigureSheetId`];figures={};insertionOrders=[];allowDispatch(e){switch(e.type){case`CREATE_FIGURE`:return this.checkFigureDuplicate(e.figure.id);case`UPDATE_FIGURE`:case`DELETE_FIGURE`:return this.checkFigureExists(e.sheetId,e.id);default:return`Success`}}beforeHandle(e){switch(e.type){case`DELETE_SHEET`:this.getters.getFigures(e.sheetId).forEach(t=>{this.dispatch(`DELETE_FIGURE`,{id:t.id,sheetId:e.sheetId})});break}}handle(e){switch(e.type){case`CREATE_SHEET`:this.figures[e.sheetId]={};break;case`DELETE_SHEET`:this.deleteSheet(e.sheetId);break;case`CREATE_FIGURE`:this.addFigure(e.figure,e.sheetId);break;case`UPDATE_FIGURE`:let{type:t,sheetId:n,...r}=e,i=r;this.updateFigure(n,i);break;case`DELETE_FIGURE`:this.removeFigure(e.id,e.sheetId);break;case`REMOVE_COLUMNS_ROWS`:this.onRowColDelete(e.sheetId,e.dimension)}}onRowColDelete(e,t){t===`ROW`?this.onRowDeletion(e):this.onColDeletion(e)}onRowDeletion(e){let t=this.getters.getNumberRows(e),n=0;for(let r=0;r<t;r++)n+=this.getters.getUserRowSize(e,r)||23;let r=this.getters.getFigures(e);for(let t of r){let r=Math.min(t.y,n-t.height);r!==t.y&&this.dispatch(`UPDATE_FIGURE`,{sheetId:e,id:t.id,y:r})}}onColDeletion(e){let t=this.getters.getNumberCols(e),n=0;for(let r=0;r<t;r++)n+=this.getters.getColSize(e,r);let r=this.getters.getFigures(e);for(let t of r){let r=Math.min(t.x,n-t.width);r!==t.x&&this.dispatch(`UPDATE_FIGURE`,{sheetId:e,id:t.id,x:r})}}updateFigure(e,t){if(`id`in t)for(let[n,r]of Object.entries(t))switch(n){case`x`:case`y`:r!==void 0&&this.history.update(`figures`,e,t.id,n,Math.max(r,0));break;case`width`:case`height`:r!==void 0&&this.history.update(`figures`,e,t.id,n,r);break}}addFigure(e,t){this.history.update(`figures`,t,e.id,e),this.history.update(`insertionOrders`,this.insertionOrders.length,e.id)}deleteSheet(e){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>!this.figures[e]?.[t])),this.history.update(`figures`,e,void 0)}removeFigure(e,t){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>t!==e)),this.history.update(`figures`,t,e,void 0)}checkFigureExists(e,t){return this.figures[e]?.[t]===void 0?`FigureDoesNotExist`:`Success`}checkFigureDuplicate(e){return Object.values(this.figures).find(t=>t?.[e])?`DuplicatedFigureId`:`Success`}getFigures(e){let t=[];for(let n of this.insertionOrders){let r=this.figures[e]?.[n];r&&t.push(r)}return t}getFigure(e,t){return this.figures[e]?.[t]}getFigureSheetId(e){return Object.keys(this.figures).find(t=>this.figures[t]?.[e]!==void 0)}import(e){for(let t of e.sheets)for(let e of t.figures)this.addFigure(e,t.id)}export(e){for(let t of e.sheets)for(let e of this.getFigures(t.id))t.figures.push({...e,data:void 0})}exportForExcel(e){this.export(e)}},RL=class extends DL{static getters=[`getUserRowSize`,`getColSize`];sizes={};handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`sizes`,e.sheetId,{COL:Array(this.getters.getNumberCols(e.sheetId)).fill(void 0),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(void 0)});break;case`DUPLICATE_SHEET`:this.history.update(`sizes`,e.sheetIdTo,y(this.sizes[e.sheetId]));break;case`DELETE_SHEET`:let t={...this.sizes};delete t[e.sheetId],this.history.update(`sizes`,t);break;case`REMOVE_COLUMNS_ROWS`:{let t=this.sizes[e.sheetId][e.dimension],n=zt(t,e.elements);this.history.update(`sizes`,e.sheetId,e.dimension,n);break}case`ADD_COLUMNS_ROWS`:{let t=[...this.sizes[e.sheetId][e.dimension]],n=Ot(e.position,e.base),r=t[e.base];t=Bt(t,Array(e.quantity).fill(r),n),this.history.update(`sizes`,e.sheetId,e.dimension,t);break}case`RESIZE_COLUMNS_ROWS`:if(e.dimension===`ROW`)for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);else for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);break}}getColSize(e,t){return Math.round(this.sizes[e]?.COL[t]||96)}getUserRowSize(e,t){let n=this.sizes[e]?.ROW[t];return n?Math.round(n):void 0}import(e){for(let t of e.sheets){let e={COL:Array(t.colNumber).fill(void 0),ROW:Array(t.rowNumber).fill(void 0)};for(let[n,r]of Object.entries(t.rows))r.size&&(e.ROW[n]=r.size);for(let[n,r]of Object.entries(t.cols))r.size&&(e.COL[n]=r.size);this.sizes[t.id]=e}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e of x(0,this.getters.getNumberRows(n.id)))(t||this.sizes[n.id].ROW[e])&&(n.rows[e]={...n.rows[e],size:this.getUserRowSize(n.id,e)??23});n.cols===void 0&&(n.cols={});for(let e of x(0,this.getters.getNumberCols(n.id)))(t||this.sizes[n.id].COL[e])&&(n.cols[e]={...n.cols[e],size:this.getColSize(n.id,e)})}}},zL=class extends DL{static getters=[`checkElementsIncludeAllVisibleHeaders`,`getHiddenColsGroups`,`getHiddenRowsGroups`,`isHeaderHiddenByUser`,`isRowHiddenByUser`,`isColHiddenByUser`];hiddenHeaders={};allowDispatch(e){switch(e.type){case`HIDE_COLUMNS_ROWS`:{if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=e.dimension===`COL`?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),n=e.dimension===`COL`?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=n?`TooManyHiddenElements`:Kt(e.elements)<0||Gt(e.elements)>n?`InvalidHeaderIndex`:`Success`}case`REMOVE_COLUMNS_ROWS`:return this.getters.tryGetSheet(e.sheetId)?this.checkElementsIncludeAllVisibleHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`:`InvalidSheetId`}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:let t={COL:Array(this.getters.getNumberCols(e.sheetId)).fill(!1),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(!1)};this.history.update(`hiddenHeaders`,e.sheetId,t);break;case`DUPLICATE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetIdTo,y(this.hiddenHeaders[e.sheetId]));break;case`DELETE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetId,void 0);break;case`REMOVE_COLUMNS_ROWS`:{let t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(let n of[...e.elements].sort((e,t)=>t-e))t.splice(n,1);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t);break}case`ADD_COLUMNS_ROWS`:{let t=Ot(e.position,e.base),n=Bt([...this.hiddenHeaders[e.sheetId][e.dimension]],Array(e.quantity).fill(!1),t);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,n);break}case`HIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!0);break;case`UNHIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!1);break}}checkElementsIncludeAllVisibleHeaders(e,t,n){return At(n,this.getAllVisibleHeaders(e,t))}isHeaderHiddenByUser(e,t,n){return t===`COL`?this.isColHiddenByUser(e,n):this.isRowHiddenByUser(e,n)}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]||this.getters.isRowFolded(e,t)}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]||this.getters.isColFolded(e,t)}getHiddenColsGroups(e){let t=[[]],n=this.hiddenHeaders[e].COL;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getHiddenRowsGroups(e){let t=[[]],n=this.hiddenHeaders[e].ROW;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getAllVisibleHeaders(e,t){let n=x(0,this.getters.getNumberHeaders(e,t)),r=[];return this.getters.getHeaderGroups(e,t).forEach(e=>{e.isFolded&&r.push(...x(e.start,e.end+1))}),n.filter(n=>!this.hiddenHeaders[e][t][n]&&!r.includes(n))}import(e){for(let t of e.sheets){this.hiddenHeaders[t.id]={COL:[],ROW:[]};for(let e=0;e<t.rowNumber;e++)this.hiddenHeaders[t.id].ROW[e]=!!t.rows[e]?.isHidden;for(let e=0;e<t.colNumber;e++)this.hiddenHeaders[t.id].COL[e]=!!t.cols[e]?.isHidden}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e=0;e<this.getters.getNumberRows(n.id);e++)(t||this.hiddenHeaders[n.id].ROW[e])&&(n.rows[e]===void 0&&(n.rows[e]={}),n.rows[e].isHidden||=this.hiddenHeaders[n.id].ROW[e]);n.cols===void 0&&(n.cols={});for(let e=0;e<this.getters.getNumberCols(n.id);e++)(t||this.hiddenHeaders[n.id].COL[e])&&(n.cols[e]===void 0&&(n.cols[e]={}),n.cols[e].isHidden||=this.hiddenHeaders[n.id].COL[e])}}},BL=class extends DL{static getters=[`getImage`,`getImagePath`,`getImageSize`];fileStore;images={};syncedImages=new Set;constructor(e){super(e),this.fileStore=e.external.fileStore}allowDispatch(e){switch(e.type){case`CREATE_IMAGE`:return this.getters.getFigure(e.sheetId,e.figureId)?`InvalidFigureId`:`Success`;default:return`Success`}}handle(e){switch(e.type){case`CREATE_IMAGE`:this.addImage(e.figureId,e.sheetId,e.position,e.size),this.history.update(`images`,e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`image`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.getImage(n.id);if(i){let t={width:n.width,height:n.height};this.dispatch(`CREATE_IMAGE`,{sheetId:e.sheetIdTo,figureId:r,position:{x:n.x,y:n.y},size:t,definition:y(i)})}}break}case`DELETE_FIGURE`:this.history.update(`images`,e.sheetId,e.id,void 0);break;case`DELETE_SHEET`:this.history.update(`images`,e.sheetId,void 0);break}}garbageCollectExternalResources(){let e=new Set(this.getAllImages().map(e=>e.path));for(let t of this.syncedImages)e.has(t)||this.fileStore?.delete(t)}getImage(e){for(let t of Object.values(this.images))if(t&&t[e])return t[e];throw Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addImage(e,t,n,r){let i={id:e,x:n.x,y:n.y,width:r.width,height:r.height,tag:`image`};this.dispatch(`CREATE_FIGURE`,{sheetId:t,figure:i})}import(e){for(let t of e.sheets){let e=(t.figures||[]).filter(e=>e.tag===`image`);for(let n of e)this.history.update(`images`,t.id,n.id,n.data),this.syncedImages.add(n.data.path)}}export(e){for(let t of e.sheets){let e=t.figures.filter(e=>e.tag===`image`);for(let n of e)n.data=this.images[t.id]?.[n.id]}}exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let t of e)if(t?.tag===`image`){let e=this.getImage(t.id);e&&n.push({...t,data:y(e)})}t.images=[...t.images,...n]}}getAllImages(){let e=[];for(let t in this.images)e.push(...Object.values(this.images[t]||{}).filter(S));return e}},VL=class extends DL{static getters=[`isInMerge`,`isInSameMerge`,`isMergeHidden`,`getMainCellPosition`,`expandZone`,`doesIntersectMerge`,`doesColumnsHaveCommonMerges`,`doesRowsHaveCommonMerges`,`getMerges`,`getMerge`,`getMergesInZone`,`isSingleCellOrMerge`,`getSelectionRangeString`,`isMainCellPosition`];nextId=1;merges={};mergeCellMap={};allowDispatch(e){let t=`force`in e?!!e.force:!1;switch(e.type){case`ADD_MERGE`:return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case`UPDATE_CELL`:return this.checkMergedContentUpdate(e);case`REMOVE_MERGE`:return this.checkMergeExists(e);default:return`Success`}}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DELETE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DUPLICATE_SHEET`:let t=this.merges[e.sheetId];if(!t)break;for(let n of Object.values(t).filter(S))this.addMerge(e.sheetIdTo,n.zone);break;case`ADD_MERGE`:for(let t of e.target)this.addMerge(e.sheetId,t);break;case`REMOVE_MERGE`:for(let t of e.target)this.removeMerge(e.sheetId,t);break}}adaptRanges(e,t){let n=t?[t]:Object.keys(this.merges);for(let t of n)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map(t=>this.getMergeById(e,parseInt(t,10))).filter(S)}getMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e],i=r?t in r&&r[t]?.[n]:void 0;return i?this.getMergeById(e,i):void 0}getMergesInZone(e,t){let n=this.mergeCellMap[e];if(!n)return[];let r=new Set;for(let e=t.left;e<=t.right;e++)for(let i=t.top;i<=t.bottom;i++){let t=n[e]?.[i];t&&r.add(t)}return Array.from(r).map(t=>this.getMergeById(e,t)).filter(S)}getSelectionRangeString(e,t){let n=Ws.fromRange(e,this.getters),r=this.getters.expandZone(n.sheetId,n.zone),i=n.clone({zone:{...r,bottom:n.isFullCol?void 0:r.bottom,right:n.isFullRow?void 0:r.right}}),a=this.getters.getRangeString(i,t);if(this.isSingleCellOrMerge(n.sheetId,n.zone)){let{sheetName:e,xc:t}=Hs(a);return Us(e,t.split(`:`)[0])}return a}doesIntersectMerge(e,t){for(let n of this.getMerges(e))if(dr(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&&dr(n,o)&&(o=sr(n,o))}return ur(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:ur(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 ur(t,n);let{numberOfCols:r,numberOfRows:i}=mr(t);return r===1&&i===1}isMainCellPosition(e){return C(this.getMainCellPosition(e),e)}isMergeDestructive(e,t){let{left:n,right:r,top:i,bottom:a}=t;r=b(r,0,this.getters.getNumberCols(e)-1),a=b(a,0,this.getters.getNumberRows(e)-1);for(let t=i;t<=a;t++)for(let a=n;a<=r;a++)if(a!==n||t!==i){let n=this.getters.getCell({sheetId:e,col:a,row:t});if(n&&n.content!==``)return!0}return!1}getMergeById(e,t){let n=this.merges[e]?.[t];return n===void 0?void 0:UL(t,n)}checkDestructiveMerge({sheetId:e,target:t}){return this.getters.tryGetSheet(e)&&t.some(t=>this.isMergeDestructive(e,t))?`MergeIsDestructive`:`Success`}checkOverlap({target:e}){for(let t of e)for(let n of e)if(t!==n&&dr(t,n))return`MergeOverlap`;return`Success`}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return`Success`;let{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(e);for(let e of t)if(e.left<n&&e.right>=n||e.top<r&&e.bottom>=r)return`FrozenPaneOverlap`;return`Success`}checkMergedContentUpdate(e){let{col:t,row:n,content:r}=e;if(r===void 0)return`Success`;let{col:i,row:a}=this.getMainCellPosition(e);return i===t&&a===n?`Success`:`CellIsMerged`}checkMergeExists(e){let{sheetId:t,target:n}=e;for(let e of n){let{left:n,top:r}=e,i=this.getMerge({sheetId:t,col:n,row:r});if(i===void 0||!ur(e,i))return`InvalidTarget`}return`Success`}addMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t;if(r=b(r,0,this.getters.getNumberCols(e)-1),a=b(a,0,this.getters.getNumberRows(e)-1),w(n,i)===w(r,a))return;let o=this.getters.getCell({sheetId:e,col:n,row:i}),s=this.nextId++;this.history.update(`merges`,e,s,this.getters.getRangeFromSheetXC(e,nr({left:n,top:i,right:r,bottom:a})));let c=new Set;for(let t=i;t<=a;t++)for(let a=n;a<=r;a++){(a!==n||t!==i)&&this.dispatch(`UPDATE_CELL`,{sheetId:e,col:a,row:t,style:o?o.style:null,content:``});let r=this.getMerge({sheetId:e,col:a,row:t});r&&c.add(r.id),this.history.update(`mergeCellMap`,e,a,t,s)}for(let t of c){let{top:n,bottom:r,left:i,right:a}=this.getMergeById(e,t);for(let t=n;t<=r;t++)for(let n=i;n<=a;n++){let r={sheetId:e,col:n,row:t},i=this.getMerge(r);(!i||i.id!==s)&&(this.history.update(`mergeCellMap`,e,n,t,void 0),this.dispatch(`CLEAR_CELL`,r))}this.history.update(`merges`,e,t,void 0)}}removeMerge(e,t){let{left:n,top:r,bottom:i,right:a}=t,o=this.getMerge({sheetId:e,col:n,row:r});if(!(o===void 0||!ur(t,o))){this.history.update(`merges`,e,o.id,void 0);for(let t=r;t<=i;t++)for(let r=n;r<=a;r++)this.history.update(`mergeCellMap`,e,r,t,void 0)}}applyRangeChangeOnSheet(e,t){let n=Object.entries(this.merges[e]||{});for(let[r,i]of n)if(i){let n=i.zone,a=t(i);switch(a.changeType){case`NONE`:break;case`REMOVE`:this.removeMerge(e,n);break;default:let{numberOfCols:t,numberOfRows:i}=mr(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 vr(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,$n(n))}export(e){for(let t of e.sheets){let e=this.merges[t.id];e&&t.merges.push(...HL(e))}}exportForExcel(e){this.export(e)}};function HL(e){return Object.entries(e).map(([e,t])=>t?UL(parseInt(e,10),t):void 0).filter(S).map(e=>w(e.left,e.top)+`:`+w(e.right,e.bottom))}function UL(e,t){return{...t.zone,id:e}}var WL=class{getters;providers=[];isAdaptingRanges=!1;constructor(e){this.getters=e}static getters=[`extendRange`,`getRangeString`,`getRangeFromSheetXC`,`createAdaptedRanges`,`getRangeDataFromXc`,`getRangeDataFromZone`,`getRangeFromRangeData`,`getRangeFromZone`,`getRangesUnion`,`recomputeRanges`,`isRangeValid`,`removeRangesSheetPrefix`];allowDispatch(e){return e.type===`MOVE_RANGES`?e.target.length===1?`Success`:`InvalidZones`:`Success`}beforeHandle(e){}handle(e){if(this.isAdaptingRanges)throw Error(`Plugins cannot dispatch commands during adaptRanges phase`);switch(e.type){case`REMOVE_COLUMNS_ROWS`:{let t=e.dimension===`COL`?`left`:`top`,n=e.dimension===`COL`?`right`:`bottom`,r=e.dimension===`COL`?`columns`:`rows`,i=[...e.elements];i.sort((e,t)=>t-e);let a=ct(i);this.executeOnAllRanges(i=>{if(i.sheetId!==e.sheetId)return{changeType:`NONE`};let o=i,s=`NONE`;for(let e of a){let a=Kt(e),c=Gt(e);if(i.zone[t]<=a&&a<=i.zone[n]){let e=Math.min(i.zone[n],c)-a+1;s=`RESIZE`,o=this.createAdaptedRange(o,r,s,-e)}else if(i.zone[t]>=a&&i.zone[n]<=c)s=`REMOVE`,o=i.clone({...this.getInvalidRange()});else if(i.zone[t]<=c&&i.zone[n]>=c){let e=c-i.zone[t]+1;s=`RESIZE`,o=this.createAdaptedRange(o,r,s,-e),o=this.createAdaptedRange(o,r,`MOVE`,-(i.zone[t]-a))}else a<i.zone[t]&&(s=`MOVE`,o=this.createAdaptedRange(o,r,s,-(c-a+1)))}return s===`NONE`?{changeType:`NONE`}:{changeType:s,range:o}},e.sheetId);break}case`ADD_COLUMNS_ROWS`:{let t=e.dimension===`COL`?`left`:`top`,n=e.dimension===`COL`?`right`:`bottom`,r=e.dimension===`COL`?`columns`:`rows`;this.executeOnAllRanges(i=>{if(i.sheetId!==e.sheetId)return{changeType:`NONE`};if(e.position===`after`){if(i.zone[t]<=e.base&&e.base<i.zone[n])return{changeType:`RESIZE`,range:this.createAdaptedRange(i,r,`RESIZE`,e.quantity)};if(e.base<i.zone[t])return{changeType:`MOVE`,range:this.createAdaptedRange(i,r,`MOVE`,e.quantity)}}else{if(i.zone[t]<e.base&&e.base<=i.zone[n])return{changeType:`RESIZE`,range:this.createAdaptedRange(i,r,`RESIZE`,e.quantity)};if(e.base<=i.zone[t])return{changeType:`MOVE`,range:this.createAdaptedRange(i,r,`MOVE`,e.quantity)}}return{changeType:`NONE`}},e.sheetId);break}case`DELETE_SHEET`:this.executeOnAllRanges(t=>{if(t.sheetId!==e.sheetId)return{changeType:`NONE`};let n=this.getters.getSheetName(e.sheetId);return t=t.clone({...this.getInvalidRange(),invalidSheetName:n}),{changeType:`REMOVE`,range:t}},e.sheetId);break;case`RENAME_SHEET`:this.executeOnAllRanges(t=>{if(t.sheetId===e.sheetId)return{changeType:`CHANGE`,range:t};if(nc(t.invalidSheetName,e.name)){let n=e.sheetId;return{changeType:`CHANGE`,range:t.clone({sheetId:n,invalidSheetName:void 0})}}return{changeType:`NONE`}});break;case`MOVE_RANGES`:{let t=e.target[0];this.executeOnAllRanges(n=>{if(n.sheetId!==e.sheetId||!pr(n.zone,t))return{changeType:`NONE`};let r=e.targetSheetId,i=e.col-t.left,a=e.row-t.top,o=this.createAdaptedRange(n,`both`,`MOVE`,[i,a]),s=e.sheetId===r?o.prefixSheet:!0;return{changeType:`MOVE`,range:o.clone({sheetId:r,prefixSheet:s})}});break}}}finalize(){}verifyRangeRemoved(e){return t=>{let n=e(t);return n.changeType!==`NONE`&&!er(n.range.zone)?{range:n.range,changeType:`REMOVE`}:n}}createAdaptedRange(e,t,n,r){let i=br(e.unboundedZone,t,n,r);return e.clone({zone:i})}executeOnAllRanges(e,t){this.isAdaptingRanges=!0;let n=this.verifyRangeRemoved(e);for(let e of this.providers)e(n,t);this.isAdaptingRanges=!1}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,n,r){return e.map(e=>Ws.fromRange(e,this.getters)).map(e=>{if(!er(e.zone))return e;let i=e.prefixSheet?e.sheetId:r,a={...e.unboundedZone,left:e.isFullRow&&!e.unboundedZone.hasHeader?e.unboundedZone.left:e.unboundedZone.left+(e.parts[0].colFixed?0:t),right:e.isFullRow?e.unboundedZone.right:e.unboundedZone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:e.isFullCol&&!e.unboundedZone.hasHeader?e.unboundedZone.top:e.unboundedZone.top+(e.parts[0].rowFixed?0:n),bottom:e.isFullCol?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:n)};return e.clone({sheetId:i,zone:a}).orderZone()})}removeRangesSheetPrefix(e,t){return t.map(t=>{let n=Ws.fromRange(t,this.getters);return n.prefixSheet&&n.sheetId===e?n.clone({prefixSheet:!1}):n})}extendRange(e,t,n){let r=Ws.fromRange(e,this.getters),i=t===`COL`?r.zone.right+n:r.zone.right,a=t===`ROW`?r.zone.bottom+n:r.zone.bottom,o={left:r.zone.left,top:r.zone.top,right:r.isFullRow?void 0:i,bottom:r.isFullCol?void 0:a};return new Ws({...r,zone:o},this.getters.getSheetSize).orderZone()}getRangeFromSheetXC(e,t){if(!Is.test(t)||!this.getters.tryGetSheet(e))return new Ws({sheetId:``,zone:{left:-1,top:-1,right:-1,bottom:-1},parts:[],invalidXc:t,prefixSheet:!1},this.getters.getSheetSize);let n,r=t,i=!1;t.includes(`!`)&&({xc:r,sheetName:n}=Hs(t),n&&(i=!0));let a=Qn(r),o=Ws.getRangeParts(r,a),s=n&&!this.getters.getSheetIdByName(n)?n:void 0,c=this.getters.getSheetIdByName(n)||e;return new Ws({prefixSheet:i,zone:a,sheetId:c,invalidSheetName:s,parts:o},this.getters.getSheetSize).orderZone()}getRangeString(e,t,n={useBoundedReference:!1,useFixedReference:!1}){if(!e)return A.InvalidReference;if(e.invalidXc)return e.invalidXc;if(!this.getters.tryGetSheet(e.sheetId)||e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0||e.zone.left<0||e.zone.top<0)return A.InvalidReference;let r=Ws.fromRange(e,this.getters),i=r.sheetId!==t||r.invalidSheetName||r.prefixSheet,a=``;if(i&&(a=r.invalidSheetName?ot(r.invalidSheetName):ot(this.getters.getSheetName(r.sheetId))),i&&!a)return A.InvalidReference;let o=this.getRangePartString(r,0,n);return r.parts&&r.parts.length===2&&(r.zone.top!==r.zone.bottom||r.zone.left!==r.zone.right||r.parts[0].rowFixed||r.parts[0].colFixed||r.parts[1].rowFixed||r.parts[1].colFixed)&&(o+=`:`,o+=this.getRangePartString(r,1,n)),`${i?a+`!`:``}${o}`}getRangeDataFromXc(e,t){return this.getters.getRangeFromSheetXC(e,t).rangeData}getRangeDataFromZone(e,t){return t=this.getters.getUnboundedZone(e,t),{_sheetId:e,_zone:t}}getRangeFromZone(e,t){return new Ws({sheetId:e,zone:t,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}],prefixSheet:!1},this.getters.getSheetSize)}recomputeRanges(e,t){return Fn(e.map(e=>Ws.fromRange(e,this.getters).unboundedZone),t.map(e=>Ws.fromRange(e,this.getters).unboundedZone)).map(t=>this.getRangeFromZone(e[0].sheetId,t))}getRangeFromRangeData(e){return new Ws({prefixSheet:!1,zone:e._zone,sheetId:e._sheetId,invalidSheetName:void 0,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}]},this.getters.getSheetSize)}isRangeValid(e){if(!e)return!1;let{xc:t,sheetName:n}=Hs(e);return t.match(Is)!==null&&(!n||this.getters.getSheetIdByName(n)!==void 0)}getRangesUnion(e){let t=cr(...e.map(e=>Ws.fromRange(e,this.getters).unboundedZone));return this.getRangeFromZone(e[0].sheetId,t)}getRangePartString(e,t,n={useBoundedReference:!1,useFixedReference:!1}){let r=e.parts[t]?.colFixed||n.useFixedReference?`$`:``,i=Tn(t===0?e.zone.left:e.zone.right),a=e.parts[t]?.rowFixed||n.useFixedReference?`$`:``,o=String(t===0?e.zone.top+1:e.zone.bottom+1),s=``;return s=e.isFullCol&&!n.useBoundedReference?t===0&&e.unboundedZone.hasHeader?r+i+a+o:r+i:e.isFullRow&&!n.useBoundedReference?t===0&&e.unboundedZone.hasHeader?r+i+a+o:a+o:r+i+a+o,s}getInvalidRange(){return{parts:[],prefixSheet:!1,zone:{left:-1,top:-1,right:-1,bottom:-1},sheetId:``,invalidXc:A.InvalidReference}}},GL=class extends DL{static getters=`getSheetName.tryGetSheetName.getSheet.tryGetSheet.getSheetIdByName.getSheetIds.getVisibleSheetIds.isSheetVisible.doesHeaderExist.doesHeadersExist.getCell.getCellPosition.getColsZone.getRowCells.getRowsZone.getNumberCols.getNumberRows.getNumberHeaders.getGridLinesVisibility.getNextSheetName.getSheetSize.getSheetZone.getPaneDivisions.checkZonesExistInSheet.getCommandZones.getUnboundedZone.checkElementsIncludeAllNonFrozenHeaders.getDuplicateSheetName`.split(`.`);sheetIdsMapName={};orderedSheetIds=[];sheets={};cellPosition={};allowDispatch(e){let t=this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e);if(t!==`Success`)return t;switch(e.type){case`HIDE_SHEET`:return this.getVisibleSheetIds().length===1?`NotEnoughSheets`:`Success`;case`CREATE_SHEET`:return this.checkValidations(e,this.checkSheetName,this.checkSheetPosition);case`DUPLICATE_SHEET`:return this.sheets[e.sheetIdTo]?`DuplicatedSheetId`:this.orderedSheetIds.map(this.getSheetName.bind(this)).includes(e.sheetNameTo)?`DuplicatedSheetName`:`Success`;case`MOVE_SHEET`:try{let t=this.orderedSheetIds.findIndex(t=>t===e.sheetId);return this.findIndexOfTargetSheet(t,e.delta),`Success`}catch{return`WrongSheetMove`}case`RENAME_SHEET`:return this.isRenameAllowed(e);case`COLOR_SHEET`:return!e.color||tn(e.color)?`Success`:`InvalidColor`;case`DELETE_SHEET`:return this.getVisibleSheetIds().length>1?`Success`:`NotEnoughSheets`;case`ADD_COLUMNS_ROWS`:return this.doesHeaderExist(e.sheetId,e.dimension,e.base)?e.quantity<=0?`InvalidQuantity`:`Success`:`InvalidHeaderIndex`;case`REMOVE_COLUMNS_ROWS`:{let t=Kt(e.elements),n=Gt(e.elements);return t<0||!this.doesHeaderExist(e.sheetId,e.dimension,n)?`InvalidHeaderIndex`:this.checkElementsIncludeAllNonFrozenHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`}case`FREEZE_ROWS`:return this.checkValidations(e,this.checkRowFreezeQuantity,this.checkRowFreezeOverlapMerge);case`FREEZE_COLUMNS`:return this.checkValidations(e,this.checkColFreezeQuantity,this.checkColFreezeOverlapMerge);default:return`Success`}}handle(e){switch(e.type){case`SET_GRID_LINES_VISIBILITY`:this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);break;case`CREATE_SHEET`:let t=this.createSheet(e.sheetId,e.name||this.getNextSheetName(),e.cols||26,e.rows||100,e.position);this.history.update(`sheetIdsMapName`,t.name,t.id);break;case`MOVE_SHEET`:this.moveSheet(e.sheetId,e.delta);break;case`RENAME_SHEET`:this.renameSheet(this.sheets[e.sheetId],e.name);break;case`COLOR_SHEET`:this.history.update(`sheets`,e.sheetId,`color`,e.color);break;case`HIDE_SHEET`:this.hideSheet(e.sheetId);break;case`SHOW_SHEET`:this.showSheet(e.sheetId);break;case`DUPLICATE_SHEET`:this.duplicateSheet(e.sheetId,e.sheetIdTo,e.sheetNameTo);break;case`DELETE_SHEET`:this.deleteSheet(this.sheets[e.sheetId]);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case`UPDATE_CELL_POSITION`:this.updateCellPosition(e);break;case`FREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,e.quantity,`COL`);break;case`FREEZE_ROWS`:this.setPaneDivisions(e.sheetId,e.quantity,`ROW`);break;case`UNFREEZE_ROWS`:this.setPaneDivisions(e.sheetId,0,`ROW`);break;case`UNFREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,0,`COL`);break;case`UNFREEZE_COLUMNS_ROWS`:this.setPaneDivisions(e.sheetId,0,`COL`),this.setPaneDivisions(e.sheetId,0,`ROW`)}}import(e){for(let t of e.sheets)this.sheetIdsMapName[t.name]=t.id;for(let t of e.sheets){let e=t.name||T(`Sheet`)+(Object.keys(this.sheets).length+1),{colNumber:n,rowNumber:r}=this.getImportedSheetSize(t),i={id:t.id,name:e,numberOfCols:n,rows:Zs(r),areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,panes:{xSplit:t.panes?.xSplit||0,ySplit:t.panes?.ySplit||0},color:t.color};this.orderedSheetIds.push(i.id),this.sheets[i.id]=i}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(S).map(e=>{let t=this.sheets[e],n={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},styles:{},formats:{},borders:{},conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,color:t.color};return(t.panes.xSplit||t.panes.ySplit)&&(n.panes=t.panes),n})}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){let t=this.sheets[e];if(!t)throw Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){return this.tryGetSheet(e)?.name}getSheetIdByName(e){if(e){let t=it(e);for(let e in this.sheetIdsMapName)if(nc(e,t))return this.sheetIdsMapName[e]}}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}doesHeaderExist(e,t,n){return t===`COL`?n>=0&&n<this.getNumberCols(e):n>=0&&n<this.getNumberRows(e)}doesHeadersExist(e,t,n){return n.every(n=>this.doesHeaderExist(e,t,n))}getCell({sheetId:e,col:t,row:n}){let r=this.tryGetSheet(e)?.rows[n]?.cells[t];if(r!==void 0)return this.getters.getCellById(r)}getColsZone(e,t,n){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:n}}getRowCells(e,t){return Object.values(this.getSheet(e).rows[t]?.cells).filter(S)}getRowsZone(e,t,n){return{top:t,bottom:n,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){let t=this.cellPosition[e];if(!t)throw Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return t===`COL`?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e=`Sheet`){return ec(this.orderedSheetIds.map(this.getSheetName.bind(this)),e)}getSheetSize(e){return{numberOfRows:this.getNumberRows(e),numberOfCols:this.getNumberCols(e)}}getSheetZone(e){return{top:0,left:0,bottom:this.getNumberRows(e)-1,right:this.getNumberCols(e)-1}}getUnboundedZone(e,t){if(t.bottom===void 0||t.right===void 0)return t;let n=t.left===0&&t.right===this.getNumberCols(e)-1,r=t.top===0&&t.bottom===this.getNumberRows(e)-1;return{...t,bottom:r?void 0:t.bottom,right:n&&!r?void 0:t.right}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,n){let r={...this.getPaneDivisions(e)};n===`COL`?r.xSplit=t:n===`ROW`&&(r.ySplit=t),this.history.update(`sheets`,e,`panes`,r)}checkElementsIncludeAllNonFrozenHeaders(e,t,n){let r=this.getters.getPaneDivisions(e),i=t===`ROW`?r.ySplit:r.xSplit,a=this.getters.getNumberHeaders(e,t);return i?At(n,x(i,a)):!1}getCommandZones(e){let t=[];return`zone`in e&&t.push(e.zone),`target`in e&&t.push(...e.target),`ranges`in e&&t.push(...e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone)),`col`in e&&`row`in e&&t.push({top:e.row,left:e.col,bottom:e.row,right:e.col}),t}checkZonesExistInSheet(e,t){if(!t.every(er))return`InvalidRange`;if(t.length){let n=this.getSheetZone(e);return t.every(e=>pr(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:Zs(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(T(`There is not enough visible sheets`))}checkSheetName(e){let t=this.getters.tryGetSheetName(e.sheetId);if(t!==void 0&&e.name===t)return`UnchangedSheetName`;let{orderedSheetIds:n,sheets:r}=this,i=e.name&&e.name.trim().toLowerCase();return n.find(t=>nc(r[t]?.name,i)&&t!==e.sheetId)?`DuplicatedSheetName`:Ke.test(i)?`ForbiddenCharactersInSheetName`:`Success`}checkSheetPosition(e){let{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?`WrongSheetPosition`:`Success`}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkRowFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.top<e.quantity&&e.quantity<=n.bottom)return`MergeOverlap`;return`Success`}checkColFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.left<e.quantity&&e.quantity<=n.right)return`MergeOverlap`;return`Success`}isRenameAllowed(e){return e.name&&e.name.trim().toLowerCase()?this.checkSheetName(e):`MissingSheetName`}renameSheet(e,t){let n=e.name;this.history.update(`sheets`,e.id,`name`,t.trim());let r=Object.assign({},this.sheetIdsMapName);delete r[n],r[t]=e.id,this.history.update(`sheetIdsMapName`,r)}hideSheet(e){this.history.update(`sheets`,e,`isVisible`,!1)}showSheet(e){this.history.update(`sheets`,e,`isVisible`,!0)}duplicateSheet(e,t,n){let r=y(this.getSheet(e));r.id=t,r.name=n;for(let e=0;e<=r.numberOfCols;e++)for(let t=0;t<=r.rows.length;t++)r.rows[t]&&(r.rows[t].cells[e]=void 0);let i=this.orderedSheetIds.slice(),a=i.indexOf(e);i.splice(a+1,0,r.id),this.history.update(`orderedSheetIds`,i),this.history.update(`sheets`,Object.assign({},this.sheets,{[r.id]:r}));for(let t of Object.values(this.getters.getCells(e))){let{col:e,row:n}=this.getCellPosition(t.id);this.dispatch(`UPDATE_CELL`,{sheetId:r.id,col:e,row:n,content:t.content,format:t.format,style:t.style})}let o=Object.assign({},this.sheetIdsMapName);o[r.name]=r.id,this.history.update(`sheetIdsMapName`,o)}getDuplicateSheetName(e){return tc(e,this.orderedSheetIds.map(this.getSheetName.bind(this)))}deleteSheet(e){let t=e.name,n=Object.assign({},this.sheets);delete n[e.id],this.history.update(`sheets`,n);let r=this.orderedSheetIds.slice(),i=r.indexOf(e.id);r.splice(i,1),this.history.update(`orderedSheetIds`,r);let a=Object.assign({},this.sheetIdsMapName);delete a[t],this.history.update(`sheetIdsMapName`,a)}removeColumns(e,t){t.sort((e,t)=>t-e);for(let n of t)this.moveCellOnColumnsDeletion(e,n);let n=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,n-t.length);let r=t.filter(t=>t<e.panes.xSplit).length;r&&this.setPaneDivisions(e.id,e.panes.xSplit-r,`COL`)}removeRows(e,t){t.sort((e,t)=>t-e);for(let n of ct(t)){let t=n[n.length-1],r=n[0];this.moveCellOnRowsDeletion(e,t,r),this.updateRowsStructureOnDeletion(e,t,r)}let n=t.filter(t=>t<e.panes.ySplit).length;n&&this.setPaneDivisions(e.id,e.panes.ySplit-n,`ROW`)}addColumns(e,t,n,r){let i=n===`before`?t:t+1;this.moveCellsOnAddition(e,i,r,`columns`);let a=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,a+r),i<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+r,`COL`)}addRows(e,t,n,r){let i=n===`before`?t:t+1;this.addEmptyRows(e,r),this.moveCellsOnAddition(e,i,r,`rows`),i<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+r,`ROW`)}moveCellOnColumnsDeletion(e,t){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:t,top:0,right:t,bottom:e.rows.length-1}]});for(let n=0;n<e.rows.length;n++){let r=e.rows[n];for(let i in r.cells){let a=Number(i),o=r.cells[i];o&&a>t&&this.setNewPosition(o,e.id,a-1,n)}}}moveCellsOnAddition(e,t,n,r){let i=[];for(let a=0;a<e.rows.length;a++){let o=e.rows[a];if(r!==`rows`||a>=t)for(let s in o.cells){let c=Number(s),l=o.cells[s];l&&(r===`rows`||c>=t)&&i.push({sheetId:e.id,cellId:l,col:c+(r===`columns`?n:0),row:a+(r===`rows`?n:0),type:`UPDATE_CELL_POSITION`})}}for(let e of i.reverse())this.updateCellPosition(e)}moveCellOnRowsDeletion(e,t,n){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:0,top:t,right:this.getters.getNumberCols(e.id),bottom:n}]});let r=n-t+1;for(let t=0;t<e.rows.length;t++){let i=e.rows[t];if(t>n)for(let n in i.cells){let a=Number(n),o=i.cells[n];o&&this.setNewPosition(o,e.id,a,t-r)}}}updateRowsStructureOnDeletion(e,t,n){let r=[],i=e.rows.map(e=>e.cells).reverse();for(let a in e.rows){let e=Number(a);e>=t&&e<=n||r.push({cells:i.pop()})}this.history.update(`sheets`,e.id,`rows`,r)}addEmptyRows(e,t){let n=e.rows.slice();for(let e=0;e<t;e++)n.push({cells:{}});this.history.update(`sheets`,e.id,`rows`,n)}getImportedSheetSize(e){let t=Object.keys(e.cells).map(Pn),n=e.rowNumber,r=e.colNumber;for(let{col:e,row:i}of t)n=Math.max(n,i+1),r=Math.max(r,e+1);return{rowNumber:n,colNumber:r}}checkSheetExists(e){return e.type!==`CREATE_SHEET`&&`sheetId`in e&&this.sheets[e.sheetId]===void 0?`InvalidSheetId`:e.type===`CREATE_SHEET`&&this.sheets[e.sheetId]!==void 0?`DuplicatedSheetId`:`Success`}checkZonesAreInSheet(e){return`sheetId`in e?`ranges`in e&&e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkZonesExistInSheet(e.sheetId,this.getCommandZones(e)):`Success`}},KL=class extends DL{static getters=[`getCoreTable`,`getCoreTables`,`getCoreTableMatchingTopLeft`];tables={};insertionOrders={};adaptRanges(e,t){let n=t?[t]:this.getters.getSheetIds();for(let t of n)for(let n of this.getCoreTables(t))this.applyRangeChangeOnTable(t,n,e)}allowDispatch(e){switch(e.type){case`CREATE_TABLE`:if(e.ranges.some(t=>!this.getters.tryGetSheet(t._sheetId)||t._sheetId!==e.sheetId))return`InvalidSheetId`;let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone);return Or(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(dr(n,t))return`MergeInTable`}break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`tables`,e.sheetId,{}),this.history.update(`insertionOrders`,e.sheetId,[]);break;case`DELETE_SHEET`:{let t={...this.tables};delete t[e.sheetId],this.history.update(`tables`,t),this.history.update(`insertionOrders`,e.sheetId,void 0);break}case`DUPLICATE_SHEET`:{let t={};for(let n of this.getCoreTables(e.sheetId))t[n.id]=n.type===`dynamic`?this.copyDynamicTableForSheet(e.sheetIdTo,n):this.copyStaticTableForSheet(e.sheetIdTo,n);this.history.update(`tables`,e.sheetIdTo,t),this.history.update(`insertionOrders`,e.sheetIdTo,[...this.insertionOrders[e.sheetId]??[]]);break}case`CREATE_TABLE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e)),n=this.getters.getRangesUnion(t),r=this.getters.getMergesInZone(e.sheetId,n.zone);r.length&&this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:r});let i=this.uuidGenerator.smallUuid(),a=e.config||km,o=e.tableType===`dynamic`?this.createDynamicTable(i,n,a):this.createStaticTable(i,e.tableType,n,a);this.history.update(`tables`,e.sheetId,o.id,o),this.history.update(`insertionOrders`,e.sheetId,[...this.insertionOrders[e.sheetId]??[],o.id]);break}case`REMOVE_TABLE`:{let t={};for(let n of this.getCoreTables(e.sheetId))e.target.every(e=>!lr(n.range.zone,e))&&(t[n.id]=n);this.history.update(`tables`,e.sheetId,t),this.history.update(`insertionOrders`,e.sheetId,this.insertionOrders[e.sheetId]?.filter(e=>e in t));break}case`UPDATE_TABLE`:this.updateTable(e);break;case`UPDATE_CELL`:{let t=e.sheetId;for(let n of this.getCoreTables(t)){if(n.type===`dynamic`)continue;let r=this.canUpdateCellCmdExtendTable(e,n);r===`down`?this.extendTableDown(t,n):r===`right`&&this.extendTableRight(t,n)}break}case`DELETE_CONTENT`:{let t={...this.tables[e.sheetId]};for(let n in t){let r=t[n];r&&e.target.some(e=>pr(r.range.zone,e))&&this.dispatch(`REMOVE_TABLE`,{sheetId:e.sheetId,target:[r.range.zone]})}break}}}getCoreTables(e){let t=[];for(let n of this.insertionOrders[e]||[]){let r=this.tables[e][n];r&&t.push(r)}return t}getCoreTable({sheetId:e,col:t,row:n}){return this.getCoreTables(e).find(e=>fr(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter(e=>t.some(t=>dr(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 x(a.left,a.right+1)){let t={...a,left:e,right:e},o=this.uuidGenerator.smallUuid();i.push(this.createFilterFromZone(o,n.sheetId,t,r))}}return{id:e,range:n,filters:i,config:r,type:t}}createDynamicTable(e,t,n){let r=wr(t.zone);return{id:e,range:this.getters.getRangeFromZone(t.sheetId,r),config:n,type:`dynamic`}}updateTable(e){let t=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return;let n=e.newTableRange?this.getters.getRangeFromRangeData(e.newTableRange):void 0;if(n){let t=this.getters.getMergesInZone(e.sheetId,n.zone);this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:t})}let r=n||t.range,i=this.updateTableConfig(e.config,t.config),a=e.tableType??t.type;if(a===`dynamic`&&t.type!==`dynamic`||a!==`dynamic`&&t.type===`dynamic`){let n=a===`dynamic`?this.createDynamicTable(t.id,r,i):this.createStaticTable(t.id,a,r,i);this.history.update(`tables`,e.sheetId,t.id,n)}else{let n=t.type===`dynamic`?this.updateDynamicTable(t,r,i):this.updateStaticTable(t,r,i,a);this.history.update(`tables`,e.sheetId,t.id,n)}}updateStaticTable(e,t,n,r=e.type){if(r===`dynamic`)throw Error(`Cannot use updateStaticTable to update a dynamic table`);let i=t||e.range,a=i.zone,o=this.updateTableConfig(n,e.config),s=o||e.config,c=[];if(t||o&&`numberOfHeaders`in o)for(let t of x(a.left,a.right+1)){let n=a.top===e.range.zone.top?e.filters.find(e=>e.col===t):void 0,r={...a,left:t,right:t},o=n?.id||this.uuidGenerator.smallUuid();c.push(this.createFilterFromZone(o,i.sheetId,r,s))}return{...e,range:i,config:s,filters:c.length?c:e.filters,type:r}}updateDynamicTable(e,t,n){let r=t?this.getters.getRangeFromZone(t.sheetId,wr(t.zone)):e.range,i=n||e.config;return{...e,range:r,config:i}}updateTableConfig(e,t){if(!e)return t;let n={...t,...e};return e.numberOfHeaders===0?n.hasFilters=!1:e.hasFilters===!0&&(n.numberOfHeaders||=1),n}createFilterFromZone(e,t,n,r){return JF(e,this.getters.getRangeFromZone(t,n),r,this.getters.getRangeFromZone)}copyStaticTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone),r=t.filters.map(n=>{let r=this.getters.getRangeFromZone(e,n.rangeWithHeaders.zone);return JF(n.id,r,t.config,this.getters.getRangeFromZone)});return{id:t.id,range:n,filters:r,config:y(t.config),type:t.type}}copyDynamicTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone);return{id:t.id,range:n,config:y(t.config),type:`dynamic`}}applyRangeChangeOnTable(e,t,n){let r=n(t.range),i;switch(r.changeType){case`REMOVE`:this.history.update(`tables`,e,t.id,void 0);return;case`NONE`:return;default:i=r.range}if(t.type===`dynamic`){let n=this.updateDynamicTable(t,i);this.history.update(`tables`,e,t.id,n);return}let a=[];for(let e of t.filters){let r=n(e.rangeWithHeaders);switch(r.changeType){case`REMOVE`:continue;case`NONE`:a.push(e);break;default:let n=r.range,i=JF(e.id,n,t.config,this.getters.getRangeFromZone);a.push(i)}}let o=i.zone;if(a.length<mr(o).numberOfCols){for(let n=o.left;n<=o.right;n++)if(!a.find(e=>e.col===n)){let r=this.uuidGenerator.smallUuid(),i={...o,left:n,right:n};a.push(this.createFilterFromZone(r,e,i,t.config))}a.sort((e,t)=>e.col-t.col)}let s=this.createStaticTable(t.id,t.type,i,t.config,a);this.history.update(`tables`,e,t.id,s)}import(e){for(let t of e.sheets){let e=[];for(let n of t.tables||[]){let r=this.uuidGenerator.uuidv4(),i=n.config||km,a=this.getters.getRangeFromSheetXC(t.id,n.range),o=n.type||`static`,s=o===`dynamic`?this.createDynamicTable(r,a,i):this.createStaticTable(r,o,a,i);this.history.update(`tables`,t.id,s.id,s),e.push(s.id)}this.history.update(`insertionOrders`,t.id,e)}}export(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n={range:nr(e.range.zone),type:e.type};C(e.config,km)||(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=nr(e.range.zone);t.tables.push({range:n,filters:[],config:e.config})}}},qL=class extends DL{static getters=[`getHeaderGroups`,`getGroupsLayers`,`getVisibleGroupLayers`,`getHeaderGroup`,`getHeaderGroupsInZone`,`isGroupFolded`,`isRowFolded`,`isColFolded`];groups={};allowDispatch(e){switch(e.type){case`GROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;if(this.findGroupWithStartEnd(e.sheetId,e.dimension,t,n))return`HeaderGroupAlreadyExists`;break}case`UNGROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;break}case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUP`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);if(!t)return`UnknownHeaderGroup`;if(x(0,this.getters.getNumberHeaders(e.sheetId,e.dimension)).every(n=>n>=t.start&&n<=t.end||this.getters.isHeaderHiddenByUser(e.sheetId,e.dimension,n)))return`NotEnoughElements`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`groups`,e.sheetId,{ROW:[],COL:[]});break;case`GROUP_HEADERS`:this.groupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`UNGROUP_HEADERS`:this.unGroupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`DUPLICATE_SHEET`:{let t=y(this.groups[e.sheetId]);this.history.update(`groups`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.groups};delete t[e.sheetId],this.history.update(`groups`,t);break}case`ADD_COLUMNS_ROWS`:let t=Ot(e.position,e.base);this.moveGroupsOnHeaderInsertion(e.sheetId,e.dimension,t,e.quantity);break;case`REMOVE_COLUMNS_ROWS`:this.moveGroupsOnHeaderDeletion(e.sheetId,e.dimension,e.elements);break;case`UNFOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.unfoldHeaderGroup(e.sheetId,e.dimension,t);break}case`FOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.foldHeaderGroup(e.sheetId,e.dimension,t);break}case`UNFOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.unfoldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.foldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:{let t=e.type===`UNFOLD_HEADER_GROUPS_IN_ZONE`?`unfold`:`fold`,n=this.getGroupsLayers(e.sheetId,e.dimension);t===`fold`&&n.reverse();let r=n.flat(),i=e.dimension===`ROW`?e.zone.top:e.zone.left,a=e.dimension===`ROW`?e.zone.bottom:e.zone.right,o=new Set;for(let e=i;e<=a;e++){let n=r.filter(t=>t.start-1<=e&&e<=t.end);for(let e of n)if(!(t===`fold`&&e.isFolded||t===`unfold`&&!e.isFolded)){o.add(e);break}}for(let n of o)t===`unfold`?this.unfoldHeaderGroup(e.sheetId,e.dimension,n):this.foldHeaderGroup(e.sheetId,e.dimension,n);break}}}getHeaderGroups(e,t){return this.groups[e][t]}getHeaderGroup(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}getHeaderGroupsInZone(e,t,n){return this.getHeaderGroups(e,t).filter(e=>{let r=t===`ROW`?n.top:n.left,i=t===`ROW`?n.bottom:n.right;return this.doGroupOverlap(e,r,i)})}getGroupsLayers(e,t){let n=this.getHeaderGroups(e,t);return this.bricksFallingAlgorithm(n,0,0)}getVisibleGroupLayers(e,t){let n=this.getGroupsLayers(e,t);for(let r of n)for(let n=r.length-1;n>=0;n--){let i=r[n];i.start!==0&&x(i.start-1,i.end+1).every(n=>this.getters.isHeaderHiddenByUser(e,t,n))&&r.splice(n,1)}return n.filter(e=>e.length>0)}isGroupFolded(e,t,n,r){return this.getHeaderGroup(e,t,n,r)?.isFolded||!1}isRowFolded(e,t){return this.getters.getHeaderGroups(e,`ROW`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}isColFolded(e,t){return this.getters.getHeaderGroups(e,`COL`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}getGroupId(e){return`${e.start}-${e.end}}`}bricksFallingAlgorithm(e,t,n,r=0){let i={};for(let t of e)i[this.getGroupId(t)]=t.isFolded;let a={};for(let t of e)for(let e=t.start;e<=t.end;e++)a[e]=a[e]?a[e]+1:1;for(let e=t;e<=n;e++)a[e]=a[e]?a[e]+r:r;let o=Math.max(...Object.values(a),0),s=Array.from({length:o},()=>[]),c=Math.max(n,...e.map(e=>e.end)),l=Math.min(t,...e.map(e=>e.start));for(let e=l;e<=c;e++){let t=a[e]||0;for(let n=0;n<t;n++){let t=s[n].at(-1);if(t&&Lt([t.end,e]))t.end++;else{let t={start:e,end:e};s[n].push(t)}}}for(let e of s)for(let t of e)t.isFolded=i[this.getGroupId(t)];return s}groupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}unGroupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,-1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}moveGroupsOnHeaderInsertion(e,t,n,r){let i=this.groups[e][t];for(let a=0;a<i.length;a++){let o=i[a],[s,c]=Qs(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=$s(n,x(e.start,e.end+1));t.length!==0&&i.push({...e,start:Math.min(...t),end:Math.max(...t)})}this.history.update(`groups`,e,t,this.bricksFallingAlgorithm(i,0,0).flat())}doGroupOverlap(e,t,n){return e.start<=n&&e.end>=t}removeDuplicateGroups(e){let t={};for(let n of e)t[this.getGroupId(n)]=n;return Object.values(t)}findGroupWithStartEnd(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}foldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!0);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end<=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!0)}}unfoldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!1);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end>=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!1)}}getGroupIndex(e,t,n,r){let i=this.groups[e][t].findIndex(e=>e.start===n&&e.end===r);return i===-1?void 0:i}import(e){for(let t of e.sheets)if(this.groups[t.id]={ROW:[],COL:[]},t.headerGroups)for(let e of[`ROW`,`COL`])for(let n of t.headerGroups[e]||[])this.groups[t.id][e].push({...n})}export(e){for(let t of e.sheets)t.headerGroups=this.groups[t.id]}exportForExcel(e){for(let t of e.sheets)for(let e of[`ROW`,`COL`]){let n=this.getGroupsLayers(t.id,e);for(let r=0;r<n.length;r++){let i=n[r];for(let n of i){for(let i=n.start;i<=n.end;i++){let a=Af(t,e,i);a.outlineLevel=r+1,n.isFolded&&(a.isHidden=!0)}if(n.isFolded){let r=Af(t,e,n.end+1);r.collapsed=!0}}}}}},JL=class extends DL{static getters=[`getPivotCoreDefinition`,`getPivotDisplayName`,`getPivotId`,`getPivotFormulaId`,`getPivotIds`,`getMeasureCompiledFormula`,`getPivotName`,`isExistingPivot`,`getMeasureFullDependencies`];nextFormulaId=1;pivots={};formulaIds={};compiledMeasureFormulas={};allowDispatch(e){switch(e.type){case`ADD_PIVOT`:return this.checkDuplicatedMeasureIds(e.pivot);case`UPDATE_PIVOT`:return e.pivotId in this.pivots?C(e.pivot,this.pivots[e.pivotId]?.definition)?`NoChanges`:e.pivot.name===``?`EmptyName`:this.checkDuplicatedMeasureIds(e.pivot):`PivotIdNotFound`;case`RENAME_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;if(e.name===``)return`EmptyName`;break;case`REMOVE_PIVOT`:case`DUPLICATE_PIVOT`:case`INSERT_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;break;case`DUPLICATE_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`}return`Success`}handle(e){switch(e.type){case`ADD_PIVOT`:{let{pivotId:t,pivot:n}=e;this.addPivot(t,n);break}case`INSERT_PIVOT`:{let{sheetId:t,col:n,row:r,pivotId:i,table:a}=e,o={sheetId:t,col:n,row:r},{cols:s,rows:c,measures:l,fieldsType:u}=a,d=new hF(s,c,l,u||{}),f=this.getPivotFormulaId(i);this.insertPivot(o,f,d);break}case`RENAME_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,`name`,e.name);break;case`REMOVE_PIVOT`:{let t={...this.pivots};delete t[e.pivotId];let n=this.getPivotFormulaId(e.pivotId);this.history.update(`formulaIds`,n,void 0),this.history.update(`pivots`,t);break}case`DUPLICATE_PIVOT`:{let{pivotId:t,newPivotId:n}=e,r=y(this.getPivotCore(t).definition);r.name=e.duplicatedPivotName??r.name+` (copy)`,this.addPivot(n,r);break}case`UPDATE_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,y(e.pivot)),this.compileCalculatedMeasures(e.pivotId,e.pivot.measures);break}}adaptRanges(e){for(let t in this.pivots){let n=y(this.pivots[t]?.definition);if(!n)continue;let r=jF.get(n.type)?.adaptRanges?.(this.getters,n,e);r&&!C(n,r)&&this.history.update(`pivots`,t,`definition`,r)}for(let t in this.compiledMeasureFormulas)for(let n in this.compiledMeasureFormulas[t]){let r=this.pivots[t]?.definition.measures.find(e=>e.id===n);if(!r||!r.computedBy)continue;let i=r.computedBy.sheetId,a=this.compiledMeasureFormulas[t][n].formula,o=[];for(let t of a.dependencies){let n=e(t);n.changeType===`NONE`?o.push(t):o.push(n.range)}let s=this.getters.getFormulaString(i,a.tokens,o);s!==r.computedBy.formula&&this.replaceMeasureFormula(t,r,s)}}getPivotDisplayName(e){return`(#${this.getPivotFormulaId(e)}) ${this.getPivotName(e)}`}getPivotName(e){return this.getPivotCore(e).definition.name}getPivotCoreDefinition(e){return this.getPivotCore(e).definition}getPivotId(e){return this.formulaIds[e]}getPivotFormulaId(e){return this.getPivotCore(e).formulaId}getPivotIds(){return Object.keys(this.pivots)}isExistingPivot(e){return e in this.pivots}getMeasureCompiledFormula(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].formula}getMeasureFullDependencies(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].dependencies}addPivot(e,t,n=this.nextFormulaId.toString()){this.history.update(`pivots`,e,{definition:y(t),formulaId:n}),this.compileCalculatedMeasures(e,t.measures),this.history.update(`formulaIds`,n,e),this.history.update(`nextFormulaId`,this.nextFormulaId+1)}compileCalculatedMeasures(e,t){for(let n of t)if(n.computedBy){let t=this.compileMeasureFormula(n.computedBy.sheetId,n.computedBy.formula);this.history.update(`compiledMeasureFormulas`,e,n.id,`formula`,t)}for(let n of t)if(n.computedBy){let t=this.computeMeasureFullDependencies(e,n);this.history.update(`compiledMeasureFormulas`,e,n.id,`dependencies`,t)}}computeMeasureFullDependencies(e,t,n=new Set){let r=[],i=this.getPivotCoreDefinition(e),a=this.getMeasureCompiledFormula(e,t);n.add(t.id);for(let o of a.tokens){if(o.type!==`SYMBOL`)continue;let a=i.measures.find(e=>ot(e.id)===o.value&&t.id!==e.id);!a||n.has(a.id)||!a.computedBy||r.push(...this.computeMeasureFullDependencies(e,a,n))}return r.push(...a.dependencies.filter(e=>!e.invalidXc)),r}insertPivot(e,t,n){this.resizeSheet(e.sheetId,e,n);let r=n.getPivotCells();for(let n=0;n<r.length;n++)for(let i=0;i<r[n].length;i++){let a=r[n][i];this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col+n,row:e.row+i,content:Iu(t,a)})}}resizeSheet(e,{col:t,row:n},r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,quantity:s-l,position:`after`})}getPivotCore(e){let t=this.pivots[e];if(!t)throw Error(`Pivot with id ${e} not found`);return t}compileMeasureFormula(e,t){let n=kE(t),r=n.dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t));return{...n,dependencies:r}}replaceMeasureFormula(e,t,n){let r=this.pivots[e];if(!r)return;let i=r.definition.measures.indexOf(t);this.history.update(`pivots`,e,`definition`,`measures`,i,`computedBy`,{formula:n,sheetId:t.computedBy.sheetId}),this.compileCalculatedMeasures(e,r.definition.measures)}checkDuplicatedMeasureIds(e){let t=new Set(e.measures.map(e=>e.id));return e.measures.length===t.size?`Success`:`InvalidDefinition`}import(e){if(e.pivots)for(let[t,n]of Object.entries(e.pivots))this.addPivot(t,n,n.formulaId);this.history.update(`nextFormulaId`,e.pivotNextId||ku(this.pivots)+1)}export(e){e.pivots={};for(let t in this.pivots)e.pivots[t]={...this.getPivotCoreDefinition(t),formulaId:this.getPivotFormulaId(t)};e.pivotNextId=this.nextFormulaId}},YL=class extends DL{static getters=[`getLocale`];locale=O;allowDispatch(e){switch(e.type){case`UPDATE_LOCALE`:return tl(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===vl(e)&&(n=vl(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??O}export(e){e.settings={locale:this.locale}}},XL=class extends DL{allowDispatch(e){switch(e.type){case`ADD_PIVOT`:case`UPDATE_PIVOT`:let t=e.pivot;return this.checkDataSetValidity(t)}return`Success`}checkDataSetValidity(e){if(e.type===`SPREADSHEET`&&e.dataSet){let{zone:t,sheetId:n}=e.dataSet;return!n||!this.getters.tryGetSheet(n)||!t||!er(t)?`InvalidDataSet`:this.getters.checkZonesExistInSheet(n,[t])}return`Success`}},ZL=class extends DL{static getters=[`getNewCustomTableStyleName`,`getTableStyle`,`getTableStyles`,`isTableStyleEditable`];styles={};allowDispatch(e){switch(e.type){case`CREATE_TABLE`:case`UPDATE_TABLE`:if(e.config?.styleId&&!this.styles[e.config.styleId])return`InvalidTableConfig`;break;case`CREATE_TABLE_STYLE`:if(!Wm[e.templateName])return`InvalidTableStyle`;try{en(e.primaryColor)}catch{return`InvalidTableStyle`}break}return`Success`}handle(e){switch(e.type){case`CREATE_TABLE_STYLE`:let t=Gm(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:km.styleId}});break}}getTableStyle(e){if(!this.styles[e])throw Error(`Table style ${e} does not exist`);return this.styles[e]}getTableStyles(){return this.styles}getNewCustomTableStyleName(){let e=T(`Custom Table Style`),t=new Set(Object.values(this.styles).map(e=>e.displayName));if(!t.has(e))return e;let n=2;for(;t.has(`${e} ${n}`);)n++;return`${e} ${n}`}isTableStyleEditable(e){return!Um[e]}import(e){for(let e in Um)this.styles[e]=Um[e];for(let t in e.customTableStyles){let n=e.customTableStyles[t];this.styles[t]=Gm(n.displayName,n.templateName,n.primaryColor)}}export(e){let t={};for(let e in this.styles)Um[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}},$=class extends EL{static layers=[];getters;ui;selection;constructor({getters:e,stateObserver:t,dispatch:n,canDispatch:r,uiActions:i,selection:a}){super(t,n,r),this.getters=e,this.ui=i,this.selection=a}drawLayer(e,t){}};let QL=new h;QL.add(`pivots`,e=>{for(let t of e.getPivotIds())e.getPivot(t).markAsDirtyForEvaluation?.()});let $L=zT.mapping;function eR(e,t,n){return new tR(e,t,n).getParameters()}var tR=class{getters;computeCell;evalContext;rangeCache={};constructor(e,t,n){this.getters=t,this.computeCell=n,this.evalContext=Object.assign(Object.create($L),e,{getters:this.getters,locale:this.getters.getLocale()})}getParameters(){return{referenceDenormalizer:this.refFn.bind(this),ensureRange:this.range.bind(this),evalContext:this.evalContext}}refFn(e,t){let n=this.getRangeError(e);if(n)return n;if(t)return{value:Us(this.getters.getSheetName(e.sheetId),nr(e.zone))};let r={sheetId:e.sheetId,col:e.zone.left,row:e.zone.top};return this.computeCell(r)}range(e){let t=this.getRangeError(e);if(t)return[[t]];let n=e.sheetId,r=e.zone,i=lr(r,this.getters.getSheetZone(n));if(!i)return[[]];let{top:a,left:o,bottom:s,right:c}=r,l=`${n}-${a}-${o}-${s}-${c}`;if(l in this.rangeCache)return this.rangeCache[l];let u=i.bottom-i.top+1,d=i.right-i.left+1,f=Array(d);for(let e=i.left;e<=i.right;e++){let t=e-i.left;f[t]=Array(u);for(let r=i.top;r<=i.bottom;r++){let a=r-i.top;f[t][a]=this.computeCell({sheetId:n,col:e,row:r})}}return this.rangeCache[l]=f,f}getRangeError(e){if(!er(e.zone))return new aa;if(e.invalidSheetName)return new j(T(`Invalid sheet name: %s`,e.invalidSheetName))}},nR=d(c(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n||=self).RBush=r()})(e,function(){"use strict";function e(e,r,i,a,o){(function e(n,r,i,a,o){for(;a>i;){if(a-i>600){var s=a-i+1,c=r-i+1,l=Math.log(s),u=.5*Math.exp(2*l/3),d=.5*Math.sqrt(l*u*(s-u)/s)*(c-s/2<0?-1:1);e(n,r,Math.max(i,Math.floor(r-c*u/s+d)),Math.min(a,Math.floor(r+(s-c)*u/s+d)),o)}var f=n[r],p=i,m=a;for(t(n,i,r),o(n[a],f)>0&&t(n,i,a);p<m;){for(t(n,p,m),p++,m--;o(n[p],f)<0;)p++;for(;o(n[m],f)>0;)m--}o(n[i],f)===0?t(n,i,m):t(n,++m,a),m<=r&&(i=m+1),r<=m&&(a=m-1)}})(e,r,i||0,a||e.length-1,o||n)}function t(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function n(e,t){return e<t?-1:+(e>t)}var r=function(e){e===void 0&&(e=9),this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()};function i(e,t,n){if(!n)return t.indexOf(e);for(var r=0;r<t.length;r++)if(n(e,t[r]))return r;return-1}function a(e,t){o(e,0,e.children.length,t,e)}function o(e,t,n,r,i){i||=m(null),i.minX=1/0,i.minY=1/0,i.maxX=-1/0,i.maxY=-1/0;for(var a=t;a<n;a++){var o=e.children[a];s(i,e.leaf?r(o):o)}return i}function s(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function c(e,t){return e.minX-t.minX}function l(e,t){return e.minY-t.minY}function u(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function d(e){return e.maxX-e.minX+(e.maxY-e.minY)}function f(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function p(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function m(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function h(t,n,r,i,a){for(var o=[n,r];o.length;)if(!((r=o.pop())-(n=o.pop())<=i)){var s=n+Math.ceil((r-n)/i/2)*i;e(t,s,n,r,a),o.push(n,s,s,r)}}return r.prototype.all=function(){return this._all(this.data,[])},r.prototype.search=function(e){var t=this.data,n=[];if(!p(e,t))return n;for(var r=this.toBBox,i=[];t;){for(var a=0;a<t.children.length;a++){var o=t.children[a],s=t.leaf?r(o):o;p(e,s)&&(t.leaf?n.push(o):f(e,s)?this._all(o,n):i.push(o))}t=i.pop()}return n},r.prototype.collides=function(e){var t=this.data;if(!p(e,t))return!1;for(var n=[];t;){for(var r=0;r<t.children.length;r++){var i=t.children[r],a=t.leaf?this.toBBox(i):i;if(p(e,a)){if(t.leaf||f(e,a))return!0;n.push(i)}}t=n.pop()}return!1},r.prototype.load=function(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(var t=0;t<e.length;t++)this.insert(e[t]);return this}var n=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===n.height)this._splitRoot(this.data,n);else{if(this.data.height<n.height){var r=this.data;this.data=n,n=r}this._insert(n,this.data.height-n.height-1,!0)}else this.data=n;return this},r.prototype.insert=function(e){return e&&this._insert(e,this.data.height-1),this},r.prototype.clear=function(){return this.data=m([]),this},r.prototype.remove=function(e,t){if(!e)return this;for(var n,r,a,o=this.data,s=this.toBBox(e),c=[],l=[];o||c.length;){if(o||(o=c.pop(),r=c[c.length-1],n=l.pop(),a=!0),o.leaf){var u=i(e,o.children,t);if(u!==-1)return o.children.splice(u,1),c.push(o),this._condense(c),this}a||o.leaf||!f(o,s)?r?(n++,o=r.children[n],a=!1):o=null:(c.push(o),l.push(n),n=0,r=o,o=o.children[0])}return this},r.prototype.toBBox=function(e){return e},r.prototype.compareMinX=function(e,t){return e.minX-t.minX},r.prototype.compareMinY=function(e,t){return e.minY-t.minY},r.prototype.toJSON=function(){return this.data},r.prototype.fromJSON=function(e){return this.data=e,this},r.prototype._all=function(e,t){for(var n=[];e;)e.leaf?t.push.apply(t,e.children):n.push.apply(n,e.children),e=n.pop();return t},r.prototype._build=function(e,t,n,r){var i,o=n-t+1,s=this._maxEntries;if(o<=s)return a(i=m(e.slice(t,n+1)),this.toBBox),i;r||(r=Math.ceil(Math.log(o)/Math.log(s)),s=Math.ceil(o/s**(r-1))),(i=m([])).leaf=!1,i.height=r;var c=Math.ceil(o/s),l=c*Math.ceil(Math.sqrt(s));h(e,t,n,l,this.compareMinX);for(var u=t;u<=n;u+=l){var d=Math.min(u+l-1,n);h(e,u,d,c,this.compareMinY);for(var f=u;f<=d;f+=c){var p=Math.min(f+c-1,d);i.children.push(this._build(e,f,p,r-1))}}return a(i,this.toBBox),i},r.prototype._chooseSubtree=function(e,t,n,r){for(;r.push(t),!t.leaf&&r.length-1!==n;){for(var i=1/0,a=1/0,o=void 0,s=0;s<t.children.length;s++){var c=t.children[s],l=u(c),d=(f=e,p=c,(Math.max(p.maxX,f.maxX)-Math.min(p.minX,f.minX))*(Math.max(p.maxY,f.maxY)-Math.min(p.minY,f.minY))-l);d<a?(a=d,i=l<i?l:i,o=c):d===a&&l<i&&(i=l,o=c)}t=o||t.children[0]}var f,p;return t},r.prototype._insert=function(e,t,n){var r=n?e:this.toBBox(e),i=[],a=this._chooseSubtree(r,this.data,t,i);for(a.children.push(e),s(a,r);t>=0&&i[t].children.length>this._maxEntries;)this._split(i,t),t--;this._adjustParentBBoxes(r,i,t)},r.prototype._split=function(e,t){var n=e[t],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);var o=this._chooseSplitIndex(n,i,r),s=m(n.children.splice(o,n.children.length-o));s.height=n.height,s.leaf=n.leaf,a(n,this.toBBox),a(s,this.toBBox),t?e[t-1].children.push(s):this._splitRoot(n,s)},r.prototype._splitRoot=function(e,t){this.data=m([e,t]),this.data.height=e.height+1,this.data.leaf=!1,a(this.data,this.toBBox)},r.prototype._chooseSplitIndex=function(e,t,n){for(var r,i,a,s,c,l,d,f=1/0,p=1/0,m=t;m<=n-t;m++){var h=o(e,0,m,this.toBBox),g=o(e,m,n,this.toBBox),_=(i=h,a=g,s=void 0,c=void 0,l=void 0,d=void 0,s=Math.max(i.minX,a.minX),c=Math.max(i.minY,a.minY),l=Math.min(i.maxX,a.maxX),d=Math.min(i.maxY,a.maxY),Math.max(0,l-s)*Math.max(0,d-c)),v=u(h)+u(g);_<f?(f=_,r=m,p=v<p?v:p):_===f&&v<p&&(p=v,r=m)}return r||n-t},r.prototype._chooseSplitAxis=function(e,t,n){var r=e.leaf?this.compareMinX:c,i=e.leaf?this.compareMinY:l;this._allDistMargin(e,t,n,r)<this._allDistMargin(e,t,n,i)&&e.children.sort(r)},r.prototype._allDistMargin=function(e,t,n,r){e.children.sort(r);for(var i=this.toBBox,a=o(e,0,t,i),c=o(e,n-t,n,i),l=d(a)+d(c),u=t;u<n-t;u++){var f=e.children[u];s(a,e.leaf?i(f):f),l+=d(a)}for(var p=n-t-1;p>=t;p--){var m=e.children[p];s(c,e.leaf?i(m):m),l+=d(c)}return l},r.prototype._adjustParentBBoxes=function(e,t,n){for(var r=n;r>=0;r--)s(t[r],e)},r.prototype._condense=function(e){for(var t=e.length-1,n=void 0;t>=0;t--)e[t].children.length===0?t>0?(n=e[t-1].children).splice(n.indexOf(e[t]),1):this.clear():a(e[t],this.toBBox)},r})}))(),1),rR=class{rTrees={};constructor(e=[]){let t={};for(let n of e){let e=n.boundingBox.sheetId;t[e]||(t[e]=[]),t[e].push(n)}for(let e in t)this.rTrees[e]=new iR,this.rTrees[e].load(t[e])}insert(e){let t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new iR),this.rTrees[t].insert(e)}search({zone:e,sheetId:t}){return this.rTrees[t]?this.rTrees[t].search({minX:e.left,minY:e.top,maxX:e.right,maxY:e.bottom}):[]}remove(e){let t=e.boundingBox.sheetId;this.rTrees[t]&&this.rTrees[t].remove(e,this.rtreeItemComparer)}rtreeItemComparer(e,t){return e.boundingBox.sheetId===t.boundingBox.sheetId&&e.boundingBox?.zone.left===t.boundingBox.zone.left&&e.boundingBox?.zone.top===t.boundingBox.zone.top&&e.boundingBox?.zone.right===t.boundingBox.zone.right&&e.boundingBox?.zone.bottom===t.boundingBox.zone.bottom&&C(e.data,t.data)}},iR=class extends nR.default{toBBox({boundingBox:e}){let t=e.zone;return{minX:t.left,minY:t.top,maxX:t.right,maxY:t.bottom}}compareMinX(e,t){return e.boundingBox.zone.left-t.boundingBox.zone.left}compareMinY(e,t){return e.boundingBox.zone.top-t.boundingBox.zone.top}},aR=class{createEmptyPositionSet;dependencies=new kL;rTree;constructor(e,t=[]){this.createEmptyPositionSet=e,this.rTree=new rR(t)}removeAllDependencies(e){let t=this.dependencies.get(e);if(t){for(let e of t)this.rTree.remove(e);this.dependencies.delete(e)}}addDependencies(e,t){let n=t.map(({sheetId:t,zone:n})=>({data:e,boundingBox:{zone:n,sheetId:t}}));for(let e of n)this.rTree.insert(e);let r=this.dependencies.get(e);r?r.push(...n):this.dependencies.set(e,n)}getCellsDependingOn(e,t){let n=this.createEmptyPositionSet(),r=Array.from(e).reverse(),i=this.createEmptyPositionSet();for(let t of e){let e=t.zone,n=t.sheetId;for(let t=e.left;t<=e.right;t++)for(let r=e.top;r<=e.bottom;r++)i.add({sheetId:n,col:t,row:r})}for(;r.length>0;){let e=r.pop(),a=e.zone,o=e.sheetId;for(let e=a.left;e<=a.right;e++)for(let t=a.top;t<=a.bottom;t++)n.add({sheetId:o,col:e,row:t});let s=this.rTree.search(e).map(e=>e.data),c={};for(let e of s)t.has(e)||(i.delete(e),n.has(e)||(c[e.sheetId]||(c[e.sheetId]=[]),c[e.sheetId].push(E(e))));for(let e in c){let t=Fn(c[e],[]);r.push(...t.map(t=>({sheetId:e,zone:t})))}}for(let e of i)n.delete(e);return n}},oR=class extends Uint32Array{columnOffset=0;cols=0;rows=0;static create(e,t){let n=sR(t),r=e<<n>>5,i=new this(r+1);return i.columnOffset=n,i.cols=t,i.rows=e,i}getValue(e){let[t,n]=this.getCoordinates(e);return this[t]>>n&1}setValue(e,t){let[n,r]=this.getCoordinates(e),i=(this[n]>>r&1)==0&&t===1;return this[n]=this[n]&~(1<<r)|t<<r,i}isEmpty(){return!this.some(e=>e!==0)}fillAllPositions(){this.fill(-1>>>0)}clear(){this.fill(0)}getCoordinates(e){let{row:t,col:n}=e,r=(t<<this.columnOffset)+n,i=r>>5;return[i,r-(i<<5)]}};function sR(e){return e===0?-1/0:e<0?NaN:32-Math.clz32(--e)}var cR=class{sheets={};insertions=[];maxSize=0;constructor(e){for(let t in e){let n=e[t].cols,r=e[t].rows;this.maxSize+=n*r,this.sheets[t]=oR.create(r,n)}}add(e){this.sheets[e.sheetId].setValue(e,1)&&this.insertions.push(e)}addMany(e){for(let t of e)this.add(t)}delete(e){this.sheets[e.sheetId].setValue(e,0)}deleteMany(e){for(let t of e)this.delete(t)}has(e){return this.sheets[e.sheetId].getValue(e)===1}clear(){let e=[...this];this.insertions=[];for(let e in this.sheets)this.sheets[e].clear();return e}isEmpty(){if(this.insertions.length===0)return!0;for(let e in this.sheets)if(!this.sheets[e].isEmpty())return!1;return!0}fillAllPositions(){this.insertions=Array(this.maxSize);let e=0;for(let t in this.sheets){let n=this.sheets[t];n.fillAllPositions();for(let r=0;r<n.rows;r++)for(let i=0;i<n.cols;i++)this.insertions[e++]={sheetId:t,row:r,col:i}}}*[Symbol.iterator](){for(let e of this.insertions)this.sheets[e.sheetId].getValue(e)===1&&(yield e)}},lR=class{resultsToArrayFormulas=new rR;arrayFormulasToResults=new kL;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map(e=>e.data)||uR}getArrayResultZone(e){return this.arrayFormulasToResults.get(e)}removeNode(e){let t=this.arrayFormulasToResults.get(e);t&&(this.resultsToArrayFormulas.remove({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.delete(e))}addRelation({arrayFormulaPosition:e,resultZone:t}){this.resultsToArrayFormulas.insert({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.set(e,t)}isArrayFormula(e){return this.arrayFormulasToResults.has(e)}};let uR=[],dR=Object.freeze(_s(new ia)),fR=Object.freeze(_s({value:null}));var pR=class{context;getters;compilationParams;evaluatedCells=new kL;formulaDependencies=Et(new aR(this.createEmptyPositionSet.bind(this)));blockedArrayFormulas=new cR({});spreadingRelations=new lR;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=eR(this.context,this.getters,this.computeAndSave.bind(this))}getEvaluatedCell(e){return this.evaluatedCells.get(e)||fR}getSpreadZone(e,t={ignoreSpillError:!1}){let n=this.spreadingRelations.getArrayResultZone(e);if(!n)return;let r=this.evaluatedCells.get(e);return r?.type===`error`&&!(t.ignoreSpillError&&r?.value===A.SpilledBlocked)?E(e):sr(E(e),n)}getEvaluatedPositions(){return this.evaluatedCells.keys()}getEvaluatedPositionsInSheet(e){return this.evaluatedCells.keysForSheet(e)}getArrayFormulaSpreadingOn(e){if(this.getEvaluatedCell(e).type===`empty`)return;let t=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e.sheetId,E(e));return Array.from(t).find(e=>!this.blockedArrayFormulas.has(e))}isArrayFormulaSpillBlocked(e){return this.blockedArrayFormulas.has(e)}updateDependencies(e){this.formulaDependencies().removeAllDependencies(e);let t=this.getDirectDependencies(e);this.formulaDependencies().addDependencies(e,t)}addDependencies(e,t){this.formulaDependencies().addDependencies(e,t);for(let e of t)this.compilationParams.ensureRange(e)}updateCompilationParameters(e){this.compilationParams=eR(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.__originCellPosition=e,this.compilationParams.evalContext.lookupCaches=this.compilationParams.evalContext.lookupCaches||{forwardSearch:new Map,reverseSearch:new Map}}updateCompilationParametersForGridEvaluation(){this.compilationParams=eR(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.updateDependencies=this.updateDependencies.bind(this),this.compilationParams.evalContext.addDependencies=this.addDependencies.bind(this),this.compilationParams.evalContext.lookupCaches={forwardSearch:new Map,reverseSearch:new Map}}createEmptyPositionSet(){let e={};for(let t of this.getters.getSheetIds())e[t]={rows:this.getters.getNumberRows(t),cols:this.getters.getNumberCols(t)};return new cR(e)}evaluateCells(e){let t=performance.now(),n=this.createEmptyPositionSet();n.addMany(e);let r=this.getArrayFormulasImpactedByChangesOf(e);n.addMany(this.getCellsDependingOn(e)),n.addMany(r),n.addMany(this.getCellsDependingOn(r)),this.evaluate(n),console.debug(`evaluate Cells`,performance.now()-t,`ms`)}getArrayFormulasImpactedByChangesOf(e){let t=this.createEmptyPositionSet();for(let n of e){let e=this.getters.getCell(n)?.content,r=this.getArrayFormulaSpreadingOn(n);r!==void 0&&t.add(r),e||t.add(n)}let n=_r(t);for(let e in n)for(let r of n[e])t.addMany(this.getArrayFormulasBlockedBy(e,r));return t}buildDependencyGraph(){this.blockedArrayFormulas=this.createEmptyPositionSet(),this.spreadingRelations=new lR,this.formulaDependencies=Et(()=>{let e=[...this.getAllCells()].flatMap(e=>this.getDirectDependencies(e).filter(e=>!e.invalidSheetName&&!e.invalidXc).map(t=>({data:e,boundingBox:{zone:t.zone,sheetId:t.sheetId}})));return new aR(this.createEmptyPositionSet.bind(this),e)})}evaluateAllCells(){let e=performance.now();this.evaluatedCells=new kL,this.evaluate(this.getAllCells()),console.debug(`evaluate all cells`,performance.now()-e,`ms`)}evaluateFormulaResult(e,t,n){let r=kE(t),i=r.dependencies.map(t=>this.getters.getRangeFromSheetXC(e,t));return this.updateCompilationParameters(n),this.evaluateCompiledFormula(e,{...r,dependencies:i})}evaluateCompiledFormula(e,t,n){try{let r=gR(t,this.compilationParams,e,this.buildSafeGetSymbolValue(n),this.compilationParams.evalContext.__originCellPosition);return k(r)?Na(r,hR):hR(r)}catch(e){return VT(e,``)}}getAllCells(){let e=this.createEmptyPositionSet();return e.fillAllPositions(),e}getArrayFormulasBlockedBy(e,t){let n=this.createEmptyPositionSet(),r=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e,t);n.addMany(r);let i=[...r].filter(e=>!this.blockedArrayFormulas.has(e));return i.length&&n.deleteMany(i),n.addMany(this.getCellsDependingOn(n)),n}nextPositionsToUpdate=new cR({});cellsBeingComputed=new Set;symbolsBeingComputed=new Set;evaluate(e){this.cellsBeingComputed=new Set,this.nextPositionsToUpdate=e;let t=0;for(;!this.nextPositionsToUpdate.isEmpty()&&t++<30;){this.updateCompilationParametersForGridEvaluation();let e=this.nextPositionsToUpdate.clear();for(let t=0;t<e.length;++t)this.evaluatedCells.delete(e[t]);for(let t=0;t<e.length;++t){let n=e[t];if(this.nextPositionsToUpdate.has(n))continue;let r=this.computeCell(n);r!==fR&&this.evaluatedCells.set(n,r)}QL.getAll().forEach(e=>e(this.getters))}t>=30&&console.warn(`Maximum iteration reached while evaluating cells`)}computeCell(e){let t=this.evaluatedCells.get(e);if(t)return t;this.blockedArrayFormulas.has(e)||this.invalidateSpreading(e),this.spreadingRelations.isArrayFormula(e)&&this.spreadingRelations.removeNode(e);let n=this.getters.getCell(e);if(n===void 0)return fR;let r=n.id,i={format:n.format,locale:this.getters.getLocale()};try{return this.cellsBeingComputed.has(r)?dR:(this.cellsBeingComputed.add(r),n.isFormula?this.computeFormulaCell(e,n):hs(n,i))}catch(e){return e.value=e?.value||A.GenericError,e.message=e?.message||WT,_s(e)}finally{this.cellsBeingComputed.delete(r)}}computeAndSave(e){let t=this.computeCell(e);return this.evaluatedCells.has(e)||this.evaluatedCells.set(e,t),t}computeFormulaCell(e,t){let n=gR(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e);if(!k(n))return _s(hR(n),this.getters.getLocale(),t);this.assertSheetHasEnoughSpaceToSpreadFormulaResult(e,n);let r=n.length,i=n[0].length;if(i===0)return _s({value:0},this.getters.getLocale(),t);if(i===1&&r===1)return _s(hR(n[0][0]),this.getters.getLocale(),t);let a={top:e.row,bottom:e.row+i-1,left:e.col,right:e.col+r-1};return this.spreadingRelations.addRelation({resultZone:a,arrayFormulaPosition:e}),this.assertNoMergedCellsInSpreadZone(e,n),mR(r,i,this.checkCollision(e)),mR(r,i,this.spreadValues(e,n)),this.invalidatePositionsDependingOnSpread(e.sheetId,a),_s(hR(n[0][0]),this.getters.getLocale(),t)}invalidatePositionsDependingOnSpread(e,t){let n=this.formulaDependencies().getCellsDependingOn(gr(t).map(t=>({sheetId:e,zone:t})),this.nextPositionsToUpdate);n.delete({sheetId:e,col:t.left,row:t.top}),this.nextPositionsToUpdate.addMany(n)}assertSheetHasEnoughSpaceToSpreadFormulaResult({sheetId:e,col:t,row:n},r){let i=this.getters.getNumberCols(e),a=this.getters.getNumberRows(e),o=t+r.length<=i,s=n+r[0].length<=a;if(!(o&&s))throw o?new ca(T(`Result couldn't be automatically expanded. Please insert more rows.`)):s?new ca(T(`Result couldn't be automatically expanded. Please insert more columns.`)):new ca(T(`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 ca(T(`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 ca(T(`Array result was not expanded because it would overwrite data in %s.`,w(o.col,o.row)));this.blockedArrayFormulas.delete(e)}}spreadValues({sheetId:e,col:t,row:n},r){return(i,a)=>{let o={sheetId:e,col:i+t,row:a+n},s=this.getters.getCell(o),c=_s(hR(r[i][a]),this.getters.getLocale(),s);this.evaluatedCells.set(o,c)}}invalidateSpreading(e){let t=this.spreadingRelations.getArrayResultZone(e);if(!t)return;for(let n=t.left;n<=t.right;n++)for(let r=t.top;r<=t.bottom;r++){let t={sheetId:e.sheetId,col:n,row:r};this.getters.getCell(t)?.content||this.evaluatedCells.delete(t)}let n=e.sheetId;this.invalidatePositionsDependingOnSpread(n,t),this.nextPositionsToUpdate.addMany(this.getArrayFormulasBlockedBy(n,t))}buildSafeGetSymbolValue(e){return t=>{if(this.symbolsBeingComputed.has(t))return dR;this.symbolsBeingComputed.add(t);try{return e?.(t)||new ra(T(`Invalid formula`))}finally{this.symbolsBeingComputed.delete(t)}}}getDirectDependencies(e){let t=this.getters.getCell(e);return t?.isFormula?t.compiledFormula.dependencies:[]}getCellsDependingOn(e){let t=[],n=_r(e);for(let e in n)t.push(...n[e].map(t=>({sheetId:e,zone:t})));return this.formulaDependencies().getCellsDependingOn(t,this.nextPositionsToUpdate)}};function mR(e,t,n){for(let r=0;r<e;++r)for(let e=0;e<t;++e)r===0&&e===0||n(r,e)}function hR(e){return e.value===null||e.value===void 0?{...e,value:0}:e}function gR(e,t,n,r,i){let a=t.evalContext,o=a.__originCellPosition,s=a.__originSheetId;a.__originCellPosition=i,a.__originSheetId=n;let c=e.execute(e.dependencies,t.referenceDenormalizer,t.ensureRange,r,a);return a.__originCellPosition=o,a.__originSheetId=s,c}var _R=class extends ${static getters=[`evaluateFormula`,`evaluateFormulaResult`,`evaluateCompiledFormula`,`getCorrespondingFormulaCell`,`getRangeFormattedValues`,`getRangeValues`,`getRangeFormats`,`getEvaluatedCell`,`getEvaluatedCells`,`getEvaluatedCellsInZone`,`getEvaluatedCellsPositions`,`getSpreadZone`,`getArrayFormulaSpreadingOn`,`isArrayFormulaSpillBlocked`,`isEmpty`];shouldRebuildDependenciesGraph=!0;evaluator;positionsToUpdate=[];constructor(e){super(e),this.evaluator=new pR(e.custom,this.getters)}beforeHandle(e){(zi.has(e.type)||Vi.has(e.type))&&(this.shouldRebuildDependenciesGraph=!0)}handle(e){switch(e.type){case`UPDATE_CELL`:if(!(`content`in e||`format`in e)||this.shouldRebuildDependenciesGraph)return;let t={sheetId:e.sheetId,row:e.row,col:e.col};this.positionsToUpdate.push(t),`content`in e&&this.evaluator.updateDependencies(t);break;case`EVALUATE_CELLS`:this.evaluator.evaluateAllCells();break}}finalize(){this.shouldRebuildDependenciesGraph?(this.evaluator.buildDependencyGraph(),this.evaluator.evaluateAllCells(),this.shouldRebuildDependenciesGraph=!1):this.positionsToUpdate.length&&this.evaluator.evaluateCells(this.positionsToUpdate),this.positionsToUpdate=[]}evaluateFormula(e,t,n){let r=this.evaluateFormulaResult(e,t,n);return k(r)?Na(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 vr(t).map(({col:t,row:n})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}))}getSpreadZone(e,t={ignoreSpillError:!1}){return this.evaluator.getSpreadZone(e,t)}getArrayFormulaSpreadingOn(e){return this.evaluator.getArrayFormulaSpreadingOn(e)}isArrayFormulaSpillBlocked(e){return this.evaluator.isArrayFormulaSpillBlocked(e)}isEmpty(e,t){return vr(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 vr(r).reduce((e,r)=>{let{col:i,row:a}=r;return!this.getters.isColHidden(n,i)&&!this.getters.isRowHidden(n,a)&&e.push(t({sheetId:n,...r})),e},[])}exportForExcel(e){for(let t of e.sheets)t.formulaSpillRanges={};for(let t of this.evaluator.getEvaluatedPositions()){let n=this.evaluator.getEvaluatedCell(t),r=w(t.col,t.row),i=n.value,a=!1,o,s,c=!0,l=e.sheets.find(e=>e.id===t.sheetId),u=this.getCorrespondingFormulaCell(t);if(u){let e=this.getters.getCell(t);c=LE(u.compiledFormula.tokens),a=c&&e?.content===u.content,c||i!==``&&(o=(i??``).toString(),s=n.format)}let d=l.cells[r]||{},f=s?Fr(s,e.formats):d.format,p;p=c&&a&&u instanceof jL?u.contentWithFixedReferences:c?d.content:o,l.cells[r]={...d,value:i,isFormula:a,content:p,format:f};let m=this.getSpreadZone(t);m&&(l.formulaSpillRanges[r]=this.getters.getRangeString(this.getters.getRangeFromZone(t.sheetId,m),t.sheetId))}}getCorrespondingFormulaCell(e){let t=this.getters.getCell(e);if(t&&t.isFormula)return t.compiledFormula.isBadExpression?void 0:t;if(t&&t.content)return;let n=this.getArrayFormulaSpreadingOn(e);if(n===void 0)return;let r=this.getters.getCell(n);if(r?.isFormula)return r}};let vR=/"(#[0-9a-fA-F]{6})"/g;function yR(e){let t=[{leadColor:an(255,0,0),colors:[]},{leadColor:an(255,128,0),colors:[]},{leadColor:an(128,128,0),colors:[]},{leadColor:an(128,255,0),colors:[]},{leadColor:an(0,255,0),colors:[]},{leadColor:an(0,255,128),colors:[]},{leadColor:an(0,255,255),colors:[]},{leadColor:an(0,127,255),colors:[]},{leadColor:an(0,0,255),colors:[]},{leadColor:an(127,0,255),colors:[]},{leadColor:an(128,0,128),colors:[]},{leadColor:an(255,0,128),colors:[]}];for(let n of e.map(ln)){let e=500,r=0;t.forEach((t,i)=>{let a=bR(n,t.leadColor);e>a&&(e=a,r=i)}),t[r].colors.push(n)}return t.map(e=>e.colors.sort((e,t)=>dn(e).s-dn(t).s)).flat().map(cn)}function bR(e,t){return Math.sqrt((e.r-t.r)**2+(e.g-t.g)**2+(e.b-t.b)**2)}var xR=class extends ${customColors={};shouldUpdateColors=!0;static getters=[`getCustomColors`];constructor(e){super(e),this.tryToAddColors(e.customColors??[])}handle(e){switch(e.type){case`START`:for(let e of this.getters.getSheetIds())for(let t of this.getters.getChartIds(e))this.tryToAddColors(this.getChartColors(t));break;case`UPDATE_CHART`:case`CREATE_CHART`:this.tryToAddColors(this.getChartColors(e.id));break;case`COLOR_SHEET`:e.color&&this.tryToAddColors([e.color]);break;case`UPDATE_CELL`:case`ADD_CONDITIONAL_FORMAT`:case`SET_BORDER`:case`SET_ZONE_BORDERS`:case`SET_FORMATTING`:case`CREATE_TABLE`:case`UPDATE_TABLE`:this.history.update(`shouldUpdateColors`,!0);break}}finalize(){this.shouldUpdateColors&&(this.history.update(`shouldUpdateColors`,!1),this.tryToAddColors(this.computeCustomColors()))}getCustomColors(){return yR(Object.keys(this.customColors))}computeCustomColors(){let e=[];for(let t of this.getters.getSheetIds())e=e.concat(this.getSheetColors(t),this.getColorsFromCells(t),this.getFormattingColors(t),this.getTableColors(t));return[...new Set([...e])]}getSheetColors(e){let t=this.getters.getSheet(e);return t.color?[t.color]:[]}getColorsFromCells(e){let t=Object.values(this.getters.getCells(e)),n=new Set;for(let e of t)e.style?.textColor&&n.add(e.style.textColor),e.style?.fillColor&&n.add(e.style.fillColor);for(let t of this.getters.getBordersColors(e))n.add(t);return[...n]}getFormattingColors(e){let t=this.getters.getConditionalFormats(e),n=[];for(let e of t){let t=e.rule;t.type===`CellIsRule`?(n.push(t.style.textColor),n.push(t.style.fillColor)):t.type===`ColorScaleRule`&&(n.push($t(t.minimum.color)),n.push(t.midpoint?$t(t.midpoint.color):void 0),n.push($t(t.maximum.color)))}return n.filter(S)}getChartColors(e){let t=this.getters.getChart(e);return t===void 0?[]:[...JSON.stringify(t.getDefinition()).matchAll(vR)].map(e=>e[1])}getTableColors(e){return this.getters.getTables(e).flatMap(e=>{let t=e.config,n=this.getters.getTableStyle(t.styleId);return[this.getTableStyleElementColors(n.wholeTable),t.numberOfHeaders>0?this.getTableStyleElementColors(n.headerRow):[],t.totalRow?this.getTableStyleElementColors(n.totalRow):[],t.bandedColumns?this.getTableStyleElementColors(n.firstColumnStripe):[],t.bandedColumns?this.getTableStyleElementColors(n.secondColumnStripe):[],t.bandedRows?this.getTableStyleElementColors(n.firstRowStripe):[],t.bandedRows?this.getTableStyleElementColors(n.secondRowStripe):[],t.firstColumn?this.getTableStyleElementColors(n.firstColumn):[],t.lastColumn?this.getTableStyleElementColors(n.lastColumn):[]].flat()})}getTableStyleElementColors(e){return e?[e.style?.fillColor,e.style?.textColor,e.border?.bottom?.color,e.border?.top?.color,e.border?.left?.color,e.border?.right?.color,e.border?.horizontal?.color,e.border?.vertical?.color].filter(S):[]}tryToAddColors(e){for(let t of e){if(!tn(t))continue;let e=en(t);t&&!Ne.includes(e)&&this.history.update(`customColors`,e,!0)}}},SR=class extends ${static getters=[`getChartRuntime`,`getStyleOfSingleCellChart`];charts={};createRuntimeChart=_k(this.getters);handle(e){if(zi.has(e.type)||Hi.has(e.type)||Bi.has(e.type))for(let e in this.charts)this.charts[e]=void 0;switch(e.type){case`UPDATE_CHART`:case`CREATE_CHART`:case`DELETE_FIGURE`:this.charts[e.id]=void 0;break;case`DELETE_SHEET`:for(let e in this.charts)this.getters.isChartDefined(e)||(this.charts[e]=void 0);break}}getChartRuntime(e){if(!this.charts[e]){let t=this.getters.getChart(e);if(!t)throw Error(`No chart for the given id: ${e}`);this.charts[e]=this.createRuntimeChart(t)}return this.charts[e]}getStyleOfSingleCellChart(e,t){if(e)return{background:e,fontColor: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)}}exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let r of e){if(!r||r.tag!==`chart`)continue;let e=r.id,i=this.getters.getChart(e)?.getDefinitionForExcel();if(i)n.push({...r,data:i});else{if(!this.getters.getChart(e))continue;let n=this.getters.getChartType(e),i=r_(this.getters.getChartRuntime(e),r,n);i&&t.images.push({...r,tag:`image`,data:{mimetype:`image/png`,path:i,size:{width:r.width,height:r.height}}})}}t.charts=n}}},CR=class extends ${static getters=[`getConditionalIcon`,`getCellConditionalFormatStyle`,`getConditionalDataBar`];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(zi.has(e.type)||Hi.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e))&&(this.isStale=!0)}finalize(){if(this.isStale){for(let e of this.getters.getSheetIds())this.computedStyles[e]=Et(()=>this.getComputedStyles(e)),this.computedIcons[e]=Et(()=>this.getComputedIcons(e)),this.computedDataBars[e]=Et(()=>this.getComputedDataBars(e));this.isStale=!1}}getCellConditionalFormatStyle(e){let{sheetId:t,col:n,row:r}=e,i=this.computedStyles[t]();return i&&i[n]?.[r]}getConditionalIcon({sheetId:e,col:t,row:n}){let r=this.computedIcons[e]();return r&&r[t]?.[n]}getConditionalDataBar({sheetId:e,col:t,row:n}){let r=this.computedDataBars[e]();return r&&r[t]?.[n]}getComputedStyles(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())switch(n.rule.type){case`ColorScaleRule`:for(let r of n.ranges)this.applyColorScale(e,r,n.rule,t);break;case`CellIsRule`:let r=n.rule.values.map(e=>e.startsWith(`=`)?kE(e):void 0);for(let i of n.ranges){let a=this.getters.getRangeFromSheetXC(e,i).zone;for(let i=a.top;i<=a.bottom;i++)for(let o=a.left;o<=a.right;o++){let s=this.rulePredicate[n.rule.type],c={sheetId:e,col:o,row:i},l=n.rule.values.map((t,n)=>{let s=r[n];return s?this.getters.getTranslatedCellFormula(e,o-a.left,i-a.top,s.tokens):t});s&&s(c,{...n.rule,values:l})&&(t[o]||(t[o]=[]),t[o][i]=Object.assign(t[o]?.[i]||{},n.rule.style))}}break}return t}getComputedIcons(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`IconSetRule`)for(let r of n.ranges)this.applyIcon(e,r,n.rule,t);return t}getComputedDataBars(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`DataBarRule`)for(let r of n.ranges)this.applyDataBar(e,r,n.rule,t);return t}parsePoint(e,t,n,r){let i=this.getters.getEvaluatedCellsInZone(e,this.getters.getRangeFromSheetXC(e,t).zone).filter(e=>e.type===`number`).map(e=>e.value);switch(n.type){case`value`:return r===`max`?Gt(i):Kt(i);case`number`:return Number(n.value);case`percentage`:let t=Kt(i);return t+(Gt(i)-t)*Number(n.value)/100;case`percentile`:return Mi(i,Number(n.value)/100,!0);case`formula`:let a=n.value&&this.getters.evaluateFormula(e,n.value);return typeof a==`number`?a:null;default:return null}}applyIcon(e,t,n,r){let i=this.parsePoint(e,t,n.lowerInflectionPoint),a=this.parsePoint(e,t,n.upperInflectionPoint);if(i===null||a===null||i>a)return;let o=this.getters.getRangeFromSheetXC(e,t).zone,s=[n.icons.upper,n.icons.middle,n.icons.lower];for(let t=o.top;t<=o.bottom;t++)for(let c=o.left;c<=o.right;c++){let o=this.getters.getEvaluatedCell({sheetId:e,col:c,row:t});if(o.type!==`number`)continue;let l=this.computeIcon(o.value,a,n.upperInflectionPoint.operator,i,n.lowerInflectionPoint.operator,s);r[c]||(r[c]=[]),r[c][t]=l}}computeIcon(e,t,n,r,i,a){return n===`ge`&&e>=t||n===`gt`&&e>t?a[0]:i===`ge`&&e>=r||i===`gt`&&e>r?a[1]:a[2]}applyDataBar(e,t,n,r){let i=this.getters.getRangeFromSheetXC(e,n.rangeValues||t),a=Gt(this.getters.getEvaluatedCellsInZone(e,i.zone).filter(e=>e.type===`number`).map(e=>e.value));if(a<=0)return;let o=n.color,s=this.getters.getRangeFromSheetXC(e,t).zone,c=i.zone;for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let i=n-s.left+c.left,l=t-s.top+c.top,u=this.getters.getEvaluatedCell({sheetId:e,col:i,row:l});!fr(i,l,c)||u.type!==`number`||u.value<=0||(r[n]||(r[n]=[]),r[n][t]={color:$t(o),percentage:u.value*100/a})}}applyColorScale(e,t,n,r){let i=this.parsePoint(e,t,n.minimum,`min`),a=n.midpoint?this.parsePoint(e,t,n.midpoint):null,o=this.parsePoint(e,t,n.maximum,`max`);if(i===null||o===null||i>=o||a!==null&&(i>=a||a>=o))return;let s=this.getters.getRangeFromSheetXC(e,t).zone,c=[];n.midpoint&&a!==null?(c.push({minValue:i,minColor:n.minimum.color,colorDiffUnit:this.computeColorDiffUnits(i,a,n.minimum.color,n.midpoint.color)}),c.push({minValue:a,minColor:n.midpoint.color,colorDiffUnit:this.computeColorDiffUnits(a,o,n.midpoint.color,n.maximum.color)})):c.push({minValue:i,minColor:n.minimum.color,colorDiffUnit:this.computeColorDiffUnits(i,o,n.minimum.color,n.maximum.color)});for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let s=this.getters.getEvaluatedCell({sheetId:e,col:n,row:t});if(s.type===`number`){let e=b(s.value,i,o),l;l=c.length===2&&a!==null?e<=a?this.colorCell(e,c[0].minValue,c[0].minColor,c[0].colorDiffUnit):this.colorCell(e,c[1].minValue,c[1].minColor,c[1].colorDiffUnit):this.colorCell(e,c[0].minValue,c[0].minColor,c[0].colorDiffUnit),r[n]||(r[n]=[]),r[n][t]=r[n]?.[t]||{},r[n][t].fillColor=$t(l)}}}computeColorDiffUnits(e,t,n,r){let i=t-e,a=(n>>16)%256-(r>>16)%256,o=(n>>8)%256-(r>>8)%256,s=n%256-r%256;return[a/i,o/i,s/i]}colorCell(e,t,n,r){let[i,a,o]=r,s=Math.round((n>>16)%256-i*(e-t)),c=Math.round((n>>8)%256-a*(e-t)),l=Math.round(n%256-o*(e-t));return s<<16|c<<8|l}rulePredicate={CellIsRule:(e,t)=>{let n=this.getters.getEvaluatedCell(e);if(n.type===`error`)return!1;let[r,i]=t.values.map(t=>t.startsWith(`=`)?this.getters.evaluateFormula(e.sheetId,t)??``:gs(t,O));if(k(r)||k(i))return!1;let a=n.value??``;switch(r??=``,i??=``,t.operator){case`IsEmpty`:return a.toString().trim()===``;case`IsNotEmpty`:return a.toString().trim()!==``;case`BeginsWith`:return r===``?!1:a.toString().startsWith(r.toString());case`EndsWith`:return r===``?!1:a.toString().endsWith(r.toString());case`Between`:return a>=r&&a<=i;case`NotBetween`:return!(a>=r&&a<=i);case`ContainsText`:return a.toString().indexOf(r.toString())>-1;case`NotContains`:return!a||a.toString().indexOf(r.toString())===-1;case`GreaterThan`:return a>r;case`GreaterThanOrEqual`:return a>=r;case`LessThan`:return a<r;case`LessThanOrEqual`:return a<=r;case`NotEqual`:return r===``?!1:a!==r;case`Equal`:return r===``?!0:a===r;default:console.warn(T(`Not implemented operator %s for kind of conditional formatting: %s`,t.operator,t.type))}return!1}}};let wR={isValid:!0};var TR=class extends ${static getters=[`getDataValidationInvalidCriterionValueMessage`,`getInvalidDataValidationMessage`,`getValidationResultForCellValue`,`isCellValidCheckbox`,`isDataValidationInvalid`];validationResults={};handle(e){if(zi.has(e.type)||e.type===`EVALUATE_CELLS`||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)){this.validationResults={};return}switch(e.type){case`ADD_DATA_VALIDATION_RULE`:case`REMOVE_DATA_VALIDATION_RULE`:delete this.validationResults[e.sheetId];break}}isDataValidationInvalid(e){return!this.getValidationResultForCell(e).isValid}getInvalidDataValidationMessage(e){let t=this.getValidationResultForCell(e);return t.isValid?void 0:t.error}getDataValidationInvalidCriterionValueMessage(e,t){let n=Q.get(e);return t.startsWith(`=`)?n.allowedValues===`onlyLiterals`?T(`The value must not be a formula`):void 0:n.allowedValues===`onlyFormulas`?T(`The value must be a formula`):n.isCriterionValueValid(t)?void 0:n.criterionValueErrorString}isCellValidCheckbox(e){if(!this.getters.isMainCellPosition(e))return!1;let t=this.getters.getValidationRuleForCell(e);return!t||t.criterion.type!==`isBoolean`?!1:this.getValidationResultForCell(e).isValid}getValidationResultForCellValue(e,t){let n=this.getters.getValidationRuleForCell(t);if(!n)return wR;let r=this.getRuleErrorForCellValue(e,t,n);return r?{error:r,rule:n,isValid:!1}:wR}getValidationResultForCell(e){let{col:t,row:n,sheetId:r}=e;return this.validationResults[r]||(this.validationResults[r]=this.computeSheetValidationResults(r)),this.validationResults[r][t]?.[n]?.()||wR}computeSheetValidationResults(e){let t={},n=this.getters.getDataValidationRules(e).map(e=>e.ranges);for(let e of Js(n.flat())){let{col:n,row:r}=e;t[n]||(t[n]=[]),t[n][r]=Et(()=>{let t=this.getters.getEvaluatedCell(e);return t.type===`empty`?wR:this.getValidationResultForCellValue(t.value,e)})}return t}getRuleErrorForCellValue(e,t,n){let{sheetId:r}=t,i=n.criterion,a=Q.get(i.type),o=this.getCellOffsetInRule(t,n),s=this.getEvaluatedCriterionValues(r,o,i),c={...i,values:s};if(!a.isValueValid(e,c,this.getters,r))return a.getErrorString(c,this.getters,r)}getCellOffsetInRule(e,t){let n=t.ranges.find(t=>fr(e.col,e.row,t.zone));if(!n)throw Error(`The cell is not in any range of the rule`);return{col:e.col-n.zone.left,row:e.row-n.zone.top}}getEvaluatedCriterionValues(e,t,n){return n.values.map(n=>{if(!n.startsWith(`=`))return n;let r=kE(n),i=this.getters.getTranslatedCellFormula(e,t.col,t.row,r.tokens),a=this.getters.evaluateFormula(e,i);return a&&!k(a)?a.toString():``})}},ER=class extends ${static getters=[`canCreateDynamicTableOnZones`,`doesZonesContainFilter`,`getFilter`,`getFilters`,`getTable`,`getTables`,`getTablesOverlappingZones`,`getFilterId`,`getFilterHeaders`,`isFilterHeader`];tables={};handle(e){if(zi.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;dr(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=>fr(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getTables(e).filter(e=>t.some(t=>dr(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(!Or(t))return!1;let n=sr(...t),r={col:n.left,row:n.top,sheetId:e},i=this.getters.getArrayFormulaSpreadingOn(r);return i?C(i,r)&&Dr(n)===1?!0:C(n,this.getters.getSpreadZone(i)):!1}coreTableToTable(e,t){if(t.type!==`dynamic`)return t;let n=t.range.zone,r={sheetId:e,col:n.left,row:n.top},i=this.getters.getSpreadZone(r)??t.range.zone,a=this.getters.getRangeFromZone(e,i),o=this.getDynamicTableFilters(e,t,i);return{id:t.id,range:a,filters:o,config:t.config}}getDynamicTableFilters(e,t,n){let r=[],{top:i,bottom:a,left:o,right:s}=n;for(let n=o;n<=s;n++){let s=n-o,c={left:n,right:n,top:i,bottom:a},l=JF(this.getDynamicTableFilterId(t.id,s),this.getters.getRangeFromZone(e,c),t.config,this.getters.getRangeFromZone);r.push(l)}return r}getDynamicTableFilterId(e,t){return e+`_`+t}isTableExcelExportable(e,t){return t.type===`dynamic`?!1:!vr(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=$n(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 vr(s.range.zone)){let r={sheetId:t.id,...n},i=this.getters.getCellComputedStyle(r),a=this.getters.getCellComputedBorder(r),o=w(n.col,n.row),s=t.cells?.[o]||{value:``,isFormula:!1};if(t.cells[o]||(t.cells[o]=s),!St(i)){let n=Fr(i,e.styles);t.styles[o]=n,s.style=n}if(a){let n=Fr(a,e.borders);t.borders[o]=n,s.border=n}}}t.tables=n}}},DR=class extends ${static getters=[`getRowSize`,`getHeaderSize`];tallestCellInRow={};ctx=document.createElement(`canvas`).getContext(`2d`);beforeHandle(e){switch(e.type){case`ADD_COLUMNS_ROWS`:if(e.dimension===`COL`)return;let t=Ot(e.position,e.base),n=Array(e.quantity).fill(void 0),r=Bt(this.tallestCellInRow[e.sheetId],n,t);this.history.update(`tallestCellInRow`,e.sheetId,r);break}}handle(e){switch(e.type){case`START`:case`UPDATE_LOCALE`:for(let e of this.getters.getSheetIds())this.initializeSheet(e);break;case`CREATE_SHEET`:this.initializeSheet(e.sheetId);break;case`DUPLICATE_SHEET`:{let t=y(this.tallestCellInRow[e.sheetId]);this.history.update(`tallestCellInRow`,e.sheetIdTo,t);break}case`DELETE_SHEET`:let t={...this.tallestCellInRow};delete t[e.sheetId],this.history.update(`tallestCellInRow`,t);break;case`REMOVE_COLUMNS_ROWS`:{if(e.dimension===`COL`)return;let t=zt(this.tallestCellInRow[e.sheetId],e.elements);this.history.update(`tallestCellInRow`,e.sheetId,t);break}case`RESIZE_COLUMNS_ROWS`:{let t=e.sheetId;if(e.dimension===`ROW`)for(let n of e.elements){let e=this.getRowTallestCell(t,n);this.history.update(`tallestCellInRow`,t,n,e)}else for(let n of x(0,this.getters.getNumberRows(t)))for(let r of e.elements)this.updateRowSizeForCellChange(t,n,r)}break;case`UPDATE_CELL`:this.updateRowSizeForCellChange(e.sheetId,e.row,e.col);break;case`ADD_MERGE`:case`REMOVE_MERGE`:for(let t of e.target)for(let n of vr(t))this.updateRowSizeForCellChange(e.sheetId,n.row,n.col)}}getRowSize(e,t){return Math.round(this.getters.getUserRowSize(e,t)??this.tallestCellInRow[e][t]?.size??23)}getHeaderSize(e,t,n){return this.getters.isHeaderHidden(e,t,n)?0:t===`ROW`?this.getRowSize(e,n):this.getters.getColSize(e,n)}updateRowSizeForCellChange(e,t,n){let r=this.tallestCellInRow[e]?.[t];if(r?.cell.col===n){let n=this.getRowTallestCell(e,t);this.history.update(`tallestCellInRow`,e,t,n)}let i=this.getCellHeight({sheetId:e,col:n,row:t});if(!(i<=23)&&(!r&&i>23||r&&i>r.size)){let r={cell:{sheetId:e,col:n,row:t},size:i};this.history.update(`tallestCellInRow`,e,t,r)}}initializeSheet(e){let t=[];for(let n=0;n<this.getters.getNumberRows(e);n++){let r=this.getRowTallestCell(e,n);t.push(r)}this.history.update(`tallestCellInRow`,e,t)}getCellHeight(e){if(this.isInMultiRowMerge(e))return 23;let t=this.getters.getCell(e),n=this.getters.getColSize(e.sheetId,e.col);return ic(this.ctx,t,this.getters.getLocale(),n)}isInMultiRowMerge(e){let t=this.getters.getMerge(e);return!!t&&t.bottom!==t.top}getRowTallestCell(e,t){if(this.getters.getUserRowSize(e,t)!==void 0)return;let n=this.getters.getRowCells(e,t),r=0,i;for(let e=0;e<n.length;e++){let t=this.getters.getCellById(n[e]);if(!t)continue;let a=this.getters.getCellPosition(t.id),o=this.getCellHeight(a);o>r&&o>23&&(r=o,i={cell:a,size:o})}if(i&&i.size>23)return i}};let OR=`0.00%`;function kR(e){class t extends e{getters;pivotId;cache={};rankAsc={};rankDesc={};runningTotal={};runningTotalInPercent={};constructor(e,t,n){super(t,n),this.getters=n.getters,this.pivotId=e}markAsDirtyForEvaluation(){this.cache={},this.rankAsc={},this.rankDesc={},this.runningTotal={},this.runningTotalInPercent={},super.markAsDirtyForEvaluation?.()}getPivotCellValueAndFormat(e,t){return this.getMeasureDisplayValue(e,t)}_getPivotCellValueAndFormat(e,t){let n=`${e}-${t.map(e=>e.field+`=`+e.value).join(`,`)}`;if(this.cache[n])return this.cache[n];let r=this.getMeasure(e),i=r.computedBy?this.computeMeasure(r,t):super.getPivotCellValueAndFormat(e,t);return r.format?this.cache[n]={...i,format:r.format}:this.cache[n]=i,this.cache[n]}computeMeasure(e,t){if(!e.computedBy)return{value:0};let{columns:n,rows:r}=super.definition;if(e.aggregator&&n.length+r.length!==t.length){let n=this.getValuesToAggregate(e,t),r=Ou[e.aggregator];if(!r)return{value:0};try{return r([n],this.getters.getLocale())}catch(t){return VT(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}=Yl(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new oa:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}if(r.find(t=>t.nameWithGranularity===e)){let{rowDomain:n}=Yl(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new oa:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}return this.getPivotCellValueAndFormat(e,t)});return k(a)?a[0][0]:a}getValuesToAggregate(e,t){let{rowDomain:n,colDomain:r}=Yl(this,t),i=this.getTableStructure(),a=[];if(r.length===0&&n.length<this.definition.rows.length&&this.definition.rows.length&&this.definition.columns.length){let t=this.treeToLeafDomains(i.getColTree()),r=this.getSubTreeMatchingDomain(i.getRowTree(),n),o=this.treeToLeafDomains(r);for(let r of t)for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t).concat(r)));return a}else if(n.length===this.definition.rows.length&&r.length===0){let t=i.getColTree(),o=this.getSubTreeMatchingDomain(t,r),s=this.treeToLeafDomains(o,r);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else if(n.length===this.definition.rows.length&&r.length&&r.length<this.definition.columns.length){let t=this.getSubTreeMatchingDomain(i.getColTree(),r),o=this.treeToLeafDomains(t,r);for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else{let t=i.getRowTree(),o=this.getSubTreeMatchingDomain(t,n),s=this.treeToLeafDomains(o,n);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,t.concat(r)));return a}}getSubTreeMatchingDomain(e,t,n=0){if(n>t.length)return[];if(t.length===n)return e;for(let r of e){let e=Lu(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:T(`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 VT(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:OR}}asPercentOfRowTotal(e,t,n){let r=this.getRowTotal(t.id,n);return r===0?{value:A.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:OR}}asPercentOfColumnTotal(e,t,n){let r=this.getColumnTotal(t.id,n);return r===0?{value:A.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:OR}}asPercentOfParentRowTotal(e,t,n){let r=ql(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:OR}}asPercentOfParentColumnTotal(e,t,n){let r=Jl(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:OR}}asPercentOfParentTotal(e,t,n,r){let{fieldNameWithGranularity:i}=r;if(!i)return e;if(!ru(i,n))return{value:``};let a=tu(this,i,n),o=this._getPivotCellValueAndFormat(t.id,a),s=this.measureValueToNumber(o);return s===0?{value:``}:{value:this.measureValueToNumber(e)/s,format:OR}}asIndex(e,t,n){let r=this.measureValueToNumber(e),i=this.getRowTotal(t.id,n),a=this.getColumnTotal(t.id,n),o=this.getGrandTotal(t.id);return i===0||a===0?{value: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}=Yl(this,n),u=ou(l),d=ou(c);return{value:s[u]?.[d]??``,format:i===`running_total`?e.format:OR}}asPercentOf(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!ru(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:OR}:s===void 0?{value:A.NullError}:{value:s/o,format:OR}}asDifferenceFrom(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!ru(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(!ru(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:OR}}asRank(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;if(!ru(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}=Yl(this,n),u=ou(l),d=ou(c);return{value:s[u]?.[d]??``}}computeRank(e,t,n){let r={},i=iu(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=Fa(o));for(let s of o){let o=ou(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=>ru(t,e.rowDomain)),l=Object.groupBy(c,e=>cu(e.rowDomain,t));for(let e in l)l[e]=Jt(l[e]||[],e=>e.value).filter(e=>e.value!==void 0).sort((e,t)=>n===`asc`?e.value-t.value:t.value-e.value);r[o]={};for(let e of c){let n=ou(Xl(this,i,e.domain)),a=l[cu(e.rowDomain,t)];if(!a)continue;let s=a.findIndex(t=>t.value===e.value);s!==-1&&(r[o][n]=s+1)}}return i===`row`?r:Yt(r)}computeRunningTotal(e,t,n){let r={},i=iu(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=Fa(o));for(let s of o){let o=ou(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=>ru(t,e.rowDomain));for(let e of l){let n=ou(e.rowDomain),i=lu(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=ou(n),a=lu(n,t),s=r[o][i]||0,l=c[a];r[o][i]=l?s/l:void 0}}return i===`row`?r:Yt(r)}getGrandTotal(e){let t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){let n=Yl(this,t).rowDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}getColumnTotal(e,t){let n=Yl(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)`?au(this,t,n,r):nu(t,n,r);if(C(i,t))return`sameValue`;if(!i||!Ql(this,i))throw new oa;let a=this._getPivotCellValueAndFormat(e.id,i);return this.strictMeasureValueToNumber(a)}getPivotValueCells(e){return this.getTableStructure().getPivotCells().map(t=>t.filter(t=>t.type===`VALUE`&&t.measure===e)).filter(e=>e.length>0)}measureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(!e.value)return 0;throw Error(`Value ${e.value} is not a number`)}strictMeasureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(e.value)throw Error(`Value ${e.value} is not a number`)}}return t}let AR=[`ADD_PIVOT`,`UPDATE_PIVOT`,`REMOVE_PIVOT`];function jR(e){return AR.includes(e.type)}var MR=class extends ${static getters=[`getPivot`,`getFirstPivotFunction`,`getPivotIdFromPosition`,`getPivotIdsFromPosition`,`getPivotCellFromPosition`,`generateNewCalculatedMeasureName`,`isPivotUnused`,`isSpillPivotFormula`];pivots={};unusedPivots;custom;constructor(e){super(e),this.custom=e.custom}beforeHandle(e){switch(e.type){case`START`:for(let e of this.getters.getPivotIds())this.setupPivot(e)}}handle(e){if(zi.has(e.type))for(let e of this.getters.getPivotIds())this.setupPivot(e,{recreate:!0});switch(e.type){case`REFRESH_PIVOT`:this.refreshPivot(e.id);break;case`ADD_PIVOT`:this.unusedPivots?.push(e.pivotId),this.setupPivot(e.pivotId);break;case`DUPLICATE_PIVOT`:this.unusedPivots?.push(e.newPivotId),this.setupPivot(e.newPivotId);break;case`UPDATE_PIVOT`:this.setupPivot(e.pivotId,{recreate:!0});break;case`DELETE_SHEET`:case`UPDATE_CELL`:this.unusedPivots=void 0;break;case`UNDO`:case`REDO`:{this.unusedPivots=void 0;let t=e.commands.filter(jR);for(let e of t){let t=e.pivotId;this.getters.isExistingPivot(t)&&this.setupPivot(t,{recreate:!0})}break}case`UPDATE_LOCALE`:kF();break}}getPivotIdFromPosition(e){return this.getPivotIdsFromPosition(e)[0]}getPivotIdsFromPosition(e){let t=this.getters.getCorrespondingFormulaCell(e);return t&&t.isFormula?this.getPivotIdsFromFormula(e.sheetId,t.compiledFormula):[]}getPivotIdsFromFormula(e,t){return this.getPivotFunctions(e,t.tokens).map(e=>{let t=e.args[0]?.toString();return t&&this.getters.getPivotId(t)}).filter(S)}isSpillPivotFormula(e){let t=this.getters.getCorrespondingFormulaCell(e);return t&&t.isFormula?this.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens)?.functionName===`PIVOT`:!1}getPivotFunctions(e,t){let n=qE(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=xC(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||JE(t.compiledFormula.tokens)===0)return gF;let n=this.getters.getCellPosition(t.id),r=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(!r)return gF;let{functionName:i,args:a}=r,o=a[0];if(!o)return gF;let s=this.getters.getPivotId(o.toString());if(!s)return gF;let c=this.getPivot(s);if(!c.isValid()||i===`PIVOT`&&!t.content.replaceAll(` `,``).toUpperCase().startsWith(`=PIVOT`))return gF;try{if(i===`PIVOT`){let t=Dl(a[2]),r=t===void 0?!0:L(t),i=Dl(a[3]),o=i===void 0?!0:L(i),s=c.getTableStructure().getPivotCells(r,o),l=e.col-n.col,u=e.row-n.row;return s[l][u]}let t=e.row-n.row,r=e.col-n.col;if(a=a.map(e=>k(e)?e[r][t]:e),i===`PIVOT.HEADER`&&a.at(-2)===`measure`)return{type:`MEASURE_HEADER`,domain:c.parseArgsToPivotDomain(a.slice(1,-2).map(e=>({value:e}))),measure:a.at(-1)?.toString()||``};if(i===`PIVOT.HEADER`)return{type:`HEADER`,domain:c.parseArgsToPivotDomain(a.slice(1).map(e=>({value:e})))};let[o,...s]=a.slice(1);return{type:`VALUE`,domain:c.parseArgsToPivotDomain(s.map(e=>({value:e}))),measure:o?.toString()||``}}catch{return gF}}generateNewCalculatedMeasureName(e){let t=e.map(e=>e.fieldName),n=1,r=T(`Calculated measure %s`,n);for(;t.includes(r);)n++,r=T(`Calculated measure %s`,n);return r}getPivot(e){if(!this.getters.isExistingPivot(e))throw Error(`pivot ${e} not found`);return this.pivots[e]}isPivotUnused(e){return this._getUnusedPivots().includes(e)}refreshPivot(e){this.getters.getPivot(e).init({reload:!0})}setupPivot(e,{recreate:t}={recreate:!1}){let n=y(this.getters.getPivotCoreDefinition(e));if(e in this.pivots)t&&this.pivots[e].onDefinitionChange(n);else{let t=kR(jF.get(n.type).ui);this.pivots[e]=new t(e,this.custom,{definition:n,getters:this.getters})}}_getUnusedPivots(){if(this.unusedPivots!==void 0)return this.unusedPivots;let e=new Set(this.getters.getPivotIds());for(let t of this.getters.getSheetIds())for(let n in this.getters.getCells(t)){let t=this.getters.getCellPosition(n),r=this.getPivotIdsFromPosition(t);for(let t of r)if(e.delete(t),!e.size)return this.unusedPivots=[],[]}for(let t of this.getters.getPivotIds()){let n=this.getters.getPivotCoreDefinition(t);for(let r of n.measures)if(r.computedBy){let{sheetId:n}=r.computedBy,i=this.getters.getMeasureCompiledFormula(t,r),a=this.getPivotIdsFromFormula(n,i);for(let t of a)if(e.delete(t),!e.size)return this.unusedPivots=[],[]}}return this.unusedPivots=[...e],this.unusedPivots}},NR=class{cells;getters;index=0;direction;constructor(e,t,n){this.cells=e,this.getters=t,this.direction=n}next(){let e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:n,tooltip:r}=eD.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:n,tooltip:r,origin:{col:e.data.col,row:e.data.row}}}},PR=class extends ${static layers=[`Autofill`];static getters=[`getAutofillTooltip`];autofillZone;steps;lastCellSelected={};direction;tooltip;allowDispatch(e){switch(e.type){case`AUTOFILL_SELECT`:let t=this.getters.getActiveSheetId();return this.lastCellSelected.col=e.col===-1?this.lastCellSelected.col:b(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=e.row===-1?this.lastCellSelected.row:b(e.row,0,this.getters.getNumberRows(t)),this.lastCellSelected.col!==void 0&&this.lastCellSelected.row!==void 0?`Success`:`InvalidAutofillSelection`}return`Success`}handle(e){switch(e.type){case`AUTOFILL`:this.autofill(!0);break;case`AUTOFILL_SELECT`:this.select(e.col,e.row);break;case`AUTOFILL_AUTO`:this.autofillAuto();break}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||this.direction===void 0){this.tooltip=void 0;return}let t=this.getters.getSelectedZone(),n=this.autofillZone,r=[];switch(this.direction){case`down`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.top;n<=t.bottom;n++)i.push(w(e,n));let a=this.createGenerator(i);for(let t=n.top;t<=n.bottom;t++)r.push(this.computeNewCell(a,e,t))}break;case`up`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.bottom;n>=t.top;n--)i.push(w(e,n));let a=this.createGenerator(i);for(let t=n.bottom;t>=n.top;t--)r.push(this.computeNewCell(a,e,t))}break;case`left`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.right;n>=t.left;n--)i.push(w(n,e));let a=this.createGenerator(i);for(let t=n.right;t>=n.left;t--)r.push(this.computeNewCell(a,t,e))}break;case`right`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.left;n<=t.right;n++)i.push(w(n,e));let a=this.createGenerator(i);for(let t=n.left;t<=n.right;t++)r.push(this.computeNewCell(a,t,e))}break}if(e){let e={},t={},n={},i=this.getters.getActiveSheetId();for(let a of r)this.collectBordersData(a,e),this.autofillMerge(i,a),this.autofillCell(i,a),this.collectConditionalFormatsData(i,a,t),this.collectDataValidationsData(i,a,n);this.autofillBorders(i,e),this.autofillConditionalFormats(i,t),this.autofillDataValidations(i,n),this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0}}collectBordersData(e,t){let n=JSON.stringify(e.border);n in t||(t[n]=[]),t[n].push(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=w(a,o);for(let e of s)e.id in n||(n[e.id]=[]),n[e.id].push(c)}collectDataValidationsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s={sheetId:e,col:r,row:i},c=this.getters.getValidationRuleForCell(s);c&&(c.id in n||(n[c.id]=[]),n[c.id].push(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:Fn(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($n),[]);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=Fn(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(fr(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=tD.getAll().sort((e,t)=>e.sequence-t.sequence).find(n=>n.condition(e,t));return n&&this.direction&&n.generateRule(e,t,this.direction)}createGenerator(e){let t=[],n=[],r=this.getters.getActiveSheetId();for(let t of e){let{col:e,row:i}=Pn(t),a=this.getters.getCell({sheetId:r,col:e,row:i});n.push({col:e,row:i,cell:a,sheetId:r})}let i=n.map(e=>e.cell);for(let e of n){let n={type:`COPY_MODIFIER`};e&&e.cell&&(n=this.getRule(e.cell,i)||n);let r=this.getters.getCellBorder(e)||void 0;t.push({data:{...e,border:r},rule:n})}return new NR(t,this.getters,this.direction)}saveZone(e,t,n,r){this.autofillZone={top:e,bottom:t,left:n,right:r}}getDirection(e,t){let n=this.getters.getSelectedZone(),r={up:{number:n.top-t,value:`up`},down:{number:t-n.bottom,value:`down`},left:{number:n.left-e,value:`left`},right:{number:e-n.right,value:`right`}};if(Object.values(r).map(e=>+(e.number>0)).reduce((e,t)=>e+t)===1)return Object.values(r).find(e=>+(e.number>0)).value;let i=r.up.number>0?`up`:`down`,a=r.left.number>0?`left`:`right`;return Math.abs(r[i].number)>=Math.abs(r[a].number)?r[i].value:r[a].value}autofillMerge(e,t){let{originCol:n,originRow:r,col:i,row:a}=t,o={sheetId:e,col:i,row:a},s={sheetId:e,col:n,row:r};if(this.getters.isInMerge(o)&&!this.getters.isInMerge(s)){let t=this.getters.getMerge(o);t&&this.dispatch(`REMOVE_MERGE`,{sheetId:e,target:[t]})}let c=this.getters.getMerge(s);c?.left===n&&c?.top===r&&this.dispatch(`ADD_MERGE`,{sheetId:e,target:[{top:a,bottom:a+c.bottom-c.top,left:i,right:i+c.right-c.left}]})}drawLayer(e){if(!this.autofillZone)return;let{ctx:t,thinLineWidth:n}=e,{x:r,y:i,width:a,height:o}=this.getters.getVisibleRect(this.autofillZone);a>0&&o>0&&(t.strokeStyle=`black`,t.lineWidth=n,t.setLineDash([3]),t.strokeRect(r,i,a,o),t.setLineDash([]))}},FR=class extends ${static getters=[`getAutomaticSums`];handle(e){switch(e.type){case`SUM_SELECTION`:let e=this.getters.getActiveSheetId(),{zones:t,anchor:n}=this.getters.getSelection();for(let r of t){let t=this.getAutomaticSums(e,r,n.cell);this.dispatchCellUpdates(e,t)}break}}getAutomaticSums(e,t,n){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,n):this.sumData(e,t)}sumData(e,t){let n=this.dimensionsToSum(e,t),r=this.sumDimensions(e,t,n).filter(({zone:t})=>!this.getters.isEmpty(e,t));return n.has(`ROW`)&&n.has(`COL`)&&r.push(this.sumTotal(t)),r}sumAdjacentData(e,t,n){let{col:r,row:i}=fr(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)||hr(sr(a,t))?[{position:{col:r,row:i},zone:a}]:this.sumDimensions(e,sr(a,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,n){let r=this.getters.getSheet(e),i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.findSuitableZoneToSum(r,i.col,i.row);if(a)return this.getters.expandZone(e,a)}findSuitableZoneToSum(e,t,n){let r=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:n-1}),i=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:n});if(this.isNumber(i)&&!this.isNumber(r))return this.findHorizontalZone(e,t,n);let a=this.findVerticalZone(e,t,n);if(this.isZoneValid(a))return a;let o=this.findHorizontalZone(e,t,n);if(this.isZoneValid(o))return o}findVerticalZone(e,t,n){let r={top:0,bottom:n-1,left:t,right:t},i=this.reduceZoneStart(e,r,r.bottom);return{...r,top:i}}findHorizontalZone(e,t,n){let r={top:n,bottom:n,left:0,right:t-1},i=this.reduceZoneStart(e,r,r.right);return{...r,left:i}}reduceZoneStart(e,t,n){let r=this.getters.getEvaluatedCellsInZone(e.id,t),i=x(n,-1,-1),a=Gt(i.filter(e=>r[e]&&!r[e].isAutoSummable)),o=ct(i.filter(e=>this.isNumber(r[e])))[0]||[];return Gt(o)<a?1/0:Kt(o)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===`number`&&!(e.format&&Ko(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 hr(t)?(n.add(mr(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)},vr(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)},vr(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`))}};wN.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],qR),wN.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],qR),wN.addTransformation(`ADD_COLUMNS_ROWS`,[`CREATE_CHART`,`UPDATE_CHART`],VR),wN.addTransformation(`REMOVE_COLUMNS_ROWS`,[`CREATE_CHART`,`UPDATE_CHART`],VR),wN.addTransformation(`DELETE_SHEET`,[`MOVE_RANGES`],zR),wN.addTransformation(`DELETE_FIGURE`,[`UPDATE_FIGURE`,`UPDATE_CHART`],BR),wN.addTransformation(`CREATE_SHEET`,[`CREATE_SHEET`],HR),wN.addTransformation(`ADD_MERGE`,[`ADD_MERGE`,`REMOVE_MERGE`],UR),wN.addTransformation(`ADD_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],WR),wN.addTransformation(`REMOVE_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],WR),wN.addTransformation(`ADD_COLUMNS_ROWS`,[`UPDATE_TABLE`],GR),wN.addTransformation(`REMOVE_COLUMNS_ROWS`,[`UPDATE_TABLE`],GR),wN.addTransformation(`REMOVE_TABLE_STYLE`,[`CREATE_TABLE`,`UPDATE_TABLE`],KR),wN.addTransformation(`ADD_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],JR),wN.addTransformation(`REMOVE_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],JR),wN.addTransformation(`REMOVE_PIVOT`,[`RENAME_PIVOT`,`DUPLICATE_PIVOT`,`INSERT_PIVOT`,`UPDATE_PIVOT`],RR),wN.addTransformation(`DELETE_SHEET`,[`ADD_PIVOT`,`UPDATE_PIVOT`],LR),wN.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],IR),wN.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],IR);function IR(e,t){if(e.pivot.type!==`SPREADSHEET`||e.pivot.dataSet?.sheetId!==t.sheetId)return e;let n=nd(e.pivot.dataSet.zone,t),r=n?{...e.pivot.dataSet,zone:n}:void 0;return{...e,pivot:{...e.pivot,dataSet:r}}}function LR(e,t){return e.pivot.type===`SPREADSHEET`&&e.pivot.dataSet?.sheetId===t.sheetId?{...e,pivot:{...e.pivot,dataSet:void 0}}:e}function RR(e,t){if(e.pivotId!==t.pivotId)return e}function zR(e,t){let n=t.sheetId;if(!(e.targetSheetId===n||e.sheetId===n))return e}function BR(e,t){if(e.id!==t.id)return e}function VR(e,t){return{...e,definition:yk(e.definition,t)}}function HR(e,t){return e.sheetId===t.sheetId&&(e={...e,sheetId:`${e.sheetId}~`}),e.name===t.name?{...e,name:e.name?.match(/\d+/)?e.name.replace(/\d+/,e=>(parseInt(e)+1).toString()):`${e.name}~`,position:e.position+1}:e}function UR(e,t){if(e.sheetId!==t.sheetId)return e;let n=[];for(let r of e.target)t.target.every(e=>!dr(r,e))&&n.push(r);if(n.length)return{...e,target:n}}function WR(e,t){if(e.sheetId!==t.sheetId||(e.type===`FREEZE_COLUMNS`?`COL`:`ROW`)!==t.dimension)return e;let n=e.quantity;if(t.type===`REMOVE_COLUMNS_ROWS`){let e=[...t.elements].sort((e,t)=>t-e);for(let t of e)n>t&&n--}if(t.type===`ADD_COLUMNS_ROWS`){let e=t.position===`before`?t.base-1:t.base;n=n>e?n+t.quantity:n}return n>0?{...e,quantity:n}:void 0}function GR(e,t){if(e.sheetId!==t.sheetId)return e;let n=nd(e.zone,t);if(!n)return;let r=e.newTableRange?rd(e.newTableRange,t):void 0;return{...e,newTableRange:r,zone:n}}function KR(e,t){return e.config?.styleId===t.tableStyleId?{...e,config:{...e.config,styleId:km.styleId}}:e}function qR(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n;if(t.type===`REMOVE_COLUMNS_ROWS`?n=$s(t.elements,[e.base])[0]:t.type===`ADD_COLUMNS_ROWS`&&(n=Qs(Ot(t.position,t.base),t.quantity,[e.base])[0]),n!==void 0)return{...e,base:n}}function JR(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n=x(e.start,e.end+1),r=[];if(t.type===`REMOVE_COLUMNS_ROWS`?r=$s(t.elements,n):t.type===`ADD_COLUMNS_ROWS`&&(r=Qs(Ot(t.position,t.base),t.quantity,n)),r.length!==0)return{...e,start:Math.min(...r),end:Math.max(...r)}}let YR=[{match:Ni,fn:$R},{match:Fi,fn:ez},{match:Ri,fn:tz},{match:Li,fn:iz},{match:Pi,fn:rz},{match:Ii,fn:nz}];function XR(e,t){let n=wN.getTransformation(e.type,t.type);return n?n(e,t):QR(e,t)}function ZR(e,t){let n=[...e],r=new Set(wN.getKeys());for(let e of t)r.has(e.type)&&(n=n.reduce((t,n)=>{let r=XR(n,e);return r&&t.push(r),t},[]));return n}function QR(e,t){for(let{match:n,fn:r}of YR)if(n(e)){let n=r(e,t);if(n===`SKIP_TRANSFORMATION`)continue;if(n===`IGNORE_COMMAND`)return;e=n}return e}function $R(e,t){if(!(`sheetId`in t))return e;let n=t.type===`DELETE_SHEET`&&t.sheetId;return e.sheetId===n?`IGNORE_COMMAND`:e.type===`CREATE_SHEET`||t.type===`CREATE_SHEET`||e.sheetId!==t.sheetId?e:`SKIP_TRANSFORMATION`}function ez(e,t){let n=$R(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=[];for(let n of e.target){let e=nd(n,t);e&&r.push(e)}return r.length?{...e,target:r}:`IGNORE_COMMAND`}function tz(e,t){let n=$R(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=nd(e.zone,t);return r?{...e,zone:r}:`IGNORE_COMMAND`}function nz(e,t){if(!(`sheetId`in t))return e;let n=e.ranges.map(e=>rd(e,t)).filter(S);return n.length?{...e,ranges:n}:`IGNORE_COMMAND`}function rz(e,t){let n=$R(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;if(t.type!==`ADD_COLUMNS_ROWS`&&t.type!==`REMOVE_COLUMNS_ROWS`)return`SKIP_TRANSFORMATION`;if(t.dimension!==e.dimension)return e;let r=[];return t.type===`REMOVE_COLUMNS_ROWS`?r=$s(t.elements,e.elements):t.type===`ADD_COLUMNS_ROWS`&&(r=Qs(Ot(t.position,t.base),t.quantity,e.elements)),r.length===0?`IGNORE_COMMAND`:{...e,elements:r}}function iz(e,t){let n=$R(e,t);return n===`SKIP_TRANSFORMATION`?t.type===`ADD_COLUMNS_ROWS`||t.type===`REMOVE_COLUMNS_ROWS`?az(e,t):t.type===`ADD_MERGE`?oz(e,t):`SKIP_TRANSFORMATION`:n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e}function az(e,t){let n=t.dimension===`COL`?`col`:`row`,r=e[n];if(t.type===`REMOVE_COLUMNS_ROWS`){let e=[...t.elements].sort((e,t)=>t-e);if(e.includes(r))return`IGNORE_COMMAND`;for(let t of e)r>=t&&r--}return t.type===`ADD_COLUMNS_ROWS`&&(r>t.base||r===t.base&&t.position===`before`)&&(r+=t.quantity),{...e,[n]:r}}function oz(e,t){for(let n of t.target)if(!(e.col===n.left&&e.row===n.top)&&fr(e.col,e.row,n))return`IGNORE_COMMAND`;return e}var sz=class{rootCommand;timestamp;id;clientId;_commands=[];_changes=[];constructor(e,t,n,r,i,a){this.rootCommand=r,this.timestamp=a,this.id=e,this.clientId=t,this._commands=[...n],this._changes=i?[...i]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}},cz=class extends Error{},lz=class extends id{revisions;transportService;serverRevisionId;clients={};clientId=`local`;debouncedMove;pendingMessages=[];waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;uuidGenerator=new Tc;lastLocalOperation;constructor(e,t,n=Ve){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=n,this.debouncedMove=Ct(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,n){if(!t.length||!n.length||!this.canApplyOptimisticUpdate())return;let r=new sz(this.uuidGenerator.uuidv4(),this.clientId,t,e,n,Date.now());this.revisions.append(r.id,r),e.type!==`REQUEST_REDO`&&(this.lastLocalOperation=r),this.trigger(`new-local-state-update`,{id:r.id}),this.sendUpdateMessage({type:`REMOTE_REVISION`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:r.id,clientId:r.clientId,commands:r.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_UNDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_REDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}move(e){this.debouncedMove(e)}join(e){e?(this.clients[e.id]=e,this.clientId=e.id):(this.clients.local={id:`local`,name:`local`},this.clientId=`local`),this.transportService.onNewMessage(this.clientId,this.onMessageReceived.bind(this))}loadInitialMessages(e){let t=performance.now(),n=e.reduce((e,t)=>e+(t.type===`REMOTE_REVISION`?t.commands.length:1),0);this.isReplayingInitialRevisions=!0;for(let t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1,console.debug(`Replayed`,n,`commands in`,performance.now()-t,`ms`)}async leave(e){e&&Object.keys(this.clients).length===1&&this.lastRevisionMessage&&this.lastRevisionMessage?.type!==`SNAPSHOT_CREATED`&&await this.snapshot(e()),delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.transportService.sendMessage({type:`CLIENT_LEFT`,clientId:this.clientId,version:1})}async snapshot(e){if(this.pendingMessages.length!==0)return;let t=this.uuidGenerator.uuidv4();await this.transportService.sendMessage({type:`SNAPSHOT`,nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getClient(){let e=this.clients[this.clientId];if(!e)throw new cz(`The client left the session`);return e}getConnectedClients(){return new Set(Object.values(this.clients).filter(S))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return this.pendingMessages.length===0}getLastLocalNonEmptyRevision(){return this.lastLocalOperation}_move(e){if(!this.clients[this.clientId])return;let t=this.clients[this.clientId]?.position;if(t?.col===e.col&&t.row===e.row&&t.sheetId===e.sheetId)return;let n=t?`CLIENT_MOVED`:`CLIENT_JOINED`,r=this.getClient();this.clients[this.clientId]={...r,position:e},this.transportService.sendMessage({type:n,version:1,client:{...r,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e)){if(this.isWrongServerRevisionId(e)){this.trigger(`unexpected-revision-id`);return}switch(e.type){case`CLIENT_MOVED`:this.onClientMoved(e);break;case`CLIENT_JOINED`:this.onClientJoined(e);break;case`CLIENT_LEFT`:this.onClientLeft(e);break;case`REVISION_REDONE`:this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger(`revision-redone`,{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case`REVISION_UNDONE`:this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger(`revision-undone`,{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case`REMOTE_REVISION`:let{clientId:t,commands:n,timestamp:r}=e,i=new sz(e.nextRevisionId,t,n,void 0,void 0,r);if(i.clientId!==this.clientId){this.revisions.insert(i.id,i,e.serverRevisionId);let t=this.pendingMessages.filter(e=>e.type===`REMOTE_REVISION`).map(e=>e.commands).flat();this.trigger(`remote-revision-received`,{commands:ZR(n,t)})}break;case`SNAPSHOT_CREATED`:{let t=new sz(e.nextRevisionId,`server`,[],void 0,void 0,Date.now());this.revisions.insert(t.id,t,e.serverRevisionId),this.dropPendingHistoryMessages(),this.trigger(`snapshot`),this.lastLocalOperation=void 0;break}}this.acknowledge(e),this.trigger(`collaborative-event-received`)}}onClientMoved(e){e.client.id!==this.clientId&&(this.clients[e.client.id]=e.client)}onClientJoined(e){if(e.client.id!==this.clientId){this.clients[e.client.id]=e.client;let t=this.clients[this.clientId];if(t){let{position:e}=t;e&&this.transportService.sendMessage({type:`CLIENT_MOVED`,version:1,client:{...t,position:e}})}}}onClientLeft(e){e.clientId!==this.clientId&&delete this.clients[e.clientId]}sendUpdateMessage(e){this.pendingMessages.push(e),!this.waitingAck&&this.sendPendingMessage()}sendPendingMessage(){let e=this.pendingMessages[0];if(e){if(e.type===`REMOTE_REVISION`){let t=this.revisions.get(e.nextRevisionId);t.commands.length===0&&(this.revisions.rebase(t.id),t=this.revisions.get(e.nextRevisionId)),e={...e,clientId:t.clientId,commands:t.commands}}if(this.isReplayingInitialRevisions)throw Error(`Trying to send a new revision while replaying initial revision. This can lead to endless dispatches every time the spreadsheet is open.
|
|
1898
1898
|
${JSON.stringify(e)}`);this.waitingAck=!0,this.transportService.sendMessage({...e,serverRevisionId:this.serverRevisionId})}}acknowledge(e){switch((e.type===`REVISION_UNDONE`||e.type===`REVISION_REDONE`)&&(this.waitingUndoRedoAck=!1),e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`SNAPSHOT_CREATED`:this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter(t=>t.nextRevisionId!==e.nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.lastRevisionMessage=e,this.sendPendingMessage();break;case`REVISION_UNDONE`:{this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter(t=>t.nextRevisionId!==e.nextRevisionId);let t=this.pendingMessages.findIndex(e=>e.type===`REMOTE_REVISION`);t!==-1&&this.revisions.rebase(this.pendingMessages[t].nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.sendPendingMessage();break}}}isAlreadyProcessed(e){if(e.type===`CLIENT_MOVED`&&e.client.id===this.clientId)return!0;switch(e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`REVISION_UNDONE`:case`SNAPSHOT_CREATED`:return this.processedRevisions.has(e.nextRevisionId);default:return!1}}isWrongServerRevisionId(e){switch(e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`REVISION_UNDONE`:case`SNAPSHOT_CREATED`:return e.serverRevisionId!==this.serverRevisionId;default:return!1}}dropPendingHistoryMessages(){this.waitingUndoRedoAck=!1,this.pendingMessages=this.pendingMessages.filter(({type:e})=>e!==`REVISION_REDONE`&&e!==`REVISION_UNDONE`)}};function uz(e){return e[Math.floor(Math.random()*e.length)]}let dz=[`#ff851b`,`#0074d9`,`#7fdbff`,`#b10dc9`,`#39cccc`,`#f012be`,`#3d9970`,`#111111`,`#ff4136`,`#aaaaaa`,`#85144b`,`#001f3f`];var fz=class extends ${static getters=[`getClientsToDisplay`,`getClient`,`getConnectedClients`,`isFullySynchronized`];static layers=[`Selection`];availableColors=new Set(dz);colors={};session;constructor(e){super(e),this.session=e.session}isPositionValid(e){return e.row<this.getters.getNumberRows(e.sheetId)&&e.col<this.getters.getNumberCols(e.sheetId)}chooseNewColor(){this.availableColors.size===0&&(this.availableColors=new Set(dz));let e=uz([...this.availableColors.values()]);return this.availableColors.delete(e),e}getClient(){return this.session.getClient()}getConnectedClients(){return this.session.getConnectedClients()}isFullySynchronized(){return this.session.isFullySynchronized()}getClientsToDisplay(){try{this.getters.getClient()}catch(e){if(e instanceof cz)return[];throw e}let e=this.getters.getActiveSheetId(),t=[];for(let n of this.getters.getConnectedClients())if(n.id!==this.getters.getClient().id&&n.position&&n.position.sheetId===e&&this.isPositionValid(n.position)){let e=n.position;this.colors[n.id]||(this.colors[n.id]=this.chooseNewColor());let r=this.colors[n.id];t.push({...n,position:e,color:r})}return t}drawLayer(e){if(this.getters.isDashboard())return;let{ctx:t,thinLineWidth:n}=e,r=this.getters.getActiveSheetId();for(let e of this.getClientsToDisplay()){let{row:i,col:a}=e.position,o=this.getters.expandZone(r,{top:i,bottom:i,left:a,right:a}),{x:s,y:c,width:l,height:u}=this.getters.getVisibleRect(o);if(l<=0||u<=0)continue;let d=e.color;t.fillStyle=`${d}10`,t.lineWidth=4*n,t.strokeStyle=d,t.globalCompositeOperation=`multiply`,t.fillRect(s,c,l,u),t.globalCompositeOperation=`source-over`,t.strokeRect(s,c,l,u),t.font=`bold ${Re+1}px ${ze}`}}},pz=class extends ${allowDispatch(e){switch(e.type){case`REMOVE_DUPLICATES`:return this.checkValidations(e,this.chainValidations(this.checkSingleRangeSelected,this.checkNoMergeInZone,this.checkRangeContainsValues,this.checkColumnsIncludedInZone),this.chainValidations(this.checkNoColumnProvided,this.checkColumnsAreUnique))}return`Success`}handle(e){switch(e.type){case`REMOVE_DUPLICATES`:this.removeDuplicates(e.columns,e.hasHeader);break;case`TRIM_WHITESPACE`:this.trimWhitespace();break}}removeDuplicates(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.getSelectedZone();t&&(r.top+=1);let i=this.getUniqueRowsIndexes(n,r.top,r.bottom,e),a=i.length;if(a===mr(r).numberOfRows){this.notifyRowsRemovedAndRemaining(0,a);return}let o=i.map(e=>({left:r.left,top:e,right:r.right,bottom:e})),s=new Gu(this.getters,this.dispatch),c=s.copy(Ec(n,o));if(!c)return;this.dispatch(`CLEAR_CELLS`,{target:[r],sheetId:n});let l={left:r.left,top:r.top,right:r.left,bottom:r.top};s.paste({zones:[l],sheetId:n},c,{isCutOperation:!1});let u={left:r.left,top:r.top-+!!t,right:r.right,bottom:r.top+a-1};this.selection.selectZone({cell:{col:u.left,row:u.top},zone:u});let d=r.bottom-r.top+1-a;this.notifyRowsRemovedAndRemaining(d,a)}getUniqueRowsIndexes(e,t,n,r){let i=new Map;for(let a of x(t,n+1)){let t=r.map(t=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:a}).value);Object.values(i).some(e=>C(e,t))||(i[a]=t)}return Object.keys(i).map(e=>parseInt(e))}notifyRowsRemovedAndRemaining(e,t){this.ui.notifyUI({type:`info`,text:T(`%s duplicate rows found and removed.
|
|
1899
1899
|
%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=Fn(this.getters.getSelectedZones()),t=this.getters.getActiveSheetId(),n=0;for(let{col:r,row:i}of e.map(vr).flat()){let e=this.getters.getCell({col:r,row:i,sheetId:t});if(!e)continue;let a=Ht(e.content);a!==e.content&&(n+=1,this.dispatch(`UPDATE_CELL`,{sheetId:t,col:r,row:i,content:a}))}let r=n?T(`Trimmed whitespace from %s cells.`,n):T(`No selected cells had whitespace trimmed.`);this.ui.notifyUI({type:`info`,text:r,sticky:!1})}},mz=class extends ${handle(e){switch(e.type){case`SET_DECIMAL`:this.setDecimal(e.sheetId,e.target,e.step);break;case`SET_FORMATTING_WITH_PIVOT`:this.setContextualFormat(e.sheetId,e.target,e.format);break}}setContextualFormat(e,t,n){let r=[],i={};for(let n of Fn(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=Fn(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:Fn(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 Fn(t))for(let t of vr(i)){let i=this.getCellNumberFormat({sheetId:e,...t});if(i!==void 0){let e=ls(i,n);r[e]=r[e]||[],r[e].push(t)}}for(let t in r){let n=Fn(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&&Ko(e.format)))return e.format||Xo(e.value)}}},hz=class extends ${static getters=[`getNextVisibleCellPosition`,`findVisibleHeader`,`findLastVisibleColRowIndex`,`findFirstVisibleColRowIndex`,`isRowHidden`,`isColHidden`,`isHeaderHidden`];isRowHidden(e,t){return this.getters.isRowHiddenByUser(e,t)||this.getters.isRowFiltered(e,t)}isColHidden(e,t){return this.getters.isColHiddenByUser(e,t)}isHeaderHidden(e,t,n){return t===`COL`?this.isColHidden(e,n):this.isRowHidden(e,n)}getNextVisibleCellPosition({sheetId:e,col:t,row:n}){return{sheetId:e,col:this.findVisibleHeader(e,`COL`,t,this.getters.getNumberCols(e)-1)||this.findVisibleHeader(e,`COL`,t,0)||0,row:this.findVisibleHeader(e,`ROW`,n,this.getters.getNumberRows(e)-1)||this.findVisibleHeader(e,`ROW`,n,0)||0}}findVisibleHeader(e,t,n,r){if(n<=r){for(let i=n;i<=r;i++)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}if(n>r){for(let i=n;i>=r;i--)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}}findLastVisibleColRowIndex(e,t,{last:n,first:r}){return x(n,r,-1).find(n=>!this.isHeaderHidden(e,t,n))||r}findFirstVisibleColRowIndex(e,t){let n=this.getters.getNumberHeaders(e,t);for(let r=0;r<n;r++)if(t===`COL`&&!this.isColHidden(e,r)||t===`ROW`&&!this.isRowHidden(e,r))return r}exportForExcel(e){for(let t of e.sheets)for(let[e,n]of Object.entries(t.rows))n.isHidden=this.isRowHidden(t.id,Number(e))}},gz=class extends ${static getters=[];allowDispatch(e){switch(e.type){case`DUPLICATE_PIVOT_IN_NEW_SHEET`:if(!this.getters.isExistingPivot(e.pivotId))return`PivotIdNotFound`;if(!this.getters.getPivot(e.pivotId).isValid())return`PivotInError`;break}return`Success`}handle(e){switch(e.type){case`INSERT_NEW_PIVOT`:this.insertNewPivot(e.pivotId,e.newSheetId);break;case`DUPLICATE_PIVOT_IN_NEW_SHEET`:this.duplicatePivotInNewSheet(e.pivotId,e.newPivotId,e.newSheetId);break;case`INSERT_PIVOT_WITH_TABLE`:this.insertPivotWithTable(e.sheetId,e.col,e.row,e.pivotId,e.table,e.pivotMode);break;case`SPLIT_PIVOT_FORMULA`:this.splitPivotFormula(e.sheetId,e.col,e.row,e.pivotId)}}insertNewPivot(e,t){Dr(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:T(`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:T(`Pivot #%(formulaId)s`,{formulaId:i}),position:r}),this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:n,sheetIdTo:t});let a=this.getters.getPivot(e);this.insertPivotWithTable(t,0,0,e,a.getTableStructure().export(),`dynamic`)}duplicatePivotInNewSheet(e,t,n){this.dispatch(`DUPLICATE_PIVOT`,{pivotId:e,newPivotId:t,duplicatedPivotName:T(`%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(T(`%(newPivotName)s (Pivot #%(formulaId)s)`,{newPivotName:o,formulaId:a})),position:i}).isSuccessful){this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:r,sheetIdTo:n});let i=this.getters.getPivot(e);this.insertPivotWithTable(n,0,0,t,i.getTableStructure().export(),`dynamic`)}}getPivotDuplicateSheetName(e){let t=1,n=this.getters.getSheetIds().map(e=>this.getters.getSheetName(e)),r=st(e),i=r;for(;n.includes(i);)i=`${r} (${t})`,t++;return i}insertPivotWithTable(e,t,n,r,i,a){let{cols:o,rows:s,measures:c,fieldsType:l}=i,u=new hF(o,s,c,l||{}),d=u.columns.length-1;this.resizeSheet(e,t,n,u);let f=this.getters.getPivotFormulaId(r),p;a===`dynamic`?(this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:n,content:`=PIVOT(${f})`}),p={left:t,right:t,top:n,bottom:n}):(this.dispatch(`INSERT_PIVOT`,{sheetId:e,col:t,row:n,pivotId:r,table:u.export()}),p={left:t,right:t+u.getNumberOfDataColumns(),top:n,bottom:n+d+u.rows.length}),this.dispatch(`CREATE_TABLE`,{tableType:a,sheetId:e,ranges:[this.getters.getRangeDataFromZone(e,p)],config:{...Ze,numberOfHeaders:d}})}resizeSheet(e,t,n,r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,quantity:s-l,position:`after`})}splitPivotFormula(e,t,n,r){let i=this.getters.getSpreadZone({sheetId:e,col:t,row:n});if(!i)return;let a=this.getters.getPivotFormulaId(r),o=new Map;for(let t=i.left;t<=i.right;t++)for(let n=i.top;n<=i.bottom;n++){let r={sheetId:e,col:t,row:n};o.set(r,this.getters.getPivotCellFromPosition(r))}for(let[e,t]of o)this.dispatch(`UPDATE_CELL`,{...e,content:Iu(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`})}}},_z=class extends ${allowDispatch(e){switch(e.type){case`SORT_CELLS`:if(!fr(e.col,e.row,e.zone))throw Error(T(`The anchor must be part of the provided zone`));return this.checkValidations(e,this.checkMerge,this.checkMergeSizes)}return`Success`}handle(e){switch(e.type){case`SORT_CELLS`:this.sortZone(e.sheetId,e,e.zone,e.sortDirection,e.sortOptions||{});break}}checkMerge({sheetId:e,zone:t}){return this.getters.doesIntersectMerge(e,t)&&vr(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=>dr(e,t)),r=mr(n[0]),[i,a]=[r.numberOfCols,r.numberOfRows];return n.every(e=>{let[t,n]=[e.right-e.left+1,e.bottom-e.top+1];return t===i&&n===a})?`Success`:`InvalidSortZone`}hasHeader(e,t){if(t[0].length===1)return!1;let n=t.map(t=>t.map(({col:t,row:n})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).type));return n[0][0]===`empty`&&(n=n.slice(1)),n.some(e=>e[0]===`empty`)?!1:!!n.some(e=>e[1]!==`empty`&&e[0]!==e[1])}sortZone(e,t,n,r,i){let[a,o]=this.mainCellsSteps(e,n),s=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,c=Object.assign({},n),l=this.mainCells(e,n);!i.sortHeaders&&this.hasHeader(e,l)&&(c.top+=o),l=this.mainCells(e,c);let u=l[s-c.left],d=mx(u.map(e=>this.getters.getEvaluatedCell(e)),r,!!i.emptyCellAsZero).map(e=>e.index),[f,p]=[l.length,l[0].length],m=[];for(let e=0;e<f;e++)for(let t=0;t<p;t++){let{col:n,row:r,sheetId:i}=l[e][d[t]],s=this.getters.getCell({sheetId:i,col:n,row:r}),u=c.left+e*a,f=c.top+t*o,p={sheetId:i,col:u,row:f,content:``};if(s){let e=s.content;if(s.isFormula){let t=this.getters.getCellPosition(s.id);e=this.getters.getTranslatedCellFormula(i,0,f-t.row,s.compiledFormula.tokens)}p.style=s.style,p.content=e,p.format=s.format}m.push(p)}m.forEach(e=>this.dispatch(`UPDATE_CELL`,e))}mainCellsSteps(e,t){let n=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[n?n.right-n.left+1:1,n?n.bottom-n.top+1:1]}mainCells(e,t){let[n,r]=this.mainCellsSteps(e,t),i=[],a=x(t.left,t.right+1,n),o=x(t.top,t.bottom+1,r);for(let t of a){let n=[];i.push(n);for(let r of o)n.push({sheetId:e,col:t,row:r})}return i}},vz=class extends ${static getters=[`shouldShowFormulas`];showFormulas=!1;handle(e){switch(e.type){case`SET_FORMULA_VISIBILITY`:this.showFormulas=e.show;break}}shouldShowFormulas(){return this.showFormulas}},yz=class extends ${static getters=[`doesCellHaveGridIcon`,`getCellWidth`,`getCellIconSrc`,`getTextWidth`,`getCellText`,`getCellMultiLineText`,`getContiguousZone`];ctx=document.createElement(`canvas`).getContext(`2d`);allowDispatch(e){return this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e)}handle(e){switch(e.type){case`AUTORESIZE_COLUMNS`:for(let t of e.cols){let n=this.getColMaxWidth(e.sheetId,t);n!==0&&this.dispatch(`RESIZE_COLUMNS_ROWS`,{elements:[t],dimension:`COL`,size:n,sheetId:e.sheetId})}break;case`AUTORESIZE_ROWS`:this.autoResizeRows(e.sheetId,e.rows);break}}getCellWidth(e){let t=this.getters.getCellComputedStyle(e),n=0,r=this.getters.getEvaluatedCell(e).formattedValue;if(r){let e=_c(this.ctx,r,t,void 0);n+=Math.max(...e.map(e=>cc(this.ctx,e,t)))}if(this.getters.getCellIconSrc(e)&&(n+=yc(t)),this.getters.doesCellHaveGridIcon(e)&&(n+=20),n===0)return 0;if(n+=8,t.wrapping===`wrap`){let t=this.getters.getColSize(e.sheetId,e.col);return Math.min(t,n)}return n}getCellIconSrc(e){let t=mf.getAll();for(let n of t){let t=n(this.getters,e);if(t)return t}}getTextWidth(e,t){return cc(this.ctx,e,t)}getCellText(e,t){let n=this.getters.getCell(e),r=this.getters.getLocale();if(t?.showFormula&&n?.isFormula)return sl(n.content,r);if(t?.showFormula&&!n?.content)return``;{let i=this.getters.getEvaluatedCell(e),a=t?.availableWidth?{availableWidth:t.availableWidth,measureText:e=>cc(this.ctx,e,n?.style||{})}:void 0;return B(i.value,{format:i.format,locale:r,formatWidth:a})}}getCellMultiLineText(e,t){let n=this.getters.getCellStyle(e),r=this.getters.getCellText(e,{showFormula:this.getters.shouldShowFormulas(),availableWidth:t.formatWidth});return _c(this.ctx,r,n,t.wrapText?t.maxWidth:void 0)}doesCellHaveGridIcon(e){let t=this.getters.isFilterHeader(e),n=!this.getters.isReadonly()&&this.getters.cellHasListDataValidationIcon(e);return t||n}getContiguousZone(e,t){let n=t=>{for(let n of x(t.left,t.right+1)){if(!this.isCellEmpty({sheetId:e,col:n,row:t.top-1}))return{...t,top:t.top-1};if(!this.isCellEmpty({sheetId:e,col:n,row:t.bottom+1}))return{...t,bottom:t.bottom+1}}for(let n of x(t.top,t.bottom+1)){if(!this.isCellEmpty({sheetId:e,col:t.left-1,row:n}))return{...t,left:t.left-1};if(!this.isCellEmpty({sheetId:e,col:t.right+1,row:n}))return{...t,right:t.right+1}}return t},r=!1,i=t;do{r=!1;let e=n(i);if(!ur(i,e)){r=!0,i=e;continue}}while(r);return i}isCellEmpty(e){let t=this.getters.getMainCellPosition(e);return this.getters.getEvaluatedCell(t).type===`empty`}getColMaxWidth(e,t){let n=vr(this.getters.getColsZone(e,t,t)).map(t=>this.getCellWidth({sheetId:e,...t}));return Math.max(0,Gt(n))}checkSheetExists(e){return`sheetId`in e&&this.getters.tryGetSheet(e.sheetId)===void 0?`InvalidSheetId`:`Success`}checkZonesAreInSheet(e){let t=`sheetId`in e?e.sheetId:this.getters.tryGetActiveSheetId();if(`ranges`in e&&e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId)))return`InvalidSheetId`;let n=this.getters.getCommandZones(e);return!t&&n.length>0?`NoActiveSheet`:t&&n.length>0?this.getters.checkZonesExistInSheet(t,n):`Success`}autoResizeRows(e,t){let n=[];for(let r of t){let t=0;for(let n of this.getters.getRowCells(e,r)){let r=this.getters.getCellById(n);if(!r)continue;let i=this.getters.getCellPosition(r.id),a=this.getters.getColSize(e,i.col);if(r.isFormula||this.getters.getArrayFormulaSpreadingOn(i)){let e=this.getters.getEvaluatedCell(i).formattedValue,n=ac(this.ctx,e,r?.style,a);n>t&&n>23&&(t=n)}else{let e=r.content,n=ac(this.ctx,e,r?.style,a);n>=t&&n>23&&(t=0)}}n.push(t||null)}let r=new Map(n.map(e=>[e,[]]));for(let e=0;e<n.length;e++)r.get(n[e])?.push(t[e]);for(let[t,n]of r)this.dispatch(`RESIZE_COLUMNS_ROWS`,{elements:n,dimension:`ROW`,size:t,sheetId:e})}},bz=class extends ${static getters=[`getCellTableStyle`,`getCellTableBorder`];tableStyles={};handle(e){if(zi.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tableStyles={};return}if(Sz(e)){`sheetId`in e?delete this.tableStyles[e.sheetId]:this.tableStyles={};return}}finalize(){for(let e of this.getters.getSheetIds()){this.tableStyles[e]||(this.tableStyles[e]={});for(let t of this.getters.getTables(e))this.tableStyles[e][t.id]||(this.tableStyles[e][t.id]=this.computeTableStyle(e,t))}}getCellTableStyle(e){let t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().styles[e.col]?.[e.row]}getCellTableBorder(e){let t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().borders[e.col]?.[e.row]}computeTableStyle(e,t){return Et(()=>{let{config:n,numberOfCols:r,numberOfRows:i}=this.getTableRuntimeConfig(e,t),a=XF(n,this.getters.getTableStyle(t.config.styleId),r,i),o=this.getTableMapping(e,t),s={borders:{},styles:{}};for(let e=0;e<r;e++){let t=o.colMapping[e];s.borders[t]={},s.styles[t]={};for(let n=0;n<i;n++){let r=o.rowMapping[n];s.borders[t][r]=a.borders[e][n],s.styles[t][r]=a.styles[e][n]}}return s})}getTableRuntimeConfig(e,t){let n=t.range.zone,r={...t.config},i=n.right-n.left+1,a=n.bottom-n.top+1;for(let i=n.top;i<=n.bottom;i++)this.getters.isRowHidden(e,i)&&(a--,i-n.top<t.config.numberOfHeaders&&(r.numberOfHeaders--,r.numberOfHeaders<0&&(r.numberOfHeaders=0)),i===n.bottom&&(r.totalRow=!1));for(let t=n.left;t<=n.right;t++)this.getters.isColHidden(e,t)&&(i--,t===n.left&&(r.firstColumn=!1),t===n.right&&(r.lastColumn=!1));return{config:r,numberOfCols:i,numberOfRows:a}}getTableMapping(e,t){let n={},r={},i=0,a=0,o=t.range.zone;for(let t=o.left;t<=o.right;t++)if(!this.getters.isColHidden(e,t)){n[i]=t,i++;for(let t=o.top;t<=o.bottom;t++)this.getters.isRowHidden(e,t)||(r[a]=t,a++)}return{colMapping:n,rowMapping:r}}};let xz=new Set([`HIDE_COLUMNS_ROWS`,`UNHIDE_COLUMNS_ROWS`,`UNFOLD_HEADER_GROUP`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`FOLD_ALL_HEADER_GROUPS`,`UNFOLD_ALL_HEADER_GROUPS`,`FOLD_HEADER_GROUPS_IN_ZONE`,`UNFOLD_HEADER_GROUPS_IN_ZONE`,`CREATE_TABLE`,`UPDATE_TABLE`,`UPDATE_FILTER`,`REMOVE_TABLE`,`RESIZE_TABLE`,`CREATE_TABLE_STYLE`,`REMOVE_TABLE_STYLE`]);function Sz(e){return xz.has(e.type)}var Cz=class extends ${static getters=[`getCellComputedBorder`,`getCellComputedStyle`];styles={};borders={};handle(e){if(zi.has(e.type)||e.type===`UPDATE_CELL`||e.type===`SET_FORMATTING`||e.type===`CLEAR_FORMATTING`||e.type===`EVALUATE_CELLS`){this.styles={},this.borders={};return}if(Sz(e)){`sheetId`in e?(delete this.styles[e.sheetId],delete this.borders[e.sheetId]):(this.styles={},this.borders={});return}if(Hi.has(e.type)){this.styles={};return}if(Ui.has(e.type)){this.borders={};return}}getCellComputedBorder(e){let{sheetId:t,row:n,col:r}=e;return this.borders[t]?.[n]?.[r]===void 0?(this.borders[t]||(this.borders[t]={}),this.borders[t][n]||(this.borders[t][n]={}),this.borders[t][n][r]||(this.borders[t][n][r]=this.computeCellBorder(e)),this.borders[t][n][r]):this.borders[t][n][r]}getCellComputedStyle(e){let{sheetId:t,row:n,col:r}=e;return this.styles[t]?.[n]?.[r]===void 0?(this.styles[t]||(this.styles[t]={}),this.styles[t][n]||(this.styles[t][n]={}),this.styles[t][n][r]||(this.styles[t][n][r]=this.computeCellStyle(e)),this.styles[t][n][r]):this.styles[t][n][r]}computeCellBorder(e){let t=this.getters.getCellBorder(e)||{},n={...jt(this.getters.getCellTableBorder(e)||{}),...jt(t)};return St(n)?null:n}computeCellStyle(e){let t=this.getters.getCell(e),n=this.getters.getCellConditionalFormatStyle(e),r={...jt(this.getters.getCellTableStyle(e)),...jt(t?.style),...jt(n)};return this.getters.getEvaluatedCell(e).link&&!r.textColor&&(r.textColor=le),r}},wz=class extends ${handle(e){switch(e.type){case`ADD_DATA_VALIDATION_RULE`:if(e.rule.criterion.type===`isBoolean`){let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e));for(let e of Js(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=(k(r)?r[0][0]:r)?.toString()}else n=t.content;(!n||!ut(n))&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}else n.type!==`boolean`&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}}}}};let Tz=[Ez,Dz,kz,Az];function Ez(e,t){return`sheetId`in t?{...y(t),sheetId:e.getActiveSheetId()}:t}function Dz(e,t){return!(`target`in t)||!Array.isArray(t.target)?t:{...y(t),target:e.getSelectedZones()}}function Oz(e,t){return`zone`in t?{...y(t),zone:e.getSelectedZone()}:t}function kz(e,t){if(!(`row`in t)||!(`col`in t))return t;let{col:n,row:r}=e.getActivePosition();return{...y(t),col:n,row:r}}function Az(e,t){return`ranges`in t?{...y(t),ranges:e.getSelectedZones().map(t=>e.getRangeDataFromZone(e.getActiveSheetId(),t))}:t}let jz=new Tc;function Mz(e,t){return{...Ez(e,t),id:jz.smallUuid()}}function Nz(e,t){return{...Ez(e,t),figureId:jz.smallUuid()}}function Pz(e,t){let n=Ez(e,t);return n.figure.id=jz.smallUuid(),n}function Fz(e,t){let n=y(t);n.sheetId=jz.smallUuid();let r=t.name||e.getSheet(e.getActiveSheetId()).name,i=r.match(/(.+?)\d*$/)?.[1]||r;return n.name=e.getNextSheetName(i),n}function Iz(e,t){let n=e.getActivePosition();return{...Ez(e,t),base:t.dimension===`COL`?n.col:n.row}}function Lz(e,t){let n=e.getSelectedZone();return{...Ez(e,t),elements:t.dimension===`COL`?x(n.left,n.right+1):x(n.top,n.bottom+1)}}function Rz(e,t){let n=e.getSelectedZone();return{...y(t),zone:n}}function zz(e,t){let n=y(t),{top:r,bottom:i,left:a,right:o}=e.getSelectedZone();return`cols`in n?n.cols=x(a,o+1):`rows`in n&&(n.rows=x(r,i+1)),n}function Bz(e,t){let n=e.getSelectedZone();return{...Ez(e,t),col:n.left,row:n.top,zone:n}}function Vz(e,t){return{type:`REPEAT_PASTE`,pasteOption:y(t.pasteOption),target:e.getSelectedZones()}}function Hz(e,t){let n=e.getSelectedZone();return{...Ez(e,t),start:t.dimension===`COL`?n.left:n.top,end:t.dimension===`COL`?n.right:n.bottom}}let Uz=new h;Uz.add(`UPDATE_CELL`,Gz),Uz.add(`CLEAR_CELL`,Gz),Uz.add(`CLEAR_CELLS`,Gz),Uz.add(`DELETE_CONTENT`,Gz),Uz.add(`ADD_MERGE`,Gz),Uz.add(`REMOVE_MERGE`,Gz),Uz.add(`SET_FORMATTING`,Gz),Uz.add(`CLEAR_FORMATTING`,Gz),Uz.add(`SET_BORDER`,Gz),Uz.add(`CREATE_TABLE`,Gz),Uz.add(`REMOVE_TABLE`,Gz),Uz.add(`HIDE_SHEET`,Gz),Uz.add(`ADD_COLUMNS_ROWS`,Iz),Uz.add(`REMOVE_COLUMNS_ROWS`,Lz),Uz.add(`HIDE_COLUMNS_ROWS`,Lz),Uz.add(`RESIZE_COLUMNS_ROWS`,Lz),Uz.add(`CREATE_SHEET`,Fz),Uz.add(`CREATE_FIGURE`,Pz),Uz.add(`CREATE_CHART`,Mz),Uz.add(`CREATE_IMAGE`,Nz),Uz.add(`GROUP_HEADERS`,Hz),Uz.add(`UNGROUP_HEADERS`,Hz),Uz.add(`UNGROUP_HEADERS`,Hz),Uz.add(`UNFOLD_HEADER_GROUPS_IN_ZONE`,Oz),Uz.add(`FOLD_HEADER_GROUPS_IN_ZONE`,Oz);let Wz=new h;Wz.add(`PASTE`,Vz),Wz.add(`INSERT_CELL`,Rz),Wz.add(`DELETE_CELL`,Rz),Wz.add(`AUTORESIZE_COLUMNS`,zz),Wz.add(`AUTORESIZE_ROWS`,zz),Wz.add(`SORT_CELLS`,Bz),Wz.add(`SUM_SELECTION`,Gz),Wz.add(`SET_DECIMAL`,Gz);function Gz(e,t){let n=y(t);for(let t of Tz)n=t(e,n);return n}function Kz(e,t){if(t&&Uz.contains(t.type))return Uz.get(t.type)(e,t)}function qz(e,t,n){if(Wz.contains(t.type))return Wz.get(t.type)(e,t,n)}function Jz(e){return!e||!e.rootCommand||typeof e.rootCommand!=`object`?!1:Ki(e.rootCommand)?Uz.contains(e.rootCommand.type):Wz.contains(e.rootCommand.type)}function Yz(e,t){if(!(!e.rootCommand||typeof e.rootCommand!=`object`))return Ki(e.rootCommand)?Kz(t,e.rootCommand):qz(t,e.rootCommand,e.commands)}var Xz=class extends ${static getters=[`canUndo`,`canRedo`];undoStack=[];redoStack=[];session;constructor(e){super(e),this.session=e.session,this.session.on(`new-local-state-update`,this,this.onNewLocalStateUpdate),this.session.on(`snapshot`,this,()=>{this.undoStack=[],this.redoStack=[]})}allowDispatch(e){switch(e.type){case`REQUEST_UNDO`:if(!this.canUndo())return`EmptyUndoStack`;break;case`REQUEST_REDO`:if(!this.canRedo())return`EmptyRedoStack`;break}return`Success`}handle(e){switch(e.type){case`REQUEST_UNDO`:case`REQUEST_REDO`:this.requestHistoryChange(e.type===`REQUEST_UNDO`?`UNDO`:`REDO`)}}finalize(){}requestHistoryChange(e){let t=e===`UNDO`?this.undoStack.pop():this.redoStack.pop();if(!t){let e=this.getPossibleRevisionToRepeat();if(!e)return;let t=Yz(e,this.getters);if(!t)return;if(!Array.isArray(t)){this.dispatch(t.type,t);return}for(let e of t)this.dispatch(e.type,e);return}e===`UNDO`?(this.session.undo(t),this.redoStack.push(t)):(this.session.redo(t),this.undoStack.push(t))}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0?!0:Jz(this.getPossibleRevisionToRepeat())}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}getPossibleRevisionToRepeat(){return this.session.getLastLocalNonEmptyRevision()}},Zz=class{trackedValues=new Set;domainToArray(e){return e.flatMap(e=>[e.field,F(e.value)])}isValuePresent(e,t){let n=JSON.stringify({measure:e,domain:this.domainToArray(t)});return this.trackedValues.has(n)}isHeaderPresent(e){let t=JSON.stringify({domain:this.domainToArray(e)});return this.trackedValues.has(t)}trackValue(e,t){let n=JSON.stringify({measure:e,domain:this.domainToArray(t)});this.trackedValues.add(n)}trackHeader(e){let t=JSON.stringify({domain:this.domainToArray(e)});this.trackedValues.add(t)}},Qz=class extends ${static getters=[`getPivotPresenceTracker`];trackPresencePivotId;tracker;handle(e){switch(e.type){case`PIVOT_START_PRESENCE_TRACKING`:this.tracker=new Zz,this.trackPresencePivotId=e.pivotId;break;case`PIVOT_STOP_PRESENCE_TRACKING`:this.trackPresencePivotId=void 0;break}}getPivotPresenceTracker(e){if(this.trackPresencePivotId===e){if(!this.tracker)throw Error(`Tracker not initialized`);return this.tracker}}},$z=class extends ${static getters=[`getAutomaticSeparator`];allowDispatch(e){switch(e.type){case`SPLIT_TEXT_INTO_COLUMNS`:return this.chainValidations(this.batchValidations(this.checkSingleColSelected,this.checkNonEmptySelector),this.batchValidations(this.checkNotOverwritingContent,this.checkSeparatorInSelection))(e)}return`Success`}handle(e){switch(e.type){case`SPLIT_TEXT_INTO_COLUMNS`:this.splitIntoColumns(e);break}}getAutomaticSeparator(){let e=this.getters.getSelectedCells();for(let t of e)if(t.value&&t.type===`text`){let e=this.getAutoSeparatorForString(t.value);if(e)return e}return` `}getAutoSeparatorForString(e){for(let t of[`
|
|
1900
1900
|
`,`;`,`,`,` `,`.`])if(e.includes(t))return t}splitIntoColumns({separator:e,addNewColumns:t}){let n=this.getters.getSelectedZone(),r=this.getters.getActiveSheetId(),i=this.getSplittedCols(n,e);t&&this.addColsToAvoidCollisions(n,i),this.removeMergesInSplitZone(n,i),this.addColumnsToNotOverflowSheet(n,i);for(let e=0;e<i.length;e++){let t=n.top+e,a=i[e],o=n.left,s=this.getters.getCell({sheetId:r,col:o,row:t});if(!(a.length===1&&a[0]===s?.content))for(let[e,n]of a.entries())this.dispatch(`UPDATE_CELL`,{sheetId:r,col:o+e,row:t,content:nl(n,this.getters.getLocale()),format:``,style:s?.style||null})}}getSplittedCols(e,t){if(!t)throw Error(`Separator cannot be empty`);let n=this.getters.getActiveSheetId(),r=[];for(let i of x(e.top,e.bottom+1)){let a=this.getters.getEvaluatedCell({sheetId:n,col:e.left,row:i}).formattedValue;r.push(this.splitAndRemoveTrailingEmpty(a,t))}return r}splitAndRemoveTrailingEmpty(e,t){let n=e.split(t);for(;n.length>1&&n[n.length-1]===``;)n.pop();return n}willSplittedColsOverwriteContent(e,t){let n=this.getters.getActiveSheetId();for(let r of x(e.top,e.bottom+1)){let i=t[r-e.top];for(let t=1;t<i.length;t++){let i=this.getters.getCell({sheetId:n,col:e.left+t,row:r});if(i&&i.content)return!0}}return!1}removeMergesInSplitZone(e,t){let n=this.getters.getActiveSheetId(),r=Math.max(...t.map(e=>e.length)),i={...e,right:e.left+r-1},a=this.getters.getMergesInZone(n,i);this.dispatch(`REMOVE_MERGE`,{sheetId:n,target:a})}addColsToAvoidCollisions(e,t){let n=this.getters.getActiveSheetId(),r=0;for(let i of x(e.top,e.bottom+1)){let a={sheetId:n,col:e.left,row:i},o=t[i-e.top],s=this.getColsToAddToAvoidCollision(a,o);r=Math.max(r,s)}r&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:e.left,sheetId:n,quantity:r,position:`after`})}getColsToAddToAvoidCollision(e,t){let n=t.length;for(let t=1;t<n;t++){let r=e.col+t,i=this.getters.getCell({...e,col:r});if(i&&i.content)return n-t}return 0}addColumnsToNotOverflowSheet(e,t){let n=this.getters.getActiveSheetId(),r=Math.max(...t.map(e=>e.length-1)),i=this.getters.getNumberCols(n)-1;e.left+r>i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:i,sheetId:n,quantity:e.left+r-i,position:`after`})}checkSingleColSelected(){return this.getters.isSingleColSelected()?`Success`:`MoreThanOneColumnSelected`}checkNonEmptySelector(e){return e.separator===``?`EmptySplitSeparator`:`Success`}checkNotOverwritingContent(e){if(e.addNewColumns||e.force)return`Success`;let t=this.getters.getSelectedZones()[0],n=this.getSplittedCols(t,e.separator);return this.willSplittedColsOverwriteContent(t,n)?`SplitWillOverwriteContent`:`Success`}checkSeparatorInSelection({separator:e}){let t=this.getters.getSelectedCells();for(let n of t)if(n.formattedValue.includes(e))return`Success`;return`NoSplitSeparatorInSelection`}},eB=class extends ${handle(e){switch(e.type){case`AUTOFILL_TABLE_COLUMN`:let t=this.getters.getCoreTable(e),n=this.getters.getCell(e);if(!t?.config.automaticAutofill||t.type===`dynamic`||!n?.isFormula)return;let{col:r,row:i}=e,a=KF(t.range.zone,t.config);if(a&&fr(r,i,a)){let t=e.autofillRowStart??a.top,n=e.autofillRowEnd??a.bottom,r={...a,top:t,bottom:n};this.autofillTableZone(e,r)}break}}autofillTableZone(e,t){if(t.top===t.bottom)return;let{col:n,row:r,sheetId:i}=e;for(let e=t.top;e<=t.bottom;e++)if(e!==r&&this.getters.getEvaluatedCell({col:n,row:e,sheetId:i}).type!==`empty`)return;let a={zone:this.getters.getSelectedZone(),cell:this.getters.getActivePosition()};this.selection.selectCell(n,r),this.dispatch(`AUTOFILL_SELECT`,{col:n,row:t.bottom}),this.dispatch(`AUTOFILL`),this.selection.selectCell(n,r),this.dispatch(`AUTOFILL_SELECT`,{col:n,row:t.top}),this.dispatch(`AUTOFILL`),this.selection.selectZone(a)}},tB=class extends ${allowDispatch(e){switch(e.type){case`RESIZE_TABLE`:let t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return`TableNotFound`;let n=t.range.zone,r=this.getters.getRangeFromRangeData(e.newTableRange).zone;return r.top!==n.top||r.left!==n.left?`InvalidTableResize`:this.canDispatch(`UPDATE_TABLE`,{...e}).reasons}return`Success`}handle(e){switch(e.type){case`RESIZE_TABLE`:{let t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(this.dispatch(`UPDATE_TABLE`,{...e}),!t||!t.config.automaticAutofill)return;let n=t.range.zone,r=this.getters.getRangeFromRangeData(e.newTableRange).zone;if(r.bottom>=n.bottom){for(let t=r.left;t<=r.right;t++){let i={col:t,row:n.bottom,sheetId:e.sheetId};this.getters.getCell(i)?.content.startsWith(`=`)&&this.dispatch(`AUTOFILL_TABLE_COLUMN`,{...i,autofillRowStart:n.bottom,autofillRowEnd:r.bottom})}break}}}}},nB=class extends ${static layers=[`Clipboard`];static getters=[`getClipboardContent`,`getClipboardId`,`getClipboardTextContent`,`isCutOperation`];status=`invisible`;originSheetId;copiedData;_isCutOperation=!1;clipboardId=new Tc().uuidv4();allowDispatch(e){switch(e.type){case`CUT`:let t=this.getters.getSelectedZones();return this.isCutAllowedOn(t);case`PASTE_FROM_OS_CLIPBOARD`:{let t=this.convertTextToClipboardData(e.clipboardContent.text??``),n=e.pasteOption;return this.isPasteAllowed(e.target,t,{pasteOption:n,isCutOperation:!1})}case`PASTE`:{if(!this.copiedData)return`EmptyClipboard`;let t=e.pasteOption;return this.isPasteAllowed(e.target,this.copiedData,{pasteOption:t,isCutOperation:this._isCutOperation})}case`COPY_PASTE_CELLS_ABOVE`:{let e=this.getters.getSelectedZones();if(e.length>1||e[0].top===0&&e[0].bottom===0)return`InvalidCopyPasteSelection`;break}case`COPY_PASTE_CELLS_ON_LEFT`:{let e=this.getters.getSelectedZones();if(e.length>1||e[0].left===0&&e[0].right===0)return`InvalidCopyPasteSelection`;break}case`INSERT_CELL`:{let{cut:t,paste:n}=this.getInsertCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);return this.isPasteAllowed(n,r,{isCutOperation:!0})}case`DELETE_CELL`:{let{cut:t,paste:n}=this.getDeleteCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);return this.isPasteAllowed(n,r,{isCutOperation:!0})}}return`Success`}handle(e){switch(e.type){case`COPY`:case`CUT`:let t=this.getters.getSelectedZones();this.status=`visible`,this.originSheetId=this.getters.getActiveSheetId(),this.copiedData=this.copy(t),this._isCutOperation=e.type===`CUT`;break;case`PASTE_FROM_OS_CLIPBOARD`:{this._isCutOperation=!1;let t=e.clipboardContent;t.data?.version!==22&&(t={...t},delete t.data),this.copiedData=t.data||this.convertTextToClipboardData(t.text??``);let n=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:n,selectTarget:!0,isCutOperation:!1}),this.status=`invisible`;break}case`PASTE`:{let t=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:t,selectTarget:!0,isCutOperation:this._isCutOperation}),this.status=`invisible`,this._isCutOperation&&=(this.copiedData=void 0,!1);break}case`COPY_PASTE_CELLS_ABOVE`:{let e=this.getters.getSelectedZone(),t=e.top!==e.bottom,n={...e,bottom:t?e.top:e.top-1,top:t?e.top:e.top-1};this.originSheetId=this.getters.getActiveSheetId();let r=this.copy([n]);this.paste([e],r,{isCutOperation:!1,selectTarget:!0})}break;case`COPY_PASTE_CELLS_ON_LEFT`:{let e=this.getters.getSelectedZone(),t=e.left!==e.right,n={...e,right:t?e.left:e.left-1,left:t?e.left:e.left-1};this.originSheetId=this.getters.getActiveSheetId();let r=this.copy([n]);this.paste([e],r,{isCutOperation:!1,selectTarget:!0})}break;case`CLEAN_CLIPBOARD_HIGHLIGHT`:this.status=`invisible`;break;case`DELETE_CELL`:{let{cut:t,paste:n}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!er(t[0])){this.dispatch(`CLEAR_CELLS`,{target:[e.zone],sheetId:this.getters.getActiveSheetId()});break}let r=this.copy(t,`shiftCells`);this.paste(n,r,{isCutOperation:!0});break}case`INSERT_CELL`:{let{cut:t,paste:n}=this.getInsertCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);this.paste(n,r,{isCutOperation:!0});break}case`ADD_COLUMNS_ROWS`:if(this.status=`invisible`,this._isCutOperation!==!0||e.sheetId!==this.copiedData?.sheetId)return;this.isColRowDirtyingClipboard(e.position===`before`?e.base:e.base+1,e.dimension)&&(this.copiedData=void 0);break;case`REMOVE_COLUMNS_ROWS`:if(this.status=`invisible`,this._isCutOperation!==!0||e.sheetId!==this.copiedData?.sheetId)return;for(let t of e.elements)if(this.isColRowDirtyingClipboard(t,e.dimension)){this.copiedData=void 0;break}this.status=`invisible`;break;case`REPEAT_PASTE`:this.paste(e.target,this.copiedData,{isCutOperation:!1,pasteOption:e.pasteOption,selectTarget:!0});break;case`DELETE_SHEET`:if(this._isCutOperation!==!0)return;this.originSheetId===e.sheetId&&(this.copiedData=void 0,this.status=`invisible`);break;default:Ki(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?td.figureHandlers:td.cellHandlers;return t.getKeys().map(e=>({handlerName:e,handler:new(t.get(e))(this.getters,this.dispatch)}))}isCutAllowedOn(e){let t=this.getClipboardData(e);for(let{handler:e}of this.selectClipboardHandlers(t)){let n=e.isCutAllowed(t);if(n!==`Success`)return n}return`Success`}isPasteAllowed(e,t,n){for(let{handler:r}of this.selectClipboardHandlers(t)){let i=r.isPasteAllowed(this.getters.getActiveSheetId(),e,t,{...n});if(i!==`Success`)return i}return`Success`}isColRowDirtyingClipboard(e,t){if(!this.copiedData||!this.copiedData.zones)return!1;let{zones:n}=this.copiedData;for(let r of n)if(t===`COL`&&e<=r.right||t===`ROW`&&e<=r.bottom)return!0;return!1}copy(e,t=`copyPaste`){let n={},r=this.getClipboardData(e);for(let{handlerName:e,handler:i}of this.selectClipboardHandlers(r)){let a=i.copy(r,t);n[e]=a;for(let e of[`sheetId`,`cells`,`zones`,`figureId`])a&&e in a&&(n[e]=a[e])}return n}paste(e,t,n){if(!t)return;let r=this.getters.getActiveSheetId(),i=this.selectClipboardHandlers(t),{target:a,zone:o,selectedZones:s}=Mc(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),jc(i,t,a,n),n?.selectTarget&&Nc(this.selection,e,s)}addMissingDimensions(e,t,n,r,i){let a=n+i-this.getters.getNumberRows(e);a>0&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:this.getters.getNumberRows(e)-1,sheetId:e,quantity:a,position:`after`});let o=t+r-this.getters.getNumberCols(e);o>0&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:this.getters.getNumberCols(e)-1,sheetId:e,quantity:o,position:`after`})}getClipboardTextContent(){return this.getPlainTextContent()}getClipboardId(){return this.clipboardId}getClipboardContent(){return{"text/plain":this.getPlainTextContent(),"text/html":this.getHTMLContent()}}getSheetData(){let e={version:22,clipboardId:this.clipboardId};return this.copiedData&&`figureId`in this.copiedData?e:{...e,...this.copiedData}}getPlainTextContent(){return this.copiedData?.cells&&this.copiedData.cells.map(e=>e.map(e=>this.getters.shouldShowFormulas()&&e?.tokens?.length?e?.content||``:e.evaluatedCell?.formattedValue||``).join(` `)).join(`
|
|
1901
|
-
`)||` `}getHTMLContent(){let e=``,t=this.copiedData?.cells;if(!t)e=` `;else if(t.length===1&&t[0].length===1)e=`${this.getters.getCellText(t[0][0].position)}`;else if(t[0][0]){let n=`<table border="1" style="border-collapse:collapse">`;for(let e of t){n+=`<tr>`;for(let t of e){if(!t)continue;let e=U(xf(this.getters.getCellComputedStyle(t.position))),r=this.getters.getCellText(t.position);n+=`<td style="${e}">`+th(r)+`</td>`}n+=`</tr>`}n+=`</table>`,e=n}else return``;return`<div data-osheet-clipboard='${th(JSON.stringify(this.getSheetData()))}'>${e}</div>`}isCutOperation(){return this._isCutOperation??!1}getDeleteCellsTargets(e,t){let n=this.getters.getActiveSheetId(),r;return r=t===`COL`?{...e,left:e.right+1,right:this.getters.getNumberCols(n)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(n)-1},{cut:[r],paste:[e]}}getInsertCellsTargets(e,t){let n=this.getters.getActiveSheetId(),r,i;return t===`COL`?(r={...e,right:this.getters.getNumberCols(n)-1},i={...e,left:e.right+1,right:e.right+1}):(r={...e,bottom:this.getters.getNumberRows(n)-1},i={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(n)-1}),{cut:[r],paste:[i]}}getClipboardData(e){let t=this.getters.getActiveSheetId(),n=this.getters.getSelectedFigureId();return n?{figureId:n,sheetId:t}:Ec(t,e)}drawLayer(e){if(this.status!==`visible`||!this.copiedData)return;let{sheetId:t,zones:n}=this.copiedData;if(t!==this.getters.getActiveSheetId()||!n||!n.length)return;let{ctx:r,thinLineWidth:i}=e;r.setLineDash([8,5]),r.strokeStyle=ae,r.lineWidth=3.3*i;for(let e of n){let{x:t,y:n,width:i,height:a}=this.getters.getVisibleRect(e);i>0&&a>0&&r.strokeRect(t,n,i,a)}}},rB=class extends ${static getters=[`getFilterHiddenValues`,`getFirstTableInSelection`,`isRowFiltered`,`isFilterActive`];filterValues={};hiddenRows={};isEvaluationDirty=!1;allowDispatch(e){switch(e.type){case`UPDATE_FILTER`:if(!this.getters.getFilterId(e))return`FilterNotFound`;break}return`Success`}handle(e){switch(e.type){case`UNDO`:case`REDO`:case`UPDATE_CELL`:case`EVALUATE_CELLS`:case`ACTIVATE_SHEET`:case`REMOVE_TABLE`:case`ADD_COLUMNS_ROWS`:case`REMOVE_COLUMNS_ROWS`:case`UPDATE_TABLE`:this.isEvaluationDirty=!0;break;case`START`:for(let e of this.getters.getSheetIds())this.filterValues[e]={};break;case`CREATE_SHEET`:this.filterValues[e.sheetId]={};break;case`HIDE_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`GROUP_HEADERS`:case`UNGROUP_HEADERS`:case`FOLD_HEADER_GROUP`:case`UNFOLD_HEADER_GROUP`:case`FOLD_ALL_HEADER_GROUPS`:case`UNFOLD_ALL_HEADER_GROUPS`:case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:this.updateHiddenRows(e.sheetId);break;case`UPDATE_FILTER`:this.updateFilter(e),this.updateHiddenRows(e.sheetId);break;case`DUPLICATE_SHEET`:this.filterValues[e.sheetIdTo]=y(this.filterValues[e.sheetId]);break}}finalize(){if(this.isEvaluationDirty){for(let e of this.getters.getSheetIds())this.updateHiddenRows(e);this.isEvaluationDirty=!1}}isRowFiltered(e,t){return!!this.hiddenRows[e]?.has(t)}getFilterHiddenValues(e){let t=this.getters.getFilterId(e),n=e.sheetId;return!t||!this.filterValues[n]?[]:this.filterValues[n][t]||[]}isFilterActive(e){let t=this.getters.getFilterId(e),n=e.sheetId;return!!(t&&this.filterValues[n]?.[t]?.length)}getFirstTableInSelection(){let e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZones();return this.getters.getTablesOverlappingZones(e,t)[0]}updateFilter({col:e,row:t,hiddenValues:n,sheetId:r}){let i=this.getters.getFilterId({sheetId:r,col:e,row:t});i&&(this.filterValues[r]||(this.filterValues[r]={}),this.filterValues[r][i]=n)}updateHiddenRows(e){let t=this.getters.getFilters(e).sort((e,t)=>e.rangeWithHeaders.zone.top-t.rangeWithHeaders.zone.top),n=new Set;for(let r of t){if(n.has(r.rangeWithHeaders.zone.top)||this.getters.isRowHiddenByUser(e,r.rangeWithHeaders.zone.top))continue;let t=this.filterValues[e]?.[r.id]?.map(bc),i=r.filteredRange?.zone;if(!t||!i)continue;let a=new Set(t);for(let t=i.top;t<=i.bottom;t++){let i=this.getCellValueAsString(e,r.col,t);a.has(i)&&n.add(t)}}this.hiddenRows[e]=n}getCellValueAsString(e,t,n){return this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).formattedValue.toLowerCase()}exportForExcel(e){for(let t of e.sheets){let e=t.id;for(let n of t.tables){let r=$n(n.range),i=[],a=[];for(let n of x(0,mr(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?vr(c.filteredRange.zone).map(t=>this.getters.getEvaluatedCell({sheetId:e,...t}).formattedValue):[];if(s.length){let e=l.filter(e=>e).filter(e=>!s.includes(e));i.push({colId:n,displayedValues:[...new Set(e)],displayBlanks:!s.includes(``)&&l.some(e=>!e)})}let u=this.getters.getEvaluatedCell(o).formattedValue,d=this.getUniqueColNameForExcel(n,u,a);a.push(d),t.cells[w(o.col,o.row)]={...t.cells[w(o.col,o.row)],content:d,value:d,isFormula:!1}}n.filters=i}}}getUniqueColNameForExcel(e,t,n){t||=`Column${e}`;let r=t,i=2;for(;n.includes(r);)r=t+String(i),i++;return r}},iB=class extends ${static layers=[`Selection`];static getters=[`getActiveSheet`,`getActiveSheetId`,`getActiveCell`,`getActiveCols`,`getActiveRows`,`getCurrentStyle`,`getSelectedZones`,`getSelectedZone`,`getSelectedCells`,`getSelectedFigureId`,`getSelection`,`getActivePosition`,`getSheetPosition`,`isSingleColSelected`,`getElementsFromSelection`,`tryGetActiveSheetId`,`isGridSelectionActive`];gridSelection={anchor:{cell:{col:0,row:0},zone:{top:0,left:0,bottom:0,right:0}},zones:[{top:0,left:0,bottom:0,right:0}]};selectedFigureId=null;sheetsData={};moveClient;activeSheet=null;constructor(e){super(e),this.moveClient=e.moveClient}allowDispatch(e){switch(e.type){case`ACTIVATE_SHEET`:try{if(!this.getters.getSheet(e.sheetIdTo).isVisible)return`SheetIsHidden`;break}catch{return`InvalidSheetId`}case`MOVE_COLUMNS_ROWS`:return this.isMoveElementAllowed(e)}return`Success`}handleEvent(e){let t=e.anchor,n=[];switch(e.mode){case`overrideSelection`:n=[t.zone];break;case`updateAnchor`:n=[...this.gridSelection.zones];let r=n.findIndex(t=>ur(t,e.previousAnchor.zone));r>=0&&(n[r]=t.zone);break;case`newAnchor`:n=[...this.gridSelection.zones,t.zone];break}this.setSelectionMixin(e.anchor,n),this.selection.resetDefaultAnchor(this,y(this.gridSelection.anchor));let{col:r,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:r,row:i}),this.selectedFigureId=null}handle(e){switch(e.type){case`ACTIVATE_SHEET`:this.selectedFigureId=null;break;case`DELETE_FIGURE`:this.selectedFigureId===e.id&&(this.selectedFigureId=null);break;case`DELETE_SHEET`:this.selectedFigureId&&this.getters.getFigure(e.sheetId,this.selectedFigureId)&&(this.selectedFigureId=null);break}switch(e.type){case`START`:let t=this.getters.getVisibleSheetIds()[0];this.activateSheet(t,t);let{col:n,row:r}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(n,r),this.selection.registerAsDefault(this,this.gridSelection.anchor,{handleEvent:this.handleEvent.bind(this)}),this.moveClient({sheetId:t,col:0,row:0});break;case`ACTIVATE_SHEET`:this.activateSheet(e.sheetIdFrom,e.sheetIdTo);break;case`REMOVE_COLUMNS_ROWS`:{let t=this.getters.getActiveSheetId();if(e.sheetId===t){e.dimension===`COL`?this.onColumnsRemoved(e):this.onRowsRemoved(e);let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:n,row:r})}break}case`ADD_COLUMNS_ROWS`:{let t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:n,row:r})}break}case`MOVE_COLUMNS_ROWS`:e.sheetId===this.getActiveSheetId()&&this.onMoveElements(e);break;case`SELECT_FIGURE`:this.selectedFigureId=e.id;break;case`ACTIVATE_NEXT_SHEET`:this.activateNextSheet(`right`);break;case`ACTIVATE_PREVIOUS_SHEET`:this.activateNextSheet(`left`);break;case`HIDE_SHEET`:e.sheetId===this.getActiveSheetId()&&this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:e.sheetId,sheetIdTo:this.getters.getVisibleSheetIds()[0]});break;case`UNDO`:case`REDO`:case`DELETE_SHEET`:let i=Object.keys(this.sheetsData).filter(e=>!this.getters.tryGetSheet(e));for(let e of i)delete this.sheetsData[e];for(let e in this.sheetsData){let t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:y(t)}}this.fallbackToVisibleSheet();let a=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map(e=>this.getters.expandZone(a,e)),this.gridSelection.anchor.zone=this.getters.expandZone(a,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones),this.selectedFigureId=null;break}}finalize(){this.fallbackToVisibleSheet(),this.selection.resetDefaultAnchor(this,y(this.gridSelection.anchor))}isGridSelectionActive(){return this.selection.isListening(this)}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}tryGetActiveSheetId(){return this.activeSheet?.id}getActiveCell(){return this.getters.getEvaluatedCell(this.getActivePosition())}getActiveCols(){let e=new Set;for(let t of this.gridSelection.zones)if(t.top===0&&t.bottom===this.getters.getNumberRows(this.getters.getActiveSheetId())-1)for(let n=t.left;n<=t.right;n++)e.add(n);return e}getActiveRows(){let e=new Set,t=this.getters.getActiveSheetId();for(let n of this.gridSelection.zones)if(n.left===0&&n.right===this.getters.getNumberCols(t)-1)for(let t=n.top;t<=n.bottom;t++)e.add(t);return e}getCurrentStyle(){let e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();return this.getters.getCellStyle({sheetId:t,col:e.left,row:e.top})}getSelectedZones(){return y(this.gridSelection.zones)}getSelectedZone(){return y(this.gridSelection.anchor.zone)}getSelection(){return y(this.gridSelection)}getSelectedCells(){let e=this.getters.getActiveSheetId(),t=[];for(let n of this.gridSelection.zones)t.push(...this.getters.getEvaluatedCellsInZone(e,n));return t}getSelectedFigureId(){return this.selectedFigureId}getActivePosition(){return this.getters.getMainCellPosition({sheetId:this.getActiveSheetId(),col:this.gridSelection.anchor.cell.col,row:this.gridSelection.anchor.cell.row})}getSheetPosition(e){if(e===this.getters.getActiveSheetId())return this.getActivePosition();{let t=this.sheetsData[e];return t?{sheetId:e,col:t.gridSelection.anchor.cell.col,row:t.gridSelection.anchor.cell.row}:this.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0})}}isSingleColSelected(){let e=this.getters.getSelectedZones();return!(e.length!==1||e[0].left!==e[0].right)}getElementsFromSelection(e){if(e===`COL`&&this.getters.getActiveCols().size===0||e===`ROW`&&this.getters.getActiveRows().size===0)return[];let t=this.getters.getSelectedZones(),n=[],r=e===`COL`?`left`:`top`,i=e===`COL`?`right`:`bottom`;for(let e of t){let t=Array.from({length:e[i]-e[r]+1},(t,n)=>e[r]+n);n=n.concat(t)}return[...new Set(n)].sort()}activateSheet(e,t){if(this.setActiveSheet(t),this.sheetsData[e]={gridSelection:y(this.gridSelection)},t in this.sheetsData)Object.assign(this,this.sheetsData[t]),this.selection.resetDefaultAnchor(this,y(this.gridSelection.anchor));else{let{col:e,row:n}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(e,n)}let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.activeSheet.id,col:n,row:r})}setSelectionMixin(e,t){let{anchor:n,zones:r}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=n,this.gridSelection.zones=xr(r)}selectCell(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.expandZone(n,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:r,cell:{col:e,row:t}},[r])}setActiveSheet(e){let t=this.getters.getSheet(e);this.activeSheet=t}activateNextSheet(e){let t=this.getters.getSheetIds(),n=(t.findIndex(e=>e===this.activeSheet.id)+(e===`left`?t.length-1:1))%t.length;this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[n]})}onColumnsRemoved(e){let{cell:t,zone:n}=this.gridSelection.anchor,r=ar(n,`left`,[...e.elements]),i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=ar(i,`left`,[...e.elements]);let a={cell:{col:i.left,row:i.top},zone:r},o=this.gridSelection.zones.map(t=>ar(t,`left`,[...e.elements]));this.setSelectionMixin(a,o)}onRowsRemoved(e){let{cell:t,zone:n}=this.gridSelection.anchor,r=ar(n,`top`,[...e.elements]),i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=ar(i,`top`,[...e.elements]);let a={cell:{col:i.left,row:i.top},zone:r},o=this.gridSelection.zones.map(t=>ar(t,`top`,[...e.elements]));this.setSelectionMixin(a,o)}onAddElements(e){let t=e.dimension===`COL`?`left`:`top`,n=ir(this.gridSelection.anchor.zone,t,e.base,e.position,e.quantity),r=this.gridSelection.zones.map(n=>ir(n,t,e.base,e.position,e.quantity)),i={cell:{col:n.left,row:n.top},zone:n};this.setSelectionMixin(i,r)}onMoveElements(e){let t=e.elements.length;this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,base:e.base,quantity:t,position:e.position});let n=e.dimension===`COL`,r=e.elements[0],i=e.elements[t-1],a=e.base<r,o=a&&n?t:0,s=a&&!n?t:0,c=a?e.elements.map(e=>e+t):e.elements,l=Object.fromEntries(c.map(t=>{let r=n?this.getters.getColSize(e.sheetId,t):this.getters.getUserRowSize(e.sheetId,t);return[t,n&&r===96||r===void 0?null:r]})),u=[{left:n?r+o:0,right:n?i+o:this.getters.getNumberCols(e.sheetId)-1,top:n?0:r+s,bottom:n?this.getters.getNumberRows(e.sheetId)-1:i+s}],d=this.getActiveSheetId(),f=a?e.base:e.base+1,p=[{left:n?f:0,right:n?f+t-1:this.getters.getNumberCols(e.sheetId)-1,top:n?0:f,bottom:n?this.getters.getNumberRows(e.sheetId)-1:f+t-1}];for(let e of td.cellHandlers.getAll()){let t=new e(this.getters,this.dispatch),n=t.copy(Ec(d,u),`shiftCells`);n&&t.paste({zones:p,sheetId:d},n,{isCutOperation:!0})}let m=p[0],h=m.left,g=m.top;this.setSelectionMixin({zone:m,cell:{col:h,row:g}},[m]);let _=a?e.base:e.base+1;for(let t of c)this.dispatch(`RESIZE_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,size:l[t],elements:[_]}),_+=1;this.dispatch(`REMOVE_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,elements:c})}isMoveElementAllowed(e){let t=e.dimension===`COL`,n=e.elements[0],r=e.elements[e.elements.length-1],i=e.sheetId,a=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;if(a(i,n-1,n)||a(i,r,r+1)||a(i,e.base-1,e.base))return`WillRemoveExistingMerge`;let o=[e.base,...e.elements],s=t?this.getters.getNumberCols(i):this.getters.getNumberRows(i);return o.some(e=>e<0||e>=s)?`InvalidHeaderIndex`:!t&&!this.isTableRowMoveAllowed(i,e.elements)?`CannotMoveTableHeader`:`Success`}isTableRowMoveAllowed(e,t){let n=this.getters.getCoreTables(e);if(n.length===0)return!0;let r=new Set(t);return n.every(({range:{zone:e},config:n})=>{let{top:i,bottom:a}=e;if(n.numberOfHeaders===0)return!0;let o=i+n.numberOfHeaders-1;return t.some(e=>e>=i&&e<=o)?x(i,a+1).every(e=>r.has(e)):!0})}fallbackToVisibleSheet(){if(!this.getters.tryGetSheet(this.getters.getActiveSheetId())){let e=this.getters.getVisibleSheetIds();if(this.activeSheet=this.getters.getSheet(e[0]),this.activeSheet.id in this.sheetsData){let{anchor:e}=this.clipSelection(this.activeSheet.id,this.sheetsData[this.activeSheet.id].gridSelection);this.selectCell(e.cell.col,e.cell.row)}else this.selectCell(0,0);let{col:t,row:n}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:n})}}clipSelection(e,t){let n=this.getters.getNumberCols(e)-1,r=this.getters.getNumberRows(e)-1,i=t.zones.map(e=>({left:b(e.left,0,n),right:b(e.right,0,n),top:b(e.top,0,r),bottom:b(e.bottom,0,r)})),a=b(t.anchor.cell.col,0,n),o=b(t.anchor.cell.row,0,r),s={left:b(t.anchor.zone.left,0,n),right:b(t.anchor.zone.right,0,n),top:b(t.anchor.zone.top,0,r),bottom:b(t.anchor.zone.bottom,0,r)};return{zones:i,anchor:{cell:{col:a,row:o},zone:s}}}drawLayer(e){if(this.getters.isDashboard())return;let{ctx:t,thinLineWidth:n}=e,r=this.getSelectedZones();t.fillStyle=`#f3f7fe`,t.fillStyle=r.length===1&&r[0].left===r[0].right&&r[0].top===r[0].bottom?`#f3f7fe`:`#e9f0ff`,t.strokeStyle=ae,t.lineWidth=1.5*n;for(let e of r){let{x:n,y:r,width:i,height:a}=this.getters.getVisibleRect(e);t.globalCompositeOperation=`multiply`,t.fillRect(n,r,i,a),t.globalCompositeOperation=`source-over`,t.strokeRect(n,r,i,a)}t.globalCompositeOperation=`source-over`;let i=this.getActivePosition();t.strokeStyle=ae,t.lineWidth=3*n;let a;a=this.getters.isInMerge(i)?this.getters.getMerge(i):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)}},aB=class{getters;sheetId;boundaries;top;bottom;left;right;offsetX;offsetY;offsetScrollbarX;offsetScrollbarY;canScrollVertically;canScrollHorizontally;viewportWidth;viewportHeight;offsetCorrectionX;offsetCorrectionY;constructor(e,t,n,r,i,a){if(this.getters=e,this.sheetId=t,this.boundaries=n,r.width<0||r.height<0)throw Error(`Viewport size cannot be negative`);this.viewportWidth=r.height&&r.width,this.viewportHeight=r.width&&r.height,this.top=n.top,this.bottom=n.bottom,this.left=n.left,this.right=n.right,this.offsetX=a.x,this.offsetY=a.y,this.offsetScrollbarX=a.x,this.offsetScrollbarY=a.y,this.canScrollVertically=i.canScrollVertically,this.canScrollHorizontally=i.canScrollHorizontally,this.offsetCorrectionX=this.getters.getColDimensions(this.sheetId,this.boundaries.left).start,this.offsetCorrectionY=this.getters.getRowDimensions(this.sheetId,this.boundaries.top).start,this.adjustViewportOffsetX(),this.adjustViewportOffsetY()}getMaxSize(){let e=this.getters.findLastVisibleColRowIndex(this.sheetId,`COL`,{first:this.boundaries.left,last:this.boundaries.right}),t=this.getters.findLastVisibleColRowIndex(this.sheetId,`ROW`,{first:this.boundaries.top,last:this.boundaries.bottom}),{end:n,size:r}=this.getters.getColDimensions(this.sheetId,e),{end:i,size:a}=this.getters.getRowDimensions(this.sheetId,t),o=this.searchHeaderIndex(`COL`,n-this.viewportWidth,0),s=this.getters.getColSize(this.sheetId,o),c=this.searchHeaderIndex(`ROW`,i-this.viewportHeight,0),l=this.getters.getRowSize(this.sheetId,c),u=n-this.offsetCorrectionX;this.canScrollHorizontally&&(u+=Math.max(96,Math.min(s,this.viewportWidth-r)),u=Math.max(u,this.viewportWidth));let d=i-this.offsetCorrectionY;return this.canScrollVertically&&(d+=Math.max(28,Math.min(l,this.viewportHeight-a)),d=Math.max(d,this.viewportHeight),i+46>d&&!this.getters.isReadonly()&&(d+=46)),{width:u,height:d}}getColIndex(e){return e<this.offsetCorrectionX||e>this.offsetCorrectionX+this.viewportWidth?-1:this.searchHeaderIndex(`COL`,e-this.offsetCorrectionX,this.left)}getRowIndex(e){return e<this.offsetCorrectionY||e>this.offsetCorrectionY+this.viewportHeight?-1:this.searchHeaderIndex(`ROW`,e-this.offsetCorrectionY,this.top)}adjustPosition(e){let t=this.sheetId,n=this.getters.getMainCellPosition({sheetId:t,...e}),{col:r,row:i}=this.getters.getNextVisibleCellPosition(n);fr(r,this.boundaries.top,this.boundaries)&&this.adjustPositionX(r),fr(this.boundaries.left,i,this.boundaries)&&this.adjustPositionY(i)}adjustPositionX(e){let t=this.sheetId,{end:n}=this.getters.getColDimensions(t,e);if(this.offsetX+this.offsetCorrectionX+this.viewportWidth<n){let n=this.getters.getNumberCols(t),r=e;for(;this.getters.isColHidden(t,r)&&r<n;)r++;let i=this.getters.getColDimensions(t,r).end,a=this.searchHeaderIndex(`COL`,i-this.viewportWidth-this.offsetCorrectionX,this.boundaries.left);this.offsetScrollbarX=this.getters.getColDimensions(t,a).end-this.offsetCorrectionX}else if(this.left>e){let n=e;for(;this.getters.isColHidden(t,n)&&n>0;)n--;this.offsetScrollbarX=this.getters.getColDimensions(t,n).start-this.offsetCorrectionX}this.adjustViewportZoneX()}adjustPositionY(e){let t=this.sheetId,{end:n}=this.getters.getRowDimensions(t,e);if(this.offsetY+this.viewportHeight+this.offsetCorrectionY<n){let n=this.getters.getNumberRows(t),r=e;for(;this.getters.isRowHidden(t,r)&&r<n;)r++;let i=this.getters.getRowDimensions(t,r).end,a=this.searchHeaderIndex(`ROW`,i-this.viewportHeight-this.offsetCorrectionY,this.boundaries.top);this.offsetScrollbarY=this.getters.getRowDimensions(t,a).end-this.offsetCorrectionY}else if(this.top>e){let n=e;for(;this.getters.isRowHidden(t,n)&&n>0;)n--;this.offsetScrollbarY=this.getters.getRowDimensions(t,n).start-this.offsetCorrectionY}this.adjustViewportZoneY()}willNewOffsetScrollViewport(e,t){return this.canScrollHorizontally&&this.offsetScrollbarX!==e||this.canScrollVertically&&this.offsetScrollbarY!==t}setViewportOffset(e,t){this.setViewportOffsetX(e),this.setViewportOffsetY(t)}adjustViewportZone(){this.adjustViewportZoneX(),this.adjustViewportZoneY()}getVisibleRect(e){let t=lr(e,this);if(t)return{x:this.getters.getColRowOffset(`COL`,this.left,t.left)+this.offsetCorrectionX,y:this.getters.getColRowOffset(`ROW`,this.top,t.top)+this.offsetCorrectionY,width:Math.min(this.getters.getColRowOffset(`COL`,t.left,t.right+1),this.viewportWidth),height:Math.min(this.getters.getColRowOffset(`ROW`,t.top,t.bottom+1),this.viewportHeight)}}getFullRect(e){if(lr(e,this))return{x:this.getters.getColRowOffset(`COL`,this.left,e.left)+this.offsetCorrectionX,y:this.getters.getColRowOffset(`ROW`,this.top,e.top)+this.offsetCorrectionY,width:this.getters.getColRowOffset(`COL`,e.left,e.right+1),height:this.getters.getColRowOffset(`ROW`,e.top,e.bottom+1)}}isVisible(e,t){return t<=this.bottom&&t>=this.top&&e>=this.left&&e<=this.right&&!this.getters.isColHidden(this.sheetId,e)&&!this.getters.isRowHidden(this.sheetId,t)}searchHeaderIndex(e,t,n=0){if(this.viewportWidth<=0||this.viewportHeight<=0)return-1;let r=this.sheetId,i=this.getters.getNumberHeaders(r,e),a=n,o=i;for(;a<=o&&a!==i&&o!==-1;){let i=Math.floor((a+o)/2),s=this.getters.getColRowOffset(e,n,i),c=this.getters.getHeaderSize(r,e,i);if(t>=s&&t<s+c)return i;t>=s+c?a=i+1:o=i-1}return-1}setViewportOffsetX(e){this.canScrollHorizontally&&(this.offsetScrollbarX=e,this.adjustViewportZoneX())}setViewportOffsetY(e){this.canScrollVertically&&(this.offsetScrollbarY=e,this.adjustViewportZoneY())}adjustViewportOffsetX(){if(this.canScrollHorizontally){let{width:e}=this.getMaxSize();this.viewportWidth+this.offsetScrollbarX>e&&(this.offsetScrollbarX=Math.max(0,e-this.viewportWidth))}this.adjustViewportZoneX()}adjustViewportOffsetY(){if(this.canScrollVertically){let{height:e}=this.getMaxSize();this.viewportHeight+this.offsetScrollbarY>e&&(this.offsetScrollbarY=Math.max(0,e-this.viewportHeight))}this.adjustViewportZoneY()}adjustViewportZoneX(){let e=this.sheetId;this.left=this.searchHeaderIndex(`COL`,this.offsetScrollbarX,this.boundaries.left),this.right=Math.min(this.boundaries.right,this.searchHeaderIndex(`COL`,this.viewportWidth,this.left)),this.viewportWidth&&(this.left===-1&&(this.left=this.boundaries.left),this.right===-1&&(this.right=this.boundaries.right),this.offsetX=this.getters.getColDimensions(e,this.left).start-this.getters.getColDimensions(e,this.boundaries.left).start)}adjustViewportZoneY(){let e=this.sheetId;this.top=this.searchHeaderIndex(`ROW`,this.offsetScrollbarY,this.boundaries.top),this.bottom=Math.min(this.boundaries.bottom,this.searchHeaderIndex(`ROW`,this.viewportHeight,this.top)),this.viewportHeight&&(this.top===-1&&(this.top=this.boundaries.top),this.bottom===-1&&(this.bottom=this.boundaries.bottom),this.offsetY=this.getters.getRowDimensions(e,this.top).start-this.getters.getRowDimensions(e,this.boundaries.top).start)}},oB=class extends ${static getters=[`getColIndex`,`getRowIndex`,`getActiveMainViewport`,`getSheetViewDimension`,`getSheetViewDimensionWithHeaders`,`getMainViewportRect`,`isVisibleInViewport`,`getEdgeScrollCol`,`getEdgeScrollRow`,`getVisibleFigures`,`getVisibleRect`,`getVisibleRectWithoutHeaders`,`getVisibleCellPositions`,`getColRowOffsetInViewport`,`getMainViewportCoordinates`,`getActiveSheetScrollInfo`,`getActiveSheetDOMScrollInfo`,`getSheetViewVisibleCols`,`getSheetViewVisibleRows`,`getFrozenSheetViewRatio`,`isPositionVisible`,`getColDimensionsInViewport`,`getRowDimensionsInViewport`,`getAllActiveViewportsZonesAndRect`,`getRect`];viewports={};sheetViewWidth=Je();sheetViewHeight=Je();gridOffsetX=0;gridOffsetY=0;sheetsWithDirtyViewports=new Set;shouldAdjustViewports=!1;allowDispatch(e){switch(e.type){case`SET_VIEWPORT_OFFSET`:return this.chainValidations(this.checkScrollingDirection,this.checkIfViewportsWillChange)(e);case`RESIZE_SHEETVIEW`:return this.chainValidations(this.checkValuesAreDifferent,this.checkPositiveDimension)(e);default:return`Success`}}handleEvent(e){let t=this.getters.getActiveSheetId();if(e.options.scrollIntoView){let{col:n,row:r}=Cr(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(zi.has(e.type))for(let e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);switch(e.type){case`START`:this.selection.observe(this,{handleEvent:this.handleEvent.bind(this)}),this.resetViewports(this.getters.getActiveSheetId());break;case`UNDO`:case`REDO`:this.cleanViewports();for(let e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);this.shouldAdjustViewports=!0;break;case`RESIZE_SHEETVIEW`:this.resizeSheetView(e.height,e.width,e.gridOffsetX,e.gridOffsetY);break;case`SET_VIEWPORT_OFFSET`:this.setSheetViewOffset(e.offsetX,e.offsetY);break;case`SHIFT_VIEWPORT_DOWN`:let t=this.getters.getActiveSheetId(),{top:n,viewportHeight:r,offsetCorrectionY:i}=this.getMainInternalViewport(t),a=this.getters.getRowDimensions(t,n);this.shiftVertically(a.start+r-i);break;case`SHIFT_VIEWPORT_UP`:{let e=this.getters.getActiveSheetId(),{top:t,viewportHeight:n,offsetCorrectionY:r}=this.getMainInternalViewport(e),i=this.getters.getRowDimensions(e,t);this.shiftVertically(i.end-r-n);break}case`REMOVE_TABLE`:case`UPDATE_TABLE`:case`UPDATE_FILTER`:case`UNFREEZE_ROWS`:case`UNFREEZE_COLUMNS`:case`FREEZE_COLUMNS`:case`FREEZE_ROWS`:case`UNFREEZE_COLUMNS_ROWS`:case`REMOVE_COLUMNS_ROWS`:case`RESIZE_COLUMNS_ROWS`:case`HIDE_COLUMNS_ROWS`:case`ADD_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`UNGROUP_HEADERS`:case`GROUP_HEADERS`:case`FOLD_HEADER_GROUP`:case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_ALL_HEADER_GROUPS`:case`FOLD_ALL_HEADER_GROUPS`:this.sheetsWithDirtyViewports.add(e.sheetId);break;case`UPDATE_CELL`:for(let e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);break;case`DELETE_SHEET`:this.cleanViewports(),this.sheetsWithDirtyViewports.delete(e.sheetId);break;case`ACTIVATE_SHEET`:this.sheetsWithDirtyViewports.add(e.sheetIdTo);break;case`DELETE_SHEET`:this.sheetsWithDirtyViewports.delete(e.sheetId);break;case`SCROLL_TO_CELL`:this.refreshViewport(this.getters.getActiveSheetId(),{col:e.col,row:e.row});break}}finalize(){for(let e of this.sheetsWithDirtyViewports)if(this.resetViewports(e),this.shouldAdjustViewports){let t=this.getters.getSheetPosition(e);this.getSubViewports(e).forEach(e=>{e.adjustPosition(t)})}this.sheetsWithDirtyViewports=new Set,this.shouldAdjustViewports=!1,this.setViewports()}setViewports(){let e=this.getters.getSheetIds();for(let t of e)this.viewports[t]?.bottomRight||this.resetViewports(t)}getColIndex(e){let t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map(t=>t.getColIndex(e)))}getRowIndex(e){let t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map(t=>t.getRowIndex(e)))}getSheetViewDimensionWithHeaders(){return{width:this.sheetViewWidth+this.gridOffsetX,height:this.sheetViewHeight+this.gridOffsetY}}getSheetViewDimension(){return{width:this.sheetViewWidth,height:this.sheetViewHeight}}getActiveMainViewport(){let e=this.getters.getActiveSheetId();return this.getMainViewport(e)}getActiveSheetScrollInfo(){let e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetX,scrollY:t.offsetY}}getActiveSheetDOMScrollInfo(){let e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetScrollbarX,scrollY:t.offsetScrollbarY}}getSheetViewVisibleCols(){let e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map(e=>x(e.left,e.right+1)).flat())].filter(t=>t>=0&&!this.getters.isHeaderHidden(e,`COL`,t))}getSheetViewVisibleRows(){let e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map(e=>x(e.top,e.bottom+1)).flat())].filter(t=>t>=0&&!this.getters.isHeaderHidden(e,`ROW`,t))}getVisibleCellPositions(){let e=this.getSheetViewVisibleCols(),t=this.getSheetViewVisibleRows(),n=this.getters.getActiveSheetId(),r=[];for(let i of e)for(let e of t){let t={sheetId:n,col:i,row:e},a=this.getters.getMainCellPosition(t);a.row!==e||a.col!==i||r.push(t)}return r}getMainViewportRect(){let e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e),{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(e),{width:i,height:a}=t.getMaxSize();return{x:this.getters.getColDimensions(e,n).start,y:this.getters.getRowDimensions(e,r).start,width:i,height:a}}getMaximumSheetOffset(){let e=this.getters.getActiveSheetId(),{width:t,height:n}=this.getMainViewportRect(),r=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-r.viewportWidth+1),maxOffsetY:Math.max(0,n-r.viewportHeight+1)}}getColRowOffsetInViewport(e,t,n){if(n<t)return-this.getColRowOffsetInViewport(e,n,t);let r=this.getters.getActiveSheetId(),i=e===`COL`?this.getters.getSheetViewVisibleCols():this.getters.getSheetViewVisibleRows(),a=i.findIndex(e=>t>=e),o=i.findIndex(e=>n<=e);o=o===-1?i.length:o;let s=i.slice(a,o),c=0;for(let t of s)c+=this.getters.getHeaderSize(r,e,t);return c}isVisibleInViewport({sheetId:e,col:t,row:n}){return this.getSubViewports(e).some(e=>e.isVisible(t,n))}getEdgeScrollCol(e,t,n){let r=!1,i=0,a=0,{xSplit:o}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{width:s}=this.getSheetViewDimension(),{x:c}=this.getMainViewportCoordinates(),l=this.getActiveSheetScrollInfo().scrollX;return e>s?(r=!0,a=ks(e-s),i=1):e<c&&n>=c&&l>0?(r=!0,a=ks(c-e),i=-1):o&&t<c&&e>c&&(r=!0,a=ks(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=ks(e-s),i=1):e<c&&n>=c&&l>0?(r=!0,a=ks(c-e),i=-1):o&&t<c&&e>c&&(r=!0,a=ks(e),i=`reset`),{canEdgeScroll:r,direction:i,delay:a}}getVisibleRect(e){let t=this.getVisibleRectWithoutHeaders(e);return{...t,x:t.x+this.gridOffsetX,y:t.y+this.gridOffsetY}}getVisibleRectWithoutHeaders(e){let t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,t=>t.getVisibleRect(e))}getRect(e){let t=this.getters.getActiveSheetId(),n=this.mapViewportsToRect(t,t=>t.getFullRect(e));return{...n,x:n.x+this.gridOffsetX,y:n.y+this.gridOffsetY}}getMainViewportCoordinates(){let e=this.getters.getActiveSheetId(),{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,n).start}}getColDimensionsInViewport(e,t){let n=Kt(this.getters.getSheetViewVisibleCols()),r=this.getters.getColRowOffsetInViewport(`COL`,n,t),i=this.getters.getColSize(e,t);return{start:r,size:i,end:r+(this.getters.isColHidden(e,t)?0:i)}}getRowDimensionsInViewport(e,t){let n=Kt(this.getters.getSheetViewVisibleRows()),r=this.getters.getColRowOffsetInViewport(`ROW`,n,t),i=this.getters.getRowSize(e,t);return{start:r,size:i,end:r+(this.getters.isRowHidden(e,t)?0:i)}}getAllActiveViewportsZonesAndRect(){let e=this.getters.getActiveSheetId();return this.getSubViewports(e).map(e=>({zone:e,rect:{x:e.offsetCorrectionX+this.gridOffsetX,y:e.offsetCorrectionY+this.gridOffsetY,...e.getMaxSize()}}))}ensureMainViewportExist(e){this.viewports[e]||this.resetViewports(e)}getSubViewports(e){return this.ensureMainViewportExist(e),Object.values(this.viewports[e]).filter(S)}checkPositiveDimension(e){return e.width<0||e.height<0?`InvalidViewportSize`:`Success`}checkValuesAreDifferent(e){let{height:t,width:n}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===n&&e.height===t?`ValuesNotChanged`:`Success`}checkScrollingDirection({offsetX:e,offsetY:t}){let n=this.getMainInternalViewport(this.getters.getActiveSheetId());return!n.canScrollHorizontally&&e>0||!n.canScrollVertically&&t>0?`InvalidScrollingDirection`:`Success`}checkIfViewportsWillChange({offsetX:e,offsetY:t}){let n=this.getters.getActiveSheetId(),{maxOffsetX:r,maxOffsetY:i}=this.getMaximumSheetOffset();return this.getSubViewports(n).some(n=>n.willNewOffsetScrollViewport(b(e,0,r),b(t,0,i)))?`Success`:`ViewportScrollLimitsReached`}getMainViewport(e){let t=this.getMainInternalViewport(e);return{top:t.top,left:t.left,bottom:t.bottom,right:t.right}}getMainInternalViewport(e){return this.ensureMainViewportExist(e),this.viewports[e].bottomRight}cleanViewports(){let e={};for(let t of this.getters.getSheetIds())e[t]=this.viewports[t];this.viewports=e}resizeSheetView(e,t,n=0,r=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=n,this.gridOffsetY=r,this.recomputeViewports()}recomputeViewports(){for(let e of this.getters.getSheetIds())this.resetViewports(e)}setSheetViewOffset(e,t){let n=this.getters.getActiveSheetId(),{maxOffsetX:r,maxOffsetY:i}=this.getMaximumSheetOffset();this.getSubViewports(n).forEach(n=>n.setViewportOffset(b(e,0,r),b(t,0,i)))}getViewportOffset(e){return{x:this.viewports[e]?.bottomRight.offsetScrollbarX||0,y:this.viewports[e]?.bottomRight.offsetScrollbarY||0}}resetViewports(e){if(!this.getters.tryGetSheet(e))return;let{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e),r=this.getters.getNumberCols(e),i=this.getters.getNumberRows(e),a=Math.min(this.getters.getColRowOffset(`COL`,0,t,e),this.sheetViewWidth),o=Math.min(this.getters.getColRowOffset(`ROW`,0,n,e),this.sheetViewHeight),s=Math.max(this.sheetViewWidth-a,0),c=Math.max(this.sheetViewHeight-o,0),{xRatio:l,yRatio:u}=this.getFrozenSheetViewRatio(e),d=l<1,f=u<1,p=this.getViewportOffset(e),m={topLeft:n&&t&&new aB(this.getters,e,{left:0,right:t-1,top:0,bottom:n-1},{width:a,height:o},{canScrollHorizontally:!1,canScrollVertically:!1},{x:0,y:0})||void 0,topRight:n&&new aB(this.getters,e,{left:t,right:r-1,top:0,bottom:n-1},{width:s,height:o},{canScrollHorizontally:d,canScrollVertically:!1},{x:d?p.x:0,y:0})||void 0,bottomLeft:t&&new aB(this.getters,e,{left:0,right:t-1,top:n,bottom:i-1},{width:a,height:c},{canScrollHorizontally:!1,canScrollVertically:f},{x:0,y:f?p.y:0})||void 0,bottomRight:new aB(this.getters,e,{left:t,right:r-1,top:n,bottom:i-1},{width:s,height:c},{canScrollHorizontally:d,canScrollVertically:f},{x:d?p.x:0,y:f?p.y:0})};this.viewports[e]=m}refreshViewport(e,t){this.getSubViewports(e).forEach(e=>{e.adjustViewportZone(),e.adjustPosition(t)})}shiftVertically(e){let t=this.getters.getActiveSheetId(),{top:n}=this.getMainInternalViewport(t),{scrollX:r}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(r,e);let{anchor:i}=this.getters.getSelection();if(i.cell.row>=this.getters.getPaneDivisions(t).ySplit){let e=this.getMainInternalViewport(t).top-n;this.selection.selectCell(i.cell.col,i.cell.row+e)}}getVisibleFigures(){let e=this.getters.getActiveSheetId(),t=[],n=this.getters.getFigures(e),{scrollX:r,scrollY:i}=this.getActiveSheetScrollInfo(),{x:a,y:o}=this.getters.getMainViewportCoordinates(),{width:s,height:c}=this.getters.getSheetViewDimensionWithHeaders();for(let e of n)e.x>=a&&(e.x+e.width<=a+r||e.x>=s+r+a)||e.y>=o&&(e.y+e.height<=o+i||e.y>=c+i+o)||t.push(e);return t}isPositionVisible(e){let{scrollX:t,scrollY:n}=this.getters.getActiveSheetScrollInfo(),{x:r,y:i}=this.getters.getMainViewportCoordinates(),{width:a,height:o}=this.getters.getSheetViewDimension();return!(e.x>=r&&(e.x<r+t||e.x>a+t+r)||e.y>=i&&(e.y<i+n||e.y>o+n+i))}getFrozenSheetViewRatio(e){let{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e),r=this.getters.getColDimensions(e,t).start,i=this.getters.getRowDimensions(e,n).start,a=this.sheetViewWidth+this.gridOffsetX,o=this.sheetViewHeight+this.gridOffsetY;return{xRatio:r/a,yRatio:i/o}}mapViewportsToRect(e,t){let n=1/0,r=1/0,i=0,a=0,o=!1;for(let s of this.getSubViewports(e)){let e=t(s);e&&(o=!0,n=Math.min(n,e.x),r=Math.min(r,e.y),i=Math.max(i,e.x+e.width),a=Math.max(a,e.y+e.height))}return o?{x:n,y:r,width:i-n,height:a-r}:{x:0,y:0,width:0,height:0}}},sB=class extends ${static getters=[`getColDimensions`,`getRowDimensions`,`getColRowOffset`];headerPositions={};isDirty=!0;handle(e){switch(zi.has(e.type)&&(this.headerPositions={},this.isDirty=!0),e.type){case`START`:for(let e of this.getters.getSheetIds())this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e);break;case`UPDATE_CELL`:this.headerPositions={},this.isDirty=!0;break;case`UPDATE_FILTER`:case`UPDATE_TABLE`:case`REMOVE_TABLE`:this.headerPositions={},this.isDirty=!0;break;case`REMOVE_COLUMNS_ROWS`:case`RESIZE_COLUMNS_ROWS`:case`HIDE_COLUMNS_ROWS`:case`ADD_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`FOLD_HEADER_GROUP`:case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_ALL_HEADER_GROUPS`:case`FOLD_ALL_HEADER_GROUPS`:case`UNGROUP_HEADERS`:case`GROUP_HEADERS`:case`CREATE_SHEET`:this.getters.tryGetSheet(e.sheetId)&&(this.headerPositions[e.sheetId]=this.computeHeaderPositionsOfSheet(e.sheetId));break;case`DUPLICATE_SHEET`:this.headerPositions[e.sheetIdTo]=y(this.headerPositions[e.sheetId]);break}}finalize(){for(let e of this.getters.getSheetIds())(this.isDirty||!this.headerPositions[e])&&(this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e));this.isDirty=!1}getColDimensions(e,t){let n=this.headerPositions[e].COL[t],r=this.getters.getColSize(e,t);return{start:n,size:r,end:n+(this.getters.isColHidden(e,t)?0:r)}}getRowDimensions(e,t){let n=this.headerPositions[e].ROW[t],r=this.getters.getRowSize(e,t);return{start:n,size:r,end:n+(this.getters.isRowHidden(e,t)?0:r)}}getColRowOffset(e,t,n,r=this.getters.getActiveSheetId()){let i=this.headerPositions[r][e][t];return this.headerPositions[r][e][n]-i}computeHeaderPositionsOfSheet(e){return{COL:this.computePositions(e,`COL`),ROW:this.computePositions(e,`ROW`)}}computePositions(e,t){let n={},r=0;for(let i=0;i<this.getters.getNumberHeaders(e,t)+1;i++)n[i]=r,!this.getters.isHeaderHidden(e,t,i)&&(r+=this.getters.getHeaderSize(e,t,i));return n}};let cB=new h().add(`settings`,YL).add(`sheet`,GL).add(`header grouping`,qL).add(`header visibility`,zL).add(`tables`,KL).add(`dataValidation`,IL).add(`cell`,AL).add(`merge`,VL).add(`headerSize`,RL).add(`borders`,OL).add(`conditional formatting`,FL).add(`figures`,LL).add(`chart`,NL).add(`image`,BL).add(`pivot_core`,JL).add(`spreadsheet_pivot_core`,XL).add(`tableStyle`,ZL),lB=new h().add(`ui_sheet`,yz).add(`ui_options`,vz).add(`autofill`,PR).add(`sort`,_z).add(`automatic_sum`,FR).add(`format`,mz).add(`insert_pivot`,gz).add(`pivot_presence`,Qz).add(`split_to_columns`,$z).add(`collaborative`,fz).add(`history`,Xz).add(`data_cleanup`,pz).add(`table_autofill`,eB).add(`table_ui_resize`,tB).add(`datavalidation_insert`,wz),uB=new h().add(`selection`,iB).add(`evaluation_filter`,rB).add(`header_visibility_ui`,hz).add(`cell_computed_style`,Cz).add(`table_computed_style`,bz).add(`header_positions`,sB).add(`viewport`,oB).add(`clipboard`,nB),dB=new h().add(`evaluation`,_R).add(`evaluation_chart`,SR).add(`evaluation_cf`,CR).add(`row_size`,DR).add(`data_validation_ui`,TR).add(`dynamic_tables`,ER).add(`custom_colors`,xR).add(`pivot_ui`,MR),fB=new h;fB.add(`link`,{condition:(e,t)=>!!t.getEvaluatedCell(e).link,execute:(e,t)=>no(t.model.getters.getEvaluatedCell(e).link,t),sequence:5});var pB=class{fileStore;constructor(e){this.fileStore=e}async requestImage(){let e=await this.getImageFromUser(),t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}getImageFromUser(){return new Promise((e,t)=>{let n=document.createElement(`input`);n.setAttribute(`type`,`file`),n.setAttribute(`accept`,`image/*`),n.addEventListener(`change`,async()=>{n.files===null||n.files.length!==1?t():e(n.files[0])}),n.click()})}getImageOriginalSize(e){return new Promise((t,n)=>{let r=new Image;r.src=e,r.addEventListener(`load`,()=>{t({width:r.width,height:r.height})}),r.addEventListener(`error`,n)})}};let mB=[{transform:`scale(0)`},{transform:`scale(0.8)`,offset:.33},{opacity:`0`,transform:`scale(1)`,offset:1}];H`
|
|
1901
|
+
`)||` `}getHTMLContent(){let e=``,t=this.copiedData?.cells;if(!t)e=` `;else if(t.length===1&&t[0].length===1)e=`${this.getters.getCellText(t[0][0].position)}`;else if(t[0][0]){let n=`<table border="1" style="border-collapse:collapse">`;for(let e of t){n+=`<tr>`;for(let t of e){if(!t)continue;let e=U(xf(this.getters.getCellComputedStyle(t.position))),r=this.getters.getCellText(t.position);n+=`<td style="${e}">`+th(r)+`</td>`}n+=`</tr>`}n+=`</table>`,e=n}else return``;return`<div data-osheet-clipboard='${th(JSON.stringify(this.getSheetData()))}'>${e}</div>`}isCutOperation(){return this._isCutOperation??!1}getDeleteCellsTargets(e,t){let n=this.getters.getActiveSheetId(),r;return r=t===`COL`?{...e,left:e.right+1,right:this.getters.getNumberCols(n)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(n)-1},{cut:[r],paste:[e]}}getInsertCellsTargets(e,t){let n=this.getters.getActiveSheetId(),r,i;return t===`COL`?(r={...e,right:this.getters.getNumberCols(n)-1},i={...e,left:e.right+1,right:e.right+1}):(r={...e,bottom:this.getters.getNumberRows(n)-1},i={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(n)-1}),{cut:[r],paste:[i]}}getClipboardData(e){let t=this.getters.getActiveSheetId(),n=this.getters.getSelectedFigureId();return n?{figureId:n,sheetId:t}:Ec(t,e)}drawLayer(e){if(this.status!==`visible`||!this.copiedData)return;let{sheetId:t,zones:n}=this.copiedData;if(t!==this.getters.getActiveSheetId()||!n||!n.length)return;let{ctx:r,thinLineWidth:i}=e;r.setLineDash([8,5]),r.strokeStyle=ae,r.lineWidth=3.3*i;for(let e of n){let{x:t,y:n,width:i,height:a}=this.getters.getVisibleRect(e);i>0&&a>0&&r.strokeRect(t,n,i,a)}}},rB=class extends ${static getters=[`getFilterHiddenValues`,`getFirstTableInSelection`,`isRowFiltered`,`isFilterActive`];filterValues={};hiddenRows={};isEvaluationDirty=!1;allowDispatch(e){switch(e.type){case`UPDATE_FILTER`:if(!this.getters.getFilterId(e))return`FilterNotFound`;break}return`Success`}handle(e){switch(e.type){case`UNDO`:case`REDO`:case`UPDATE_CELL`:case`EVALUATE_CELLS`:case`ACTIVATE_SHEET`:case`REMOVE_TABLE`:case`ADD_COLUMNS_ROWS`:case`REMOVE_COLUMNS_ROWS`:case`UPDATE_TABLE`:this.isEvaluationDirty=!0;break;case`START`:for(let e of this.getters.getSheetIds())this.filterValues[e]={};break;case`CREATE_SHEET`:this.filterValues[e.sheetId]={};break;case`HIDE_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`GROUP_HEADERS`:case`UNGROUP_HEADERS`:case`FOLD_HEADER_GROUP`:case`UNFOLD_HEADER_GROUP`:case`FOLD_ALL_HEADER_GROUPS`:case`UNFOLD_ALL_HEADER_GROUPS`:case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:this.updateHiddenRows(e.sheetId);break;case`UPDATE_FILTER`:this.updateFilter(e),this.updateHiddenRows(e.sheetId);break;case`DUPLICATE_SHEET`:this.filterValues[e.sheetIdTo]=y(this.filterValues[e.sheetId]);break}}finalize(){if(this.isEvaluationDirty){for(let e of this.getters.getSheetIds())this.updateHiddenRows(e);this.isEvaluationDirty=!1}}isRowFiltered(e,t){return!!this.hiddenRows[e]?.has(t)}getFilterHiddenValues(e){let t=this.getters.getFilterId(e),n=e.sheetId;return!t||!this.filterValues[n]?[]:this.filterValues[n][t]||[]}isFilterActive(e){let t=this.getters.getFilterId(e),n=e.sheetId;return!!(t&&this.filterValues[n]?.[t]?.length)}getFirstTableInSelection(){let e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZones();return this.getters.getTablesOverlappingZones(e,t)[0]}updateFilter({col:e,row:t,hiddenValues:n,sheetId:r}){let i=this.getters.getFilterId({sheetId:r,col:e,row:t});i&&(this.filterValues[r]||(this.filterValues[r]={}),this.filterValues[r][i]=n)}updateHiddenRows(e){let t=this.getters.getFilters(e).sort((e,t)=>e.rangeWithHeaders.zone.top-t.rangeWithHeaders.zone.top),n=new Set;for(let r of t){if(n.has(r.rangeWithHeaders.zone.top)||this.getters.isRowHiddenByUser(e,r.rangeWithHeaders.zone.top))continue;let t=this.filterValues[e]?.[r.id]?.map(bc),i=r.filteredRange?.zone;if(!t||!i)continue;let a=new Set(t);for(let t=i.top;t<=i.bottom;t++){let i=this.getCellValueAsString(e,r.col,t);a.has(i)&&n.add(t)}}this.hiddenRows[e]=n}getCellValueAsString(e,t,n){return this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).formattedValue.toLowerCase()}exportForExcel(e){for(let t of e.sheets){let e=t.id;for(let n of t.tables){let r=$n(n.range),i=[],a=[];for(let n of x(0,mr(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?vr(c.filteredRange.zone).map(t=>this.getters.getEvaluatedCell({sheetId:e,...t}).formattedValue):[];if(s.length){let e=l.filter(e=>e).filter(e=>!s.includes(e));i.push({colId:n,displayedValues:[...new Set(e)],displayBlanks:!s.includes(``)&&l.some(e=>!e)})}let u=this.getters.getEvaluatedCell(o).formattedValue,d=this.getUniqueColNameForExcel(n,u,a);a.push(d),t.cells[w(o.col,o.row)]={...t.cells[w(o.col,o.row)],content:d,value:d,isFormula:!1}}n.filters=i}}}getUniqueColNameForExcel(e,t,n){t||=`Column${e}`;let r=t,i=2;for(;n.includes(r);)r=t+String(i),i++;return r}},iB=class extends ${static layers=[`Selection`];static getters=[`getActiveSheet`,`getActiveSheetId`,`getActiveCell`,`getActiveCols`,`getActiveRows`,`getCurrentStyle`,`getSelectedZones`,`getSelectedZone`,`getSelectedCells`,`getSelectedFigureId`,`getSelection`,`getActivePosition`,`getSheetPosition`,`isSingleColSelected`,`getElementsFromSelection`,`tryGetActiveSheetId`,`isGridSelectionActive`];gridSelection={anchor:{cell:{col:0,row:0},zone:{top:0,left:0,bottom:0,right:0}},zones:[{top:0,left:0,bottom:0,right:0}]};selectedFigureId=null;sheetsData={};moveClient;activeSheet=null;constructor(e){super(e),this.moveClient=e.moveClient}allowDispatch(e){switch(e.type){case`ACTIVATE_SHEET`:try{if(!this.getters.getSheet(e.sheetIdTo).isVisible)return`SheetIsHidden`;break}catch{return`InvalidSheetId`}case`MOVE_COLUMNS_ROWS`:return this.isMoveElementAllowed(e)}return`Success`}handleEvent(e){let t=e.anchor,n=[];switch(e.mode){case`overrideSelection`:n=[t.zone];break;case`updateAnchor`:n=[...this.gridSelection.zones];let r=n.findIndex(t=>ur(t,e.previousAnchor.zone));r>=0&&(n[r]=t.zone);break;case`newAnchor`:n=[...this.gridSelection.zones,t.zone];break}this.setSelectionMixin(e.anchor,n),this.selection.resetDefaultAnchor(this,y(this.gridSelection.anchor));let{col:r,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:r,row:i}),this.selectedFigureId=null}handle(e){switch(e.type){case`ACTIVATE_SHEET`:this.selectedFigureId=null;break;case`DELETE_FIGURE`:this.selectedFigureId===e.id&&(this.selectedFigureId=null);break;case`DELETE_SHEET`:this.selectedFigureId&&this.getters.getFigure(e.sheetId,this.selectedFigureId)&&(this.selectedFigureId=null);break}switch(e.type){case`START`:let t=this.getters.getVisibleSheetIds()[0];this.activateSheet(t,t);let{col:n,row:r}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(n,r),this.selection.registerAsDefault(this,this.gridSelection.anchor,{handleEvent:this.handleEvent.bind(this)}),this.moveClient({sheetId:t,col:0,row:0});break;case`ACTIVATE_SHEET`:this.activateSheet(e.sheetIdFrom,e.sheetIdTo);break;case`REMOVE_COLUMNS_ROWS`:{let t=this.getters.getActiveSheetId();if(e.sheetId===t){e.dimension===`COL`?this.onColumnsRemoved(e):this.onRowsRemoved(e);let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:n,row:r})}break}case`ADD_COLUMNS_ROWS`:{let t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:n,row:r})}break}case`MOVE_COLUMNS_ROWS`:e.sheetId===this.getActiveSheetId()&&this.onMoveElements(e);break;case`SELECT_FIGURE`:this.selectedFigureId=e.id;break;case`ACTIVATE_NEXT_SHEET`:this.activateNextSheet(`right`);break;case`ACTIVATE_PREVIOUS_SHEET`:this.activateNextSheet(`left`);break;case`HIDE_SHEET`:e.sheetId===this.getActiveSheetId()&&this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:e.sheetId,sheetIdTo:this.getters.getVisibleSheetIds()[0]});break;case`UNDO`:case`REDO`:case`DELETE_SHEET`:let i=Object.keys(this.sheetsData).filter(e=>!this.getters.tryGetSheet(e));for(let e of i)delete this.sheetsData[e];for(let e in this.sheetsData){let t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:y(t)}}this.fallbackToVisibleSheet();let a=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map(e=>this.getters.expandZone(a,e)),this.gridSelection.anchor.zone=this.getters.expandZone(a,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones),this.selectedFigureId=null;break}}finalize(){this.fallbackToVisibleSheet(),this.selection.resetDefaultAnchor(this,y(this.gridSelection.anchor))}isGridSelectionActive(){return this.selection.isListening(this)}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}tryGetActiveSheetId(){return this.activeSheet?.id}getActiveCell(){return this.getters.getEvaluatedCell(this.getActivePosition())}getActiveCols(){let e=new Set;for(let t of this.gridSelection.zones)if(t.top===0&&t.bottom===this.getters.getNumberRows(this.getters.getActiveSheetId())-1)for(let n=t.left;n<=t.right;n++)e.add(n);return e}getActiveRows(){let e=new Set,t=this.getters.getActiveSheetId();for(let n of this.gridSelection.zones)if(n.left===0&&n.right===this.getters.getNumberCols(t)-1)for(let t=n.top;t<=n.bottom;t++)e.add(t);return e}getCurrentStyle(){let e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();return this.getters.getCellStyle({sheetId:t,col:e.left,row:e.top})}getSelectedZones(){return y(this.gridSelection.zones)}getSelectedZone(){return y(this.gridSelection.anchor.zone)}getSelection(){return y(this.gridSelection)}getSelectedCells(){let e=this.getters.getActiveSheetId(),t=[];for(let n of this.gridSelection.zones)t.push(...this.getters.getEvaluatedCellsInZone(e,n));return t}getSelectedFigureId(){return this.selectedFigureId}getActivePosition(){return this.getters.getMainCellPosition({sheetId:this.getActiveSheetId(),col:this.gridSelection.anchor.cell.col,row:this.gridSelection.anchor.cell.row})}getSheetPosition(e){if(e===this.getters.getActiveSheetId())return this.getActivePosition();{let t=this.sheetsData[e];return t?{sheetId:e,col:t.gridSelection.anchor.cell.col,row:t.gridSelection.anchor.cell.row}:this.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0})}}isSingleColSelected(){let e=this.getters.getSelectedZones();return!(e.length!==1||e[0].left!==e[0].right)}getElementsFromSelection(e){if(e===`COL`&&this.getters.getActiveCols().size===0||e===`ROW`&&this.getters.getActiveRows().size===0)return[];let t=this.getters.getSelectedZones(),n=[],r=e===`COL`?`left`:`top`,i=e===`COL`?`right`:`bottom`;for(let e of t){let t=Array.from({length:e[i]-e[r]+1},(t,n)=>e[r]+n);n=n.concat(t)}return[...new Set(n)].sort()}activateSheet(e,t){if(this.setActiveSheet(t),this.sheetsData[e]={gridSelection:y(this.gridSelection)},t in this.sheetsData)Object.assign(this,this.sheetsData[t]),this.selection.resetDefaultAnchor(this,y(this.gridSelection.anchor));else{let{col:e,row:n}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(e,n)}let{col:n,row:r}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.activeSheet.id,col:n,row:r})}setSelectionMixin(e,t){let{anchor:n,zones:r}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=n,this.gridSelection.zones=xr(r)}selectCell(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.expandZone(n,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:r,cell:{col:e,row:t}},[r])}setActiveSheet(e){let t=this.getters.getSheet(e);this.activeSheet=t}activateNextSheet(e){let t=this.getters.getSheetIds(),n=(t.findIndex(e=>e===this.activeSheet.id)+(e===`left`?t.length-1:1))%t.length;this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[n]})}onColumnsRemoved(e){let{cell:t,zone:n}=this.gridSelection.anchor,r=ar(n,`left`,[...e.elements]),i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=ar(i,`left`,[...e.elements]);let a={cell:{col:i.left,row:i.top},zone:r},o=this.gridSelection.zones.map(t=>ar(t,`left`,[...e.elements]));this.setSelectionMixin(a,o)}onRowsRemoved(e){let{cell:t,zone:n}=this.gridSelection.anchor,r=ar(n,`top`,[...e.elements]),i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=ar(i,`top`,[...e.elements]);let a={cell:{col:i.left,row:i.top},zone:r},o=this.gridSelection.zones.map(t=>ar(t,`top`,[...e.elements]));this.setSelectionMixin(a,o)}onAddElements(e){let t=e.dimension===`COL`?`left`:`top`,n=ir(this.gridSelection.anchor.zone,t,e.base,e.position,e.quantity),r=this.gridSelection.zones.map(n=>ir(n,t,e.base,e.position,e.quantity)),i={cell:{col:n.left,row:n.top},zone:n};this.setSelectionMixin(i,r)}onMoveElements(e){let t=e.elements.length;this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,base:e.base,quantity:t,position:e.position});let n=e.dimension===`COL`,r=e.elements[0],i=e.elements[t-1],a=e.base<r,o=a&&n?t:0,s=a&&!n?t:0,c=a?e.elements.map(e=>e+t):e.elements,l=Object.fromEntries(c.map(t=>{let r=n?this.getters.getColSize(e.sheetId,t):this.getters.getUserRowSize(e.sheetId,t);return[t,n&&r===96||r===void 0?null:r]})),u=[{left:n?r+o:0,right:n?i+o:this.getters.getNumberCols(e.sheetId)-1,top:n?0:r+s,bottom:n?this.getters.getNumberRows(e.sheetId)-1:i+s}],d=this.getActiveSheetId(),f=a?e.base:e.base+1,p=[{left:n?f:0,right:n?f+t-1:this.getters.getNumberCols(e.sheetId)-1,top:n?0:f,bottom:n?this.getters.getNumberRows(e.sheetId)-1:f+t-1}];for(let e of td.cellHandlers.getAll()){let t=new e(this.getters,this.dispatch),n=t.copy(Ec(d,u),`shiftCells`);n&&t.paste({zones:p,sheetId:d},n,{isCutOperation:!0})}let m=p[0],h=m.left,g=m.top;this.setSelectionMixin({zone:m,cell:{col:h,row:g}},[m]);let _=a?e.base:e.base+1;for(let t of c)this.dispatch(`RESIZE_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,size:l[t],elements:[_]}),_+=1;this.dispatch(`REMOVE_COLUMNS_ROWS`,{dimension:e.dimension,sheetId:e.sheetId,elements:c})}isMoveElementAllowed(e){let t=e.dimension===`COL`,n=e.elements[0],r=e.elements[e.elements.length-1],i=e.sheetId,a=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;if(a(i,n-1,n)||a(i,r,r+1)||a(i,e.base-1,e.base))return`WillRemoveExistingMerge`;let o=[e.base,...e.elements],s=t?this.getters.getNumberCols(i):this.getters.getNumberRows(i);return o.some(e=>e<0||e>=s)?`InvalidHeaderIndex`:!t&&!this.isTableRowMoveAllowed(i,e.elements)?`CannotMoveTableHeader`:`Success`}isTableRowMoveAllowed(e,t){let n=this.getters.getCoreTables(e);if(n.length===0)return!0;let r=new Set(t);return n.every(({range:{zone:e},config:n})=>{let{top:i,bottom:a}=e;if(n.numberOfHeaders===0)return!0;let o=i+n.numberOfHeaders-1;return t.some(e=>e>=i&&e<=o)?x(i,a+1).every(e=>r.has(e)):!0})}fallbackToVisibleSheet(){if(!this.getters.tryGetSheet(this.getters.getActiveSheetId())){let e=this.getters.getVisibleSheetIds();if(this.activeSheet=this.getters.getSheet(e[0]),this.activeSheet.id in this.sheetsData){let{anchor:e}=this.clipSelection(this.activeSheet.id,this.sheetsData[this.activeSheet.id].gridSelection);this.selectCell(e.cell.col,e.cell.row)}else this.selectCell(0,0);let{col:t,row:n}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:n})}}clipSelection(e,t){let n=this.getters.getNumberCols(e)-1,r=this.getters.getNumberRows(e)-1,i=t.zones.map(e=>({left:b(e.left,0,n),right:b(e.right,0,n),top:b(e.top,0,r),bottom:b(e.bottom,0,r)})),a=b(t.anchor.cell.col,0,n),o=b(t.anchor.cell.row,0,r),s={left:b(t.anchor.zone.left,0,n),right:b(t.anchor.zone.right,0,n),top:b(t.anchor.zone.top,0,r),bottom:b(t.anchor.zone.bottom,0,r)};return{zones:i,anchor:{cell:{col:a,row:o},zone:s}}}drawLayer(e){if(this.getters.isDashboard())return;let{ctx:t,thinLineWidth:n}=e,r=this.getSelectedZones();t.fillStyle=`#f3f7fe`,t.fillStyle=r.length===1&&r[0].left===r[0].right&&r[0].top===r[0].bottom?`#f3f7fe`:`#e9f0ff`,t.strokeStyle=ae,t.lineWidth=1.5*n;for(let e of r){let{x:n,y:r,width:i,height:a}=this.getters.getVisibleRect(e);t.globalCompositeOperation=`multiply`,t.fillRect(n,r,i,a),t.globalCompositeOperation=`source-over`,t.strokeRect(n,r,i,a)}t.globalCompositeOperation=`source-over`;let i=this.getActivePosition();t.strokeStyle=ae,t.lineWidth=3*n;let a;a=this.getters.isInMerge(i)?this.getters.getMerge(i):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)}},aB=class{getters;sheetId;boundaries;top;bottom;left;right;offsetX;offsetY;offsetScrollbarX;offsetScrollbarY;canScrollVertically;canScrollHorizontally;viewportWidth;viewportHeight;offsetCorrectionX;offsetCorrectionY;constructor(e,t,n,r,i,a){if(this.getters=e,this.sheetId=t,this.boundaries=n,r.width<0||r.height<0)throw Error(`Viewport size cannot be negative`);this.viewportWidth=r.height&&r.width,this.viewportHeight=r.width&&r.height,this.top=n.top,this.bottom=n.bottom,this.left=n.left,this.right=n.right,this.offsetX=a.x,this.offsetY=a.y,this.offsetScrollbarX=a.x,this.offsetScrollbarY=a.y,this.canScrollVertically=i.canScrollVertically,this.canScrollHorizontally=i.canScrollHorizontally,this.offsetCorrectionX=this.getters.getColDimensions(this.sheetId,this.boundaries.left).start,this.offsetCorrectionY=this.getters.getRowDimensions(this.sheetId,this.boundaries.top).start,this.adjustViewportOffsetX(),this.adjustViewportOffsetY()}getMaxSize(){let e=this.getters.findLastVisibleColRowIndex(this.sheetId,`COL`,{first:this.boundaries.left,last:this.boundaries.right}),t=this.getters.findLastVisibleColRowIndex(this.sheetId,`ROW`,{first:this.boundaries.top,last:this.boundaries.bottom}),{end:n,size:r}=this.getters.getColDimensions(this.sheetId,e),{end:i,size:a}=this.getters.getRowDimensions(this.sheetId,t),o=this.searchHeaderIndex(`COL`,n-this.viewportWidth,0),s=this.getters.getColSize(this.sheetId,o),c=this.searchHeaderIndex(`ROW`,i-this.viewportHeight,0),l=this.getters.getRowSize(this.sheetId,c),u=n-this.offsetCorrectionX;this.canScrollHorizontally&&(u+=Math.max(96,Math.min(s,this.viewportWidth-r)),u=Math.max(u,this.viewportWidth));let d=i-this.offsetCorrectionY;return this.canScrollVertically&&(d+=Math.max(28,Math.min(l,this.viewportHeight-a)),d=Math.max(d,this.viewportHeight),i+46>d&&!this.getters.isReadonly()&&(d+=46)),{width:u,height:d}}getColIndex(e){return e<this.offsetCorrectionX||e>this.offsetCorrectionX+this.viewportWidth?-1:this.searchHeaderIndex(`COL`,e-this.offsetCorrectionX,this.left)}getRowIndex(e){return e<this.offsetCorrectionY||e>this.offsetCorrectionY+this.viewportHeight?-1:this.searchHeaderIndex(`ROW`,e-this.offsetCorrectionY,this.top)}adjustPosition(e){let t=this.sheetId,n=this.getters.getMainCellPosition({sheetId:t,...e}),{col:r,row:i}=this.getters.getNextVisibleCellPosition(n);fr(r,this.boundaries.top,this.boundaries)&&this.adjustPositionX(r),fr(this.boundaries.left,i,this.boundaries)&&this.adjustPositionY(i)}adjustPositionX(e){let t=this.sheetId,{end:n}=this.getters.getColDimensions(t,e);if(this.offsetX+this.offsetCorrectionX+this.viewportWidth<n){let n=this.getters.getNumberCols(t),r=e;for(;this.getters.isColHidden(t,r)&&r<n;)r++;let i=this.getters.getColDimensions(t,r).end,a=this.searchHeaderIndex(`COL`,i-this.viewportWidth-this.offsetCorrectionX,this.boundaries.left);this.offsetScrollbarX=this.getters.getColDimensions(t,a).end-this.offsetCorrectionX}else if(this.left>e){let n=e;for(;this.getters.isColHidden(t,n)&&n>0;)n--;this.offsetScrollbarX=this.getters.getColDimensions(t,n).start-this.offsetCorrectionX}this.adjustViewportZoneX()}adjustPositionY(e){let t=this.sheetId,{end:n}=this.getters.getRowDimensions(t,e);if(this.offsetY+this.viewportHeight+this.offsetCorrectionY<n){let n=this.getters.getNumberRows(t),r=e;for(;this.getters.isRowHidden(t,r)&&r<n;)r++;let i=this.getters.getRowDimensions(t,r).end,a=this.searchHeaderIndex(`ROW`,i-this.viewportHeight-this.offsetCorrectionY,this.boundaries.top);this.offsetScrollbarY=this.getters.getRowDimensions(t,a).end-this.offsetCorrectionY}else if(this.top>e){let n=e;for(;this.getters.isRowHidden(t,n)&&n>0;)n--;this.offsetScrollbarY=this.getters.getRowDimensions(t,n).start-this.offsetCorrectionY}this.adjustViewportZoneY()}willNewOffsetScrollViewport(e,t){return this.canScrollHorizontally&&this.offsetScrollbarX!==e||this.canScrollVertically&&this.offsetScrollbarY!==t}setViewportOffset(e,t){this.setViewportOffsetX(e),this.setViewportOffsetY(t)}adjustViewportZone(){this.adjustViewportZoneX(),this.adjustViewportZoneY()}getVisibleRect(e){let t=lr(e,this);if(t)return{x:this.getters.getColRowOffset(`COL`,this.left,t.left)+this.offsetCorrectionX,y:this.getters.getColRowOffset(`ROW`,this.top,t.top)+this.offsetCorrectionY,width:Math.min(this.getters.getColRowOffset(`COL`,t.left,t.right+1),this.viewportWidth),height:Math.min(this.getters.getColRowOffset(`ROW`,t.top,t.bottom+1),this.viewportHeight)}}getFullRect(e){if(lr(e,this))return{x:this.getters.getColRowOffset(`COL`,this.left,e.left)+this.offsetCorrectionX,y:this.getters.getColRowOffset(`ROW`,this.top,e.top)+this.offsetCorrectionY,width:this.getters.getColRowOffset(`COL`,e.left,e.right+1),height:this.getters.getColRowOffset(`ROW`,e.top,e.bottom+1)}}isVisible(e,t){return t<=this.bottom&&t>=this.top&&e>=this.left&&e<=this.right&&!this.getters.isColHidden(this.sheetId,e)&&!this.getters.isRowHidden(this.sheetId,t)}searchHeaderIndex(e,t,n=0){if(this.viewportWidth<=0||this.viewportHeight<=0)return-1;let r=this.sheetId,i=this.getters.getNumberHeaders(r,e),a=n,o=i;for(;a<=o&&a!==i&&o!==-1;){let i=Math.floor((a+o)/2),s=this.getters.getColRowOffset(e,n,i),c=this.getters.getHeaderSize(r,e,i);if(t>=s&&t<s+c)return i;t>=s+c?a=i+1:o=i-1}return-1}setViewportOffsetX(e){this.canScrollHorizontally&&(this.offsetScrollbarX=e,this.adjustViewportZoneX())}setViewportOffsetY(e){this.canScrollVertically&&(this.offsetScrollbarY=e,this.adjustViewportZoneY())}adjustViewportOffsetX(){if(this.canScrollHorizontally){let{width:e}=this.getMaxSize();this.viewportWidth+this.offsetScrollbarX>e&&(this.offsetScrollbarX=Math.max(0,e-this.viewportWidth))}this.adjustViewportZoneX()}adjustViewportOffsetY(){if(this.canScrollVertically){let{height:e}=this.getMaxSize();this.viewportHeight+this.offsetScrollbarY>e&&(this.offsetScrollbarY=Math.max(0,e-this.viewportHeight))}this.adjustViewportZoneY()}adjustViewportZoneX(){let e=this.sheetId;if(this.left=this.searchHeaderIndex(`COL`,this.offsetScrollbarX,this.boundaries.left),this.right=Math.min(this.boundaries.right,this.searchHeaderIndex(`COL`,this.viewportWidth,this.left)),this.viewportWidth){if(this.left===-1){let e=this.getters.getColRowOffset(`COL`,this.boundaries.left,this.boundaries.right);0<e&&e<=this.offsetScrollbarX?this.left=this.boundaries.right:this.left=this.boundaries.left}this.right===-1&&(this.right=this.boundaries.right),this.offsetX=this.getters.getColDimensions(e,this.left).start-this.getters.getColDimensions(e,this.boundaries.left).start}}adjustViewportZoneY(){let e=this.sheetId;if(this.top=this.searchHeaderIndex(`ROW`,this.offsetScrollbarY,this.boundaries.top),this.bottom=Math.min(this.boundaries.bottom,this.searchHeaderIndex(`ROW`,this.viewportHeight,this.top)),this.viewportHeight){if(this.top===-1){let e=this.getters.getColRowOffset(`ROW`,this.boundaries.top,this.boundaries.bottom);0<e&&e<=this.offsetScrollbarY?this.top=this.boundaries.bottom:this.top=this.boundaries.top}this.bottom===-1&&(this.bottom=this.boundaries.bottom),this.offsetY=this.getters.getRowDimensions(e,this.top).start-this.getters.getRowDimensions(e,this.boundaries.top).start}}},oB=class extends ${static getters=[`getColIndex`,`getRowIndex`,`getActiveMainViewport`,`getSheetViewDimension`,`getSheetViewDimensionWithHeaders`,`getMainViewportRect`,`isVisibleInViewport`,`getEdgeScrollCol`,`getEdgeScrollRow`,`getVisibleFigures`,`getVisibleRect`,`getVisibleRectWithoutHeaders`,`getVisibleCellPositions`,`getColRowOffsetInViewport`,`getMainViewportCoordinates`,`getActiveSheetScrollInfo`,`getActiveSheetDOMScrollInfo`,`getSheetViewVisibleCols`,`getSheetViewVisibleRows`,`getFrozenSheetViewRatio`,`isPositionVisible`,`getColDimensionsInViewport`,`getRowDimensionsInViewport`,`getAllActiveViewportsZonesAndRect`,`getRect`];viewports={};sheetViewWidth=Je();sheetViewHeight=Je();gridOffsetX=0;gridOffsetY=0;sheetsWithDirtyViewports=new Set;shouldAdjustViewports=!1;allowDispatch(e){switch(e.type){case`SET_VIEWPORT_OFFSET`:return this.chainValidations(this.checkScrollingDirection,this.checkIfViewportsWillChange)(e);case`RESIZE_SHEETVIEW`:return this.chainValidations(this.checkValuesAreDifferent,this.checkPositiveDimension)(e);default:return`Success`}}handleEvent(e){let t=this.getters.getActiveSheetId();if(e.options.scrollIntoView){let{col:n,row:r}=Cr(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(zi.has(e.type))for(let e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);switch(e.type){case`START`:this.selection.observe(this,{handleEvent:this.handleEvent.bind(this)}),this.resetViewports(this.getters.getActiveSheetId());break;case`UNDO`:case`REDO`:this.cleanViewports();for(let e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);this.shouldAdjustViewports=!0;break;case`RESIZE_SHEETVIEW`:this.resizeSheetView(e.height,e.width,e.gridOffsetX,e.gridOffsetY);break;case`SET_VIEWPORT_OFFSET`:this.setSheetViewOffset(e.offsetX,e.offsetY);break;case`SHIFT_VIEWPORT_DOWN`:let t=this.getters.getActiveSheetId(),{top:n,viewportHeight:r,offsetCorrectionY:i}=this.getMainInternalViewport(t),a=this.getters.getRowDimensions(t,n);this.shiftVertically(a.start+r-i);break;case`SHIFT_VIEWPORT_UP`:{let e=this.getters.getActiveSheetId(),{top:t,viewportHeight:n,offsetCorrectionY:r}=this.getMainInternalViewport(e),i=this.getters.getRowDimensions(e,t);this.shiftVertically(i.end-r-n);break}case`REMOVE_TABLE`:case`UPDATE_TABLE`:case`UPDATE_FILTER`:case`UNFREEZE_ROWS`:case`UNFREEZE_COLUMNS`:case`FREEZE_COLUMNS`:case`FREEZE_ROWS`:case`UNFREEZE_COLUMNS_ROWS`:case`REMOVE_COLUMNS_ROWS`:case`RESIZE_COLUMNS_ROWS`:case`HIDE_COLUMNS_ROWS`:case`ADD_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`UNGROUP_HEADERS`:case`GROUP_HEADERS`:case`FOLD_HEADER_GROUP`:case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_ALL_HEADER_GROUPS`:case`FOLD_ALL_HEADER_GROUPS`:this.sheetsWithDirtyViewports.add(e.sheetId);break;case`UPDATE_CELL`:for(let e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);break;case`DELETE_SHEET`:this.cleanViewports(),this.sheetsWithDirtyViewports.delete(e.sheetId);break;case`ACTIVATE_SHEET`:this.sheetsWithDirtyViewports.add(e.sheetIdTo);break;case`DELETE_SHEET`:this.sheetsWithDirtyViewports.delete(e.sheetId);break;case`SCROLL_TO_CELL`:this.refreshViewport(this.getters.getActiveSheetId(),{col:e.col,row:e.row});break}}finalize(){for(let e of this.sheetsWithDirtyViewports)if(this.resetViewports(e),this.shouldAdjustViewports){let t=this.getters.getSheetPosition(e);this.getSubViewports(e).forEach(e=>{e.adjustPosition(t)})}this.sheetsWithDirtyViewports=new Set,this.shouldAdjustViewports=!1,this.setViewports()}setViewports(){let e=this.getters.getSheetIds();for(let t of e)this.viewports[t]?.bottomRight||this.resetViewports(t)}getColIndex(e){let t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map(t=>t.getColIndex(e)))}getRowIndex(e){let t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map(t=>t.getRowIndex(e)))}getSheetViewDimensionWithHeaders(){return{width:this.sheetViewWidth+this.gridOffsetX,height:this.sheetViewHeight+this.gridOffsetY}}getSheetViewDimension(){return{width:this.sheetViewWidth,height:this.sheetViewHeight}}getActiveMainViewport(){let e=this.getters.getActiveSheetId();return this.getMainViewport(e)}getActiveSheetScrollInfo(){let e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetX,scrollY:t.offsetY}}getActiveSheetDOMScrollInfo(){let e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetScrollbarX,scrollY:t.offsetScrollbarY}}getSheetViewVisibleCols(){let e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map(e=>x(e.left,e.right+1)).flat())].filter(t=>t>=0&&!this.getters.isHeaderHidden(e,`COL`,t))}getSheetViewVisibleRows(){let e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map(e=>x(e.top,e.bottom+1)).flat())].filter(t=>t>=0&&!this.getters.isHeaderHidden(e,`ROW`,t))}getVisibleCellPositions(){let e=this.getSheetViewVisibleCols(),t=this.getSheetViewVisibleRows(),n=this.getters.getActiveSheetId(),r=[];for(let i of e)for(let e of t){let t={sheetId:n,col:i,row:e},a=this.getters.getMainCellPosition(t);a.row!==e||a.col!==i||r.push(t)}return r}getMainViewportRect(){let e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e),{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(e),{width:i,height:a}=t.getMaxSize();return{x:this.getters.getColDimensions(e,n).start,y:this.getters.getRowDimensions(e,r).start,width:i,height:a}}getMaximumSheetOffset(){let e=this.getters.getActiveSheetId(),{width:t,height:n}=this.getMainViewportRect(),r=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-r.viewportWidth+1),maxOffsetY:Math.max(0,n-r.viewportHeight+1)}}getColRowOffsetInViewport(e,t,n){if(n<t)return-this.getColRowOffsetInViewport(e,n,t);let r=this.getters.getActiveSheetId(),i=e===`COL`?this.getters.getSheetViewVisibleCols():this.getters.getSheetViewVisibleRows(),a=i.findIndex(e=>t>=e),o=i.findIndex(e=>n<=e);o=o===-1?i.length:o;let s=i.slice(a,o),c=0;for(let t of s)c+=this.getters.getHeaderSize(r,e,t);return c}isVisibleInViewport({sheetId:e,col:t,row:n}){return this.getSubViewports(e).some(e=>e.isVisible(t,n))}getEdgeScrollCol(e,t,n){let r=!1,i=0,a=0,{xSplit:o}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{width:s}=this.getSheetViewDimension(),{x:c}=this.getMainViewportCoordinates(),l=this.getActiveSheetScrollInfo().scrollX;return e>s?(r=!0,a=ks(e-s),i=1):e<c&&n>=c&&l>0?(r=!0,a=ks(c-e),i=-1):o&&t<c&&e>c&&(r=!0,a=ks(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=ks(e-s),i=1):e<c&&n>=c&&l>0?(r=!0,a=ks(c-e),i=-1):o&&t<c&&e>c&&(r=!0,a=ks(e),i=`reset`),{canEdgeScroll:r,direction:i,delay:a}}getVisibleRect(e){let t=this.getVisibleRectWithoutHeaders(e);return{...t,x:t.x+this.gridOffsetX,y:t.y+this.gridOffsetY}}getVisibleRectWithoutHeaders(e){let t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,t=>t.getVisibleRect(e))}getRect(e){let t=this.getters.getActiveSheetId(),n=this.mapViewportsToRect(t,t=>t.getFullRect(e));return{...n,x:n.x+this.gridOffsetX,y:n.y+this.gridOffsetY}}getMainViewportCoordinates(){let e=this.getters.getActiveSheetId(),{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,n).start}}getColDimensionsInViewport(e,t){let n=Kt(this.getters.getSheetViewVisibleCols()),r=this.getters.getColRowOffsetInViewport(`COL`,n,t),i=this.getters.getColSize(e,t);return{start:r,size:i,end:r+(this.getters.isColHidden(e,t)?0:i)}}getRowDimensionsInViewport(e,t){let n=Kt(this.getters.getSheetViewVisibleRows()),r=this.getters.getColRowOffsetInViewport(`ROW`,n,t),i=this.getters.getRowSize(e,t);return{start:r,size:i,end:r+(this.getters.isRowHidden(e,t)?0:i)}}getAllActiveViewportsZonesAndRect(){let e=this.getters.getActiveSheetId();return this.getSubViewports(e).map(e=>({zone:e,rect:{x:e.offsetCorrectionX+this.gridOffsetX,y:e.offsetCorrectionY+this.gridOffsetY,...e.getMaxSize()}}))}ensureMainViewportExist(e){this.viewports[e]||this.resetViewports(e)}getSubViewports(e){return this.ensureMainViewportExist(e),Object.values(this.viewports[e]).filter(S)}checkPositiveDimension(e){return e.width<0||e.height<0?`InvalidViewportSize`:`Success`}checkValuesAreDifferent(e){let{height:t,width:n}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===n&&e.height===t?`ValuesNotChanged`:`Success`}checkScrollingDirection({offsetX:e,offsetY:t}){let n=this.getMainInternalViewport(this.getters.getActiveSheetId());return!n.canScrollHorizontally&&e>0||!n.canScrollVertically&&t>0?`InvalidScrollingDirection`:`Success`}checkIfViewportsWillChange({offsetX:e,offsetY:t}){let n=this.getters.getActiveSheetId(),{maxOffsetX:r,maxOffsetY:i}=this.getMaximumSheetOffset();return this.getSubViewports(n).some(n=>n.willNewOffsetScrollViewport(b(e,0,r),b(t,0,i)))?`Success`:`ViewportScrollLimitsReached`}getMainViewport(e){let t=this.getMainInternalViewport(e);return{top:t.top,left:t.left,bottom:t.bottom,right:t.right}}getMainInternalViewport(e){return this.ensureMainViewportExist(e),this.viewports[e].bottomRight}cleanViewports(){let e={};for(let t of this.getters.getSheetIds())e[t]=this.viewports[t];this.viewports=e}resizeSheetView(e,t,n=0,r=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=n,this.gridOffsetY=r,this.recomputeViewports()}recomputeViewports(){for(let e of this.getters.getSheetIds())this.resetViewports(e)}setSheetViewOffset(e,t){let n=this.getters.getActiveSheetId(),{maxOffsetX:r,maxOffsetY:i}=this.getMaximumSheetOffset();this.getSubViewports(n).forEach(n=>n.setViewportOffset(b(e,0,r),b(t,0,i)))}getViewportOffset(e){return{x:this.viewports[e]?.bottomRight.offsetScrollbarX||0,y:this.viewports[e]?.bottomRight.offsetScrollbarY||0}}resetViewports(e){if(!this.getters.tryGetSheet(e))return;let{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e),r=this.getters.getNumberCols(e),i=this.getters.getNumberRows(e),a=Math.min(this.getters.getColRowOffset(`COL`,0,t,e),this.sheetViewWidth),o=Math.min(this.getters.getColRowOffset(`ROW`,0,n,e),this.sheetViewHeight),s=Math.max(this.sheetViewWidth-a,0),c=Math.max(this.sheetViewHeight-o,0),{xRatio:l,yRatio:u}=this.getFrozenSheetViewRatio(e),d=l<1,f=u<1,p=this.getViewportOffset(e),m={topLeft:n&&t&&new aB(this.getters,e,{left:0,right:t-1,top:0,bottom:n-1},{width:a,height:o},{canScrollHorizontally:!1,canScrollVertically:!1},{x:0,y:0})||void 0,topRight:n&&new aB(this.getters,e,{left:t,right:r-1,top:0,bottom:n-1},{width:s,height:o},{canScrollHorizontally:d,canScrollVertically:!1},{x:d?p.x:0,y:0})||void 0,bottomLeft:t&&new aB(this.getters,e,{left:0,right:t-1,top:n,bottom:i-1},{width:a,height:c},{canScrollHorizontally:!1,canScrollVertically:f},{x:0,y:f?p.y:0})||void 0,bottomRight:new aB(this.getters,e,{left:t,right:r-1,top:n,bottom:i-1},{width:s,height:c},{canScrollHorizontally:d,canScrollVertically:f},{x:d?p.x:0,y:f?p.y:0})};this.viewports[e]=m}refreshViewport(e,t){this.getSubViewports(e).forEach(e=>{e.adjustViewportZone(),e.adjustPosition(t)})}shiftVertically(e){let t=this.getters.getActiveSheetId(),{top:n}=this.getMainInternalViewport(t),{scrollX:r}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(r,e);let{anchor:i}=this.getters.getSelection();if(i.cell.row>=this.getters.getPaneDivisions(t).ySplit){let e=this.getMainInternalViewport(t).top-n;this.selection.selectCell(i.cell.col,i.cell.row+e)}}getVisibleFigures(){let e=this.getters.getActiveSheetId(),t=[],n=this.getters.getFigures(e),{scrollX:r,scrollY:i}=this.getActiveSheetScrollInfo(),{x:a,y:o}=this.getters.getMainViewportCoordinates(),{width:s,height:c}=this.getters.getSheetViewDimensionWithHeaders();for(let e of n)e.x>=a&&(e.x+e.width<=a+r||e.x>=s+r+a)||e.y>=o&&(e.y+e.height<=o+i||e.y>=c+i+o)||t.push(e);return t}isPositionVisible(e){let{scrollX:t,scrollY:n}=this.getters.getActiveSheetScrollInfo(),{x:r,y:i}=this.getters.getMainViewportCoordinates(),{width:a,height:o}=this.getters.getSheetViewDimension();return!(e.x>=r&&(e.x<r+t||e.x>a+t+r)||e.y>=i&&(e.y<i+n||e.y>o+n+i))}getFrozenSheetViewRatio(e){let{xSplit:t,ySplit:n}=this.getters.getPaneDivisions(e),r=this.getters.getColDimensions(e,t).start,i=this.getters.getRowDimensions(e,n).start,a=this.sheetViewWidth+this.gridOffsetX,o=this.sheetViewHeight+this.gridOffsetY;return{xRatio:r/a,yRatio:i/o}}mapViewportsToRect(e,t){let n=1/0,r=1/0,i=0,a=0,o=!1;for(let s of this.getSubViewports(e)){let e=t(s);e&&(o=!0,n=Math.min(n,e.x),r=Math.min(r,e.y),i=Math.max(i,e.x+e.width),a=Math.max(a,e.y+e.height))}return o?{x:n,y:r,width:i-n,height:a-r}:{x:0,y:0,width:0,height:0}}},sB=class extends ${static getters=[`getColDimensions`,`getRowDimensions`,`getColRowOffset`];headerPositions={};isDirty=!0;handle(e){switch(zi.has(e.type)&&(this.headerPositions={},this.isDirty=!0),e.type){case`START`:for(let e of this.getters.getSheetIds())this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e);break;case`UPDATE_CELL`:this.headerPositions={},this.isDirty=!0;break;case`UPDATE_FILTER`:case`UPDATE_TABLE`:case`REMOVE_TABLE`:this.headerPositions={},this.isDirty=!0;break;case`REMOVE_COLUMNS_ROWS`:case`RESIZE_COLUMNS_ROWS`:case`HIDE_COLUMNS_ROWS`:case`ADD_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`FOLD_HEADER_GROUP`:case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_ALL_HEADER_GROUPS`:case`FOLD_ALL_HEADER_GROUPS`:case`UNGROUP_HEADERS`:case`GROUP_HEADERS`:case`CREATE_SHEET`:this.getters.tryGetSheet(e.sheetId)&&(this.headerPositions[e.sheetId]=this.computeHeaderPositionsOfSheet(e.sheetId));break;case`DUPLICATE_SHEET`:this.headerPositions[e.sheetIdTo]=y(this.headerPositions[e.sheetId]);break}}finalize(){for(let e of this.getters.getSheetIds())(this.isDirty||!this.headerPositions[e])&&(this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e));this.isDirty=!1}getColDimensions(e,t){let n=this.headerPositions[e].COL[t],r=this.getters.getColSize(e,t);return{start:n,size:r,end:n+(this.getters.isColHidden(e,t)?0:r)}}getRowDimensions(e,t){let n=this.headerPositions[e].ROW[t],r=this.getters.getRowSize(e,t);return{start:n,size:r,end:n+(this.getters.isRowHidden(e,t)?0:r)}}getColRowOffset(e,t,n,r=this.getters.getActiveSheetId()){let i=this.headerPositions[r][e][t];return this.headerPositions[r][e][n]-i}computeHeaderPositionsOfSheet(e){return{COL:this.computePositions(e,`COL`),ROW:this.computePositions(e,`ROW`)}}computePositions(e,t){let n={},r=0;for(let i=0;i<this.getters.getNumberHeaders(e,t)+1;i++)n[i]=r,!this.getters.isHeaderHidden(e,t,i)&&(r+=this.getters.getHeaderSize(e,t,i));return n}};let cB=new h().add(`settings`,YL).add(`sheet`,GL).add(`header grouping`,qL).add(`header visibility`,zL).add(`tables`,KL).add(`dataValidation`,IL).add(`cell`,AL).add(`merge`,VL).add(`headerSize`,RL).add(`borders`,OL).add(`conditional formatting`,FL).add(`figures`,LL).add(`chart`,NL).add(`image`,BL).add(`pivot_core`,JL).add(`spreadsheet_pivot_core`,XL).add(`tableStyle`,ZL),lB=new h().add(`ui_sheet`,yz).add(`ui_options`,vz).add(`autofill`,PR).add(`sort`,_z).add(`automatic_sum`,FR).add(`format`,mz).add(`insert_pivot`,gz).add(`pivot_presence`,Qz).add(`split_to_columns`,$z).add(`collaborative`,fz).add(`history`,Xz).add(`data_cleanup`,pz).add(`table_autofill`,eB).add(`table_ui_resize`,tB).add(`datavalidation_insert`,wz),uB=new h().add(`selection`,iB).add(`evaluation_filter`,rB).add(`header_visibility_ui`,hz).add(`cell_computed_style`,Cz).add(`table_computed_style`,bz).add(`header_positions`,sB).add(`viewport`,oB).add(`clipboard`,nB),dB=new h().add(`evaluation`,_R).add(`evaluation_chart`,SR).add(`evaluation_cf`,CR).add(`row_size`,DR).add(`data_validation_ui`,TR).add(`dynamic_tables`,ER).add(`custom_colors`,xR).add(`pivot_ui`,MR),fB=new h;fB.add(`link`,{condition:(e,t)=>!!t.getEvaluatedCell(e).link,execute:(e,t)=>no(t.model.getters.getEvaluatedCell(e).link,t),sequence:5});var pB=class{fileStore;constructor(e){this.fileStore=e}async requestImage(){let e=await this.getImageFromUser(),t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}getImageFromUser(){return new Promise((e,t)=>{let n=document.createElement(`input`);n.setAttribute(`type`,`file`),n.setAttribute(`accept`,`image/*`),n.addEventListener(`change`,async()=>{n.files===null||n.files.length!==1?t():e(n.files[0])}),n.click()})}getImageOriginalSize(e){return new Promise((t,n)=>{let r=new Image;r.src=e,r.addEventListener(`load`,()=>{t({width:r.width,height:r.height})}),r.addEventListener(`error`,n)})}};let mB=[{transform:`scale(0)`},{transform:`scale(0.8)`,offset:.33},{opacity:`0`,transform:`scale(1)`,offset:1}];H`
|
|
1902
1902
|
.o-ripple {
|
|
1903
1903
|
z-index: 1;
|
|
1904
1904
|
}
|
|
@@ -3312,4 +3312,4 @@ stores.inject(MyMetaStore, storeInstance);
|
|
|
3312
3312
|
<Relationships xmlns="${tf.Relationships}">
|
|
3313
3313
|
<Relationship ${K(e)} />
|
|
3314
3314
|
</Relationships>
|
|
3315
|
-
`),`_rels/.rels`)}function NH(e){let t={},n=new Set;for(let r of e.sheets){let e=r.name.slice(0,31),i=1;for(;n.has(e);)e=e.slice(0,31-String(i).length)+i++;n.add(e),e!==r.name&&(t[r.name]=e,r.name=e)}if(!Object.keys(t).length)return e;let r=Object.keys(t).sort((e,t)=>t.length-e.length),i=JSON.stringify(e);for(let e of r){let n=RegExp(`'?${nt(e)}'?!`,`g`);i=i.replaceAll(n,n=>{let r=t[e];return n.replace(e,r)})}return JSON.parse(i)}function PH(e){for(let t of e.sheets)t.tables=t.tables.filter(e=>mr($n(e.range)).numberOfRows>1);return e}var FH=class extends id{corePlugins=[];featurePlugins=[];statefulUIPlugins=[];coreViewsPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},n={},r=[],i=new Tc,a=!1){let o=performance.now();console.debug(`##### Model creation #####`),super(),Yn(),r=Gh(e,r);let s=zh(e,a);this.state=new nV,this.uuidGenerator=i,this.config=this.setupConfig(n),this.session=this.setupSession(s.revisionId),this.coreGetters={},this.range=new WL(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.coreGetters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.coreGetters.getRangeDataFromXc=this.range.getRangeDataFromXc.bind(this.range),this.coreGetters.getRangeDataFromZone=this.range.getRangeDataFromZone.bind(this.range),this.coreGetters.getRangeFromRangeData=this.range.getRangeFromRangeData.bind(this.range),this.coreGetters.getRangeFromZone=this.range.getRangeFromZone.bind(this.range),this.coreGetters.recomputeRanges=this.range.recomputeRanges.bind(this.range),this.coreGetters.isRangeValid=this.range.isRangeValid.bind(this.range),this.coreGetters.extendRange=this.range.extendRange.bind(this.range),this.coreGetters.getRangesUnion=this.range.getRangesUnion.bind(this.range),this.coreGetters.removeRangesSheetPrefix=this.range.removeRangesSheetPrefix.bind(this.range),this.getters={isReadonly:()=>this.config.mode===`readonly`||this.config.mode===`dashboard`,isDashboard:()=>this.config.mode===`dashboard`},this.selection=new eV(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(let e of cB.getAll())this.setupCorePlugin(e,s);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(r);for(let e of dB.getAll()){let t=this.setupUiPlugin(e);this.coreViewsPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(let e of uB.getAll()){let t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(let e of lB.getAll()){let t=this.setupUiPlugin(e);this.featurePlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}if(this.uuidGenerator.setIsFastStrategy(!1),this.dispatch(`START`),this.selection.observe(this,{handleEvent:()=>this.trigger(`update`)}),this.setupSessionEvents(),this.joinSession(),n.snapshotRequested||e[`[Content_Types].xml`]&&!this.getters.isReadonly()){let e=performance.now();console.debug(`Snapshot requested`),this.session.snapshot(this.exportData()),this.garbageCollectExternalResources(),console.debug(`Snapshot taken in`,performance.now()-e,`ms`)}(0,t.markRaw)(this),console.debug(`Model created in`,performance.now()-o,`ms`),console.debug(`######`)}joinSession(){this.session.join(this.config.client)}async leaveSession(){let e=this.getters.isReadonly()?void 0:Et(()=>this.exportData());await this.session.leave(e)}setupUiPlugin(e){let t=new e(this.uiPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}for(let n of e.layers)this.renderers[n]||(this.renderers[n]=[]),this.renderers[n].push(t);return t}setupCorePlugin(e,t){let n=new e(this.corePluginConfig);for(let t of e.getters){if(!(t in n))throw Error(`Invalid getter name: ${t} for plugin ${n.constructor}`);if(t in this.coreGetters)throw Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=n[t].bind(n)}n.import(t),this.corePlugins.push(n),this.coreHandlers.push(n),this.handlers.push(n)}onRemoteRevisionReceived({commands:e}){for(let t of e){let e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new lz(XB({initialRevisionId:e,recordChanges:this.state.recordChanges.bind(this.state),dispatch:e=>{if(!this.checkDispatchAllowed(e).isSuccessful){this.dispatchToHandlers(this.coreHandlers,{type:`UNDO`,commands:[e]});return}this.isReplayingCommand=!0,this.dispatchToHandlers(this.coreHandlers,e),this.isReplayingCommand=!1}}),this.config.transportService,e)}setupSessionEvents(){this.session.on(`remote-revision-received`,this,this.onRemoteRevisionReceived),this.session.on(`revision-undone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`UNDO`,{commands:e}),this.finalize()}),this.session.on(`revision-redone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`REDO`,{commands:e}),this.finalize()}),this.session.on(`unexpected-revision-id`,this,()=>this.trigger(`unexpected-revision-id`)),this.session.on(`collaborative-event-received`,this,()=>{this.trigger(`update`)})}setupConfig(e){let t=e.client||{id:this.uuidGenerator.smallUuid(),name:T(`Anonymous`).toString()},n=e.transportService||new HB;return{...e,mode:e.mode||`normal`,custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:n,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger(`notify-ui`,e),raiseBlockingErrorUI:e=>this.trigger(`raise-error-ui`,{text:e}),customColors:e.customColors||[]}}setupExternalConfig(e){let t=e.loadLocales||(()=>Promise.resolve(Zi));return{...e,loadLocales:t}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,canDispatch:this.canDispatch,uuidGenerator:this.uuidGenerator,custom:this.config.custom,external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,canDispatch:this.canDispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[]}}checkDispatchAllowed(e){let t=Ki(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return t.some(e=>e!==`Success`)?new Ji(t.flat()):Ji.Success}checkDispatchAllowedCoreCommand(e){let t=this.corePlugins.map(t=>t.allowDispatch(e));return t.push(this.range.allowDispatch(e)),t}checkDispatchAllowedLocalCommand(e){return this.uiHandlers.map(t=>t.allowDispatch(e))}finalize(){this.status=3;for(let e of this.handlers)e.finalize();this.status=0,this.trigger(`command-finalized`)}canDispatch=(e,t)=>this.checkDispatchAllowed(IH(e,t));dispatch=(e,t)=>{let n=IH(e,t),r=this.status;if(this.getters.isReadonly()&&!qi(n))return new Ji(`Readonly`);if(!this.session.canApplyOptimisticUpdate())return new Ji(`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();Ki(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(Ki(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(Ki(n))throw Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,n)}return Ji.Success};dispatchFromCorePlugin=(e,t)=>{let n=IH(e,t),r=this.status;this.status=2;let i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,n),this.status=r,Ji.Success};dispatchToHandlers(e,t){let n=Ki(t);for(let r of e)!n&&r instanceof DL||r.beforeHandle(t);for(let r of e)!n&&r instanceof DL||r.handle(t);this.trigger(`command-dispatched`,t)}drawLayer(e,t){let n=this.renderers[t];if(n)for(let r of n)e.ctx.save(),r.drawLayer(e,t),e.ctx.restore()}exportData(){let e=Zh();for(let t of this.handlers)t instanceof DL&&t.export(e);return e.revisionId=this.session.getRevisionId()||`START_REVISION`,e=y(e),e}updateMode(e){this.config.mode=e,this.trigger(`update`)}exportXLSX(){this.dispatch(`EVALUATE_CELLS`);let e=$h();for(let t of this.handlers)t instanceof EL&&t.exportForExcel(e);return e=y(e),wH(e)}garbageCollectExternalResources(){for(let e of this.corePlugins)e.garbageCollectExternalResources()}};function IH(e,t={}){let n=y(t);return n.type=e,n}let LH={},RH={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:26,HEADER_WIDTH:48,TOPBAR_HEIGHT:63,BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:96,DEFAULT_CELL_HEIGHT:23,SCROLLBAR_WIDTH:15},zH={autoCompleteProviders:l_,autofillModifiersRegistry:eD,autofillRulesRegistry:tD,cellMenuRegistry:bj,colMenuRegistry:fN,errorTypes:na,linkMenuRegistry:rk,functionRegistry:zT,featurePluginRegistry:lB,iconsOnCellRegistry:mf,statefulUIPluginRegistry:uB,coreViewsPluginRegistry:dB,corePluginRegistry:cB,rowMenuRegistry:_N,sidePanelRegistry:pI,figureRegistry:mO,chartSidePanelComponentRegistry:iP,chartComponentRegistry:oO,chartRegistry:aO,chartSubtypeRegistry:cO,topbarMenuRegistry:CN,topbarComponentRegistry:TN,clickableCellRegistry:fB,otRegistry:wN,inverseCommandRegistry:bO,urlRegistry:Za,cellPopoverRegistry:dD,numberFormatMenuRegistry:pN,repeatLocalCommandTransformRegistry:Wz,repeatCommandTransformRegistry:Uz,clipboardHandlersRegistries:td,pivotRegistry:jF,pivotTimeAdapterRegistry:uu,pivotSidePanelRegistry:LF,pivotNormalizationValueRegistry:Vu,supportedPivotPositionalFormulaRegistry:YE,pivotToFunctionValueRegistry:Hu,migrationStepRegistry:Ih},BH={arg:Y,isEvaluationError:N,toBoolean:L,toJsDate:R,toNumber:P,toString:F,toNormalizedPivotValue:Lu,toXC:w,toZone:$n,toUnboundedZone:Qn,toCartesian:Pn,numberToLetters:Tn,lettersToNumber:En,UuidGenerator:Tc,formatValue:B,createCurrencyFormat:$o,ColorGenerator:wn,computeTextWidth:cc,createEmptyWorkbookData:Zh,createEmptySheet:Xh,createEmptyExcelSheet:Qh,getDefaultChartJsRuntime:Zg,chartFontColor:Od,getChartAxisTitleRuntime:Nd,getChartAxisType:TD,getTrendDatasetForBarChart:Id,getTrendDatasetForLineChart:MD,getFillingMode:n_,rgbaToHex:cn,colorToRGBA:ln,positionToZone:E,isDefined:S,isMatrix:k,lazy:Et,genericRepeat:Gz,createAction:m,createActions:f,transformRangeData:rd,deepEquals:C,overlap:dr,union:sr,isInside:fr,deepCopy:y,expandZoneOnInsertion:rr,reduceZoneOnDeletion:or,unquote:at,getMaxObjectId:ku,getFunctionsFromTokens:RE,getFirstPivotFunction:KE,getNumberOfPivotFunctions:JE,parseDimension:Mu,isDateOrDatetimeField:Nu,makeFieldProposal:VE,insertTokenAfterArgSeparator:UE,insertTokenAfterLeftParenthesis:WE,mergeContiguousZones:Mr,getPivotHighlights:yN,pivotTimeAdapter:du,UNDO_REDO_PIVOT_COMMANDS:AR,createPivotFormula:Iu,areDomainArgsFieldsValid:Fu,splitReference:Hs,formatTickValue:Bd,sanitizeSheetName:st,isNumber:ki,isDateTime:Zr},VH={isMarkdownLink:pt,parseMarkdownLink:gt,markdownLink:ht,openLink:no,urlRepresentation:to},HH={Checkbox:EN,Section:Z,RoundColorPicker:UN,ChartDataSeries:AN,ChartErrorSection:MN,ChartLabelRange:NN,ChartTitle:GN,ChartPanel:sP,ChartFigure:uO,ChartJsComponent:s_,Grid:CL,GridOverlay:eL,ScorecardChart:c_,LineConfigPanel:QN,BarConfigPanel:FN,PieChartDesignPanel:$N,GenericChartConfigPanel:PN,ChartWithAxisDesignPanel:JN,GaugeChartConfigPanel:XN,GaugeChartDesignPanel:ZN,ScorecardChartConfigPanel:tP,ScorecardChartDesignPanel:nP,ChartTypePicker:aP,FigureComponent:mI,Menu:mk,Popover:uk,SelectionInput:kN,ValidationMessages:jN,AddDimensionButton:nF,PivotDimensionGranularity:oF,PivotDimensionOrder:sF,PivotDimension:aF,PivotLayoutConfigurator:uF,PivotHTMLRenderer:TL,EditableName:wL,PivotDeferUpdate:eF,PivotTitleSection:dF,CogWheelMenu:iF,TextInput:rF,SidePanelCollapsible:LN},UH={useDragAndDropListItems:pP,useHighlights:xP,useHighlightsOnHover:bP},WH={useStoreProvider:ld,DependencyContainer:ad,CellPopoverStore:KO,ComposerFocusStore:vd,CellComposerStore:EI,FindAndReplaceStore:JP,HighlightStore:SN,HoveredCellStore:GO,ModelStore:md,NotificationStore:cP,RendererStore:hd,SelectionInputStore:ON,SpreadsheetStore:gd,useStore:V,useLocalStore:ud,SidePanelStore:yL,PivotSidePanelStore:FF,PivotMeasureDisplayPanelStore:QP};function GH(e,t){return zT.add(e,t),{addFunction:(e,t)=>GH(e,t)}}let KH={DEFAULT_LOCALE:O,HIGHLIGHT_COLOR:_,PIVOT_TABLE_CONFIG:Ze,TREND_LINE_XAXIS_ID:`x1`,CHART_AXIS_CHOICES:Hd,ChartTerms:og};e.AbstractCellClipboardHandler=Fc,e.AbstractChart=jg,e.AbstractFigureClipboardHandler=Ku,e.CellErrorType=A,e.CommandResult=Xi,e.CorePlugin=DL,e.DispatchResult=Ji,e.EvaluationError=j,e.Model=FH,e.PivotRuntimeDefinition=fF,e.Registry=h,e.Revision=sz,e.SPREADSHEET_DIMENSIONS=RH,e.Spreadsheet=VB,e.SpreadsheetPivotTable=hF,e.UIPlugin=$,e.__info__=LH,e.addFunction=GH,e.addRenderingLayer=ta,e.astToFormula=xC,e.compile=kE,e.compileTokens=AE,e.components=HH,e.constants=KH,e.convertAstNodes=_C,e.coreTypes=Gi,e.findCellInNewZone=Cr,e.functionCache=OE,e.helpers=BH,e.hooks=UH,e.invalidateCFEvaluationCommands=Hi,e.invalidateDependenciesCommands=Vi,e.invalidateEvaluationCommands=zi,e.iterateAstNodes=vC,e.links=VH,e.load=zh,e.parse=hC,e.parseTokens=gC,e.readonlyAllowedCommands=Wi,e.registries=zH,e.setDefaultSheetViewSize=Ye,e.setTranslationMethod=Jn,e.stores=WH,e.tokenColors=vE,e.tokenize=zc,LH.version=`18.0.80`,LH.date=`2026-08-29T09:13:05.057Z`,LH.hash=`af324f5`})(this.o_spreadsheet=this.o_spreadsheet||{},owl);
|
|
3315
|
+
`),`_rels/.rels`)}function NH(e){let t={},n=new Set;for(let r of e.sheets){let e=r.name.slice(0,31),i=1;for(;n.has(e);)e=e.slice(0,31-String(i).length)+i++;n.add(e),e!==r.name&&(t[r.name]=e,r.name=e)}if(!Object.keys(t).length)return e;let r=Object.keys(t).sort((e,t)=>t.length-e.length),i=JSON.stringify(e);for(let e of r){let n=RegExp(`'?${nt(e)}'?!`,`g`);i=i.replaceAll(n,n=>{let r=t[e];return n.replace(e,r)})}return JSON.parse(i)}function PH(e){for(let t of e.sheets)t.tables=t.tables.filter(e=>mr($n(e.range)).numberOfRows>1);return e}var FH=class extends id{corePlugins=[];featurePlugins=[];statefulUIPlugins=[];coreViewsPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},n={},r=[],i=new Tc,a=!1){let o=performance.now();console.debug(`##### Model creation #####`),super(),Yn(),r=Gh(e,r);let s=zh(e,a);this.state=new nV,this.uuidGenerator=i,this.config=this.setupConfig(n),this.session=this.setupSession(s.revisionId),this.coreGetters={},this.range=new WL(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.coreGetters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.coreGetters.getRangeDataFromXc=this.range.getRangeDataFromXc.bind(this.range),this.coreGetters.getRangeDataFromZone=this.range.getRangeDataFromZone.bind(this.range),this.coreGetters.getRangeFromRangeData=this.range.getRangeFromRangeData.bind(this.range),this.coreGetters.getRangeFromZone=this.range.getRangeFromZone.bind(this.range),this.coreGetters.recomputeRanges=this.range.recomputeRanges.bind(this.range),this.coreGetters.isRangeValid=this.range.isRangeValid.bind(this.range),this.coreGetters.extendRange=this.range.extendRange.bind(this.range),this.coreGetters.getRangesUnion=this.range.getRangesUnion.bind(this.range),this.coreGetters.removeRangesSheetPrefix=this.range.removeRangesSheetPrefix.bind(this.range),this.getters={isReadonly:()=>this.config.mode===`readonly`||this.config.mode===`dashboard`,isDashboard:()=>this.config.mode===`dashboard`},this.selection=new eV(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(let e of cB.getAll())this.setupCorePlugin(e,s);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(r);for(let e of dB.getAll()){let t=this.setupUiPlugin(e);this.coreViewsPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(let e of uB.getAll()){let t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(let e of lB.getAll()){let t=this.setupUiPlugin(e);this.featurePlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}if(this.uuidGenerator.setIsFastStrategy(!1),this.dispatch(`START`),this.selection.observe(this,{handleEvent:()=>this.trigger(`update`)}),this.setupSessionEvents(),this.joinSession(),n.snapshotRequested||e[`[Content_Types].xml`]&&!this.getters.isReadonly()){let e=performance.now();console.debug(`Snapshot requested`),this.session.snapshot(this.exportData()),this.garbageCollectExternalResources(),console.debug(`Snapshot taken in`,performance.now()-e,`ms`)}(0,t.markRaw)(this),console.debug(`Model created in`,performance.now()-o,`ms`),console.debug(`######`)}joinSession(){this.session.join(this.config.client)}async leaveSession(){let e=this.getters.isReadonly()?void 0:Et(()=>this.exportData());await this.session.leave(e)}setupUiPlugin(e){let t=new e(this.uiPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}for(let n of e.layers)this.renderers[n]||(this.renderers[n]=[]),this.renderers[n].push(t);return t}setupCorePlugin(e,t){let n=new e(this.corePluginConfig);for(let t of e.getters){if(!(t in n))throw Error(`Invalid getter name: ${t} for plugin ${n.constructor}`);if(t in this.coreGetters)throw Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=n[t].bind(n)}n.import(t),this.corePlugins.push(n),this.coreHandlers.push(n),this.handlers.push(n)}onRemoteRevisionReceived({commands:e}){for(let t of e){let e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new lz(XB({initialRevisionId:e,recordChanges:this.state.recordChanges.bind(this.state),dispatch:e=>{if(!this.checkDispatchAllowed(e).isSuccessful){this.dispatchToHandlers(this.coreHandlers,{type:`UNDO`,commands:[e]});return}this.isReplayingCommand=!0,this.dispatchToHandlers(this.coreHandlers,e),this.isReplayingCommand=!1}}),this.config.transportService,e)}setupSessionEvents(){this.session.on(`remote-revision-received`,this,this.onRemoteRevisionReceived),this.session.on(`revision-undone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`UNDO`,{commands:e}),this.finalize()}),this.session.on(`revision-redone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`REDO`,{commands:e}),this.finalize()}),this.session.on(`unexpected-revision-id`,this,()=>this.trigger(`unexpected-revision-id`)),this.session.on(`collaborative-event-received`,this,()=>{this.trigger(`update`)})}setupConfig(e){let t=e.client||{id:this.uuidGenerator.smallUuid(),name:T(`Anonymous`).toString()},n=e.transportService||new HB;return{...e,mode:e.mode||`normal`,custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:n,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger(`notify-ui`,e),raiseBlockingErrorUI:e=>this.trigger(`raise-error-ui`,{text:e}),customColors:e.customColors||[]}}setupExternalConfig(e){let t=e.loadLocales||(()=>Promise.resolve(Zi));return{...e,loadLocales:t}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,canDispatch:this.canDispatch,uuidGenerator:this.uuidGenerator,custom:this.config.custom,external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,canDispatch:this.canDispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[]}}checkDispatchAllowed(e){let t=Ki(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return t.some(e=>e!==`Success`)?new Ji(t.flat()):Ji.Success}checkDispatchAllowedCoreCommand(e){let t=this.corePlugins.map(t=>t.allowDispatch(e));return t.push(this.range.allowDispatch(e)),t}checkDispatchAllowedLocalCommand(e){return this.uiHandlers.map(t=>t.allowDispatch(e))}finalize(){this.status=3;for(let e of this.handlers)e.finalize();this.status=0,this.trigger(`command-finalized`)}canDispatch=(e,t)=>this.checkDispatchAllowed(IH(e,t));dispatch=(e,t)=>{let n=IH(e,t),r=this.status;if(this.getters.isReadonly()&&!qi(n))return new Ji(`Readonly`);if(!this.session.canApplyOptimisticUpdate())return new Ji(`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();Ki(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(Ki(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(Ki(n))throw Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,n)}return Ji.Success};dispatchFromCorePlugin=(e,t)=>{let n=IH(e,t),r=this.status;this.status=2;let i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,n),this.status=r,Ji.Success};dispatchToHandlers(e,t){let n=Ki(t);for(let r of e)!n&&r instanceof DL||r.beforeHandle(t);for(let r of e)!n&&r instanceof DL||r.handle(t);this.trigger(`command-dispatched`,t)}drawLayer(e,t){let n=this.renderers[t];if(n)for(let r of n)e.ctx.save(),r.drawLayer(e,t),e.ctx.restore()}exportData(){let e=Zh();for(let t of this.handlers)t instanceof DL&&t.export(e);return e.revisionId=this.session.getRevisionId()||`START_REVISION`,e=y(e),e}updateMode(e){this.config.mode=e,this.trigger(`update`)}exportXLSX(){this.dispatch(`EVALUATE_CELLS`);let e=$h();for(let t of this.handlers)t instanceof EL&&t.exportForExcel(e);return e=y(e),wH(e)}garbageCollectExternalResources(){for(let e of this.corePlugins)e.garbageCollectExternalResources()}};function IH(e,t={}){let n=y(t);return n.type=e,n}let LH={},RH={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:26,HEADER_WIDTH:48,TOPBAR_HEIGHT:63,BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:96,DEFAULT_CELL_HEIGHT:23,SCROLLBAR_WIDTH:15},zH={autoCompleteProviders:l_,autofillModifiersRegistry:eD,autofillRulesRegistry:tD,cellMenuRegistry:bj,colMenuRegistry:fN,errorTypes:na,linkMenuRegistry:rk,functionRegistry:zT,featurePluginRegistry:lB,iconsOnCellRegistry:mf,statefulUIPluginRegistry:uB,coreViewsPluginRegistry:dB,corePluginRegistry:cB,rowMenuRegistry:_N,sidePanelRegistry:pI,figureRegistry:mO,chartSidePanelComponentRegistry:iP,chartComponentRegistry:oO,chartRegistry:aO,chartSubtypeRegistry:cO,topbarMenuRegistry:CN,topbarComponentRegistry:TN,clickableCellRegistry:fB,otRegistry:wN,inverseCommandRegistry:bO,urlRegistry:Za,cellPopoverRegistry:dD,numberFormatMenuRegistry:pN,repeatLocalCommandTransformRegistry:Wz,repeatCommandTransformRegistry:Uz,clipboardHandlersRegistries:td,pivotRegistry:jF,pivotTimeAdapterRegistry:uu,pivotSidePanelRegistry:LF,pivotNormalizationValueRegistry:Vu,supportedPivotPositionalFormulaRegistry:YE,pivotToFunctionValueRegistry:Hu,migrationStepRegistry:Ih},BH={arg:Y,isEvaluationError:N,toBoolean:L,toJsDate:R,toNumber:P,toString:F,toNormalizedPivotValue:Lu,toXC:w,toZone:$n,toUnboundedZone:Qn,toCartesian:Pn,numberToLetters:Tn,lettersToNumber:En,UuidGenerator:Tc,formatValue:B,createCurrencyFormat:$o,ColorGenerator:wn,computeTextWidth:cc,createEmptyWorkbookData:Zh,createEmptySheet:Xh,createEmptyExcelSheet:Qh,getDefaultChartJsRuntime:Zg,chartFontColor:Od,getChartAxisTitleRuntime:Nd,getChartAxisType:TD,getTrendDatasetForBarChart:Id,getTrendDatasetForLineChart:MD,getFillingMode:n_,rgbaToHex:cn,colorToRGBA:ln,positionToZone:E,isDefined:S,isMatrix:k,lazy:Et,genericRepeat:Gz,createAction:m,createActions:f,transformRangeData:rd,deepEquals:C,overlap:dr,union:sr,isInside:fr,deepCopy:y,expandZoneOnInsertion:rr,reduceZoneOnDeletion:or,unquote:at,getMaxObjectId:ku,getFunctionsFromTokens:RE,getFirstPivotFunction:KE,getNumberOfPivotFunctions:JE,parseDimension:Mu,isDateOrDatetimeField:Nu,makeFieldProposal:VE,insertTokenAfterArgSeparator:UE,insertTokenAfterLeftParenthesis:WE,mergeContiguousZones:Mr,getPivotHighlights:yN,pivotTimeAdapter:du,UNDO_REDO_PIVOT_COMMANDS:AR,createPivotFormula:Iu,areDomainArgsFieldsValid:Fu,splitReference:Hs,formatTickValue:Bd,sanitizeSheetName:st,isNumber:ki,isDateTime:Zr},VH={isMarkdownLink:pt,parseMarkdownLink:gt,markdownLink:ht,openLink:no,urlRepresentation:to},HH={Checkbox:EN,Section:Z,RoundColorPicker:UN,ChartDataSeries:AN,ChartErrorSection:MN,ChartLabelRange:NN,ChartTitle:GN,ChartPanel:sP,ChartFigure:uO,ChartJsComponent:s_,Grid:CL,GridOverlay:eL,ScorecardChart:c_,LineConfigPanel:QN,BarConfigPanel:FN,PieChartDesignPanel:$N,GenericChartConfigPanel:PN,ChartWithAxisDesignPanel:JN,GaugeChartConfigPanel:XN,GaugeChartDesignPanel:ZN,ScorecardChartConfigPanel:tP,ScorecardChartDesignPanel:nP,ChartTypePicker:aP,FigureComponent:mI,Menu:mk,Popover:uk,SelectionInput:kN,ValidationMessages:jN,AddDimensionButton:nF,PivotDimensionGranularity:oF,PivotDimensionOrder:sF,PivotDimension:aF,PivotLayoutConfigurator:uF,PivotHTMLRenderer:TL,EditableName:wL,PivotDeferUpdate:eF,PivotTitleSection:dF,CogWheelMenu:iF,TextInput:rF,SidePanelCollapsible:LN},UH={useDragAndDropListItems:pP,useHighlights:xP,useHighlightsOnHover:bP},WH={useStoreProvider:ld,DependencyContainer:ad,CellPopoverStore:KO,ComposerFocusStore:vd,CellComposerStore:EI,FindAndReplaceStore:JP,HighlightStore:SN,HoveredCellStore:GO,ModelStore:md,NotificationStore:cP,RendererStore:hd,SelectionInputStore:ON,SpreadsheetStore:gd,useStore:V,useLocalStore:ud,SidePanelStore:yL,PivotSidePanelStore:FF,PivotMeasureDisplayPanelStore:QP};function GH(e,t){return zT.add(e,t),{addFunction:(e,t)=>GH(e,t)}}let KH={DEFAULT_LOCALE:O,HIGHLIGHT_COLOR:_,PIVOT_TABLE_CONFIG:Ze,TREND_LINE_XAXIS_ID:`x1`,CHART_AXIS_CHOICES:Hd,ChartTerms:og};e.AbstractCellClipboardHandler=Fc,e.AbstractChart=jg,e.AbstractFigureClipboardHandler=Ku,e.CellErrorType=A,e.CommandResult=Xi,e.CorePlugin=DL,e.DispatchResult=Ji,e.EvaluationError=j,e.Model=FH,e.PivotRuntimeDefinition=fF,e.Registry=h,e.Revision=sz,e.SPREADSHEET_DIMENSIONS=RH,e.Spreadsheet=VB,e.SpreadsheetPivotTable=hF,e.UIPlugin=$,e.__info__=LH,e.addFunction=GH,e.addRenderingLayer=ta,e.astToFormula=xC,e.compile=kE,e.compileTokens=AE,e.components=HH,e.constants=KH,e.convertAstNodes=_C,e.coreTypes=Gi,e.findCellInNewZone=Cr,e.functionCache=OE,e.helpers=BH,e.hooks=UH,e.invalidateCFEvaluationCommands=Hi,e.invalidateDependenciesCommands=Vi,e.invalidateEvaluationCommands=zi,e.iterateAstNodes=vC,e.links=VH,e.load=zh,e.parse=hC,e.parseTokens=gC,e.readonlyAllowedCommands=Wi,e.registries=zH,e.setDefaultSheetViewSize=Ye,e.setTranslationMethod=Jn,e.stores=WH,e.tokenColors=vE,e.tokenize=zc,LH.version=`18.0.82`,LH.date=`2026-09-10T05:35:40.438Z`,LH.hash=`d0329aa`})(this.o_spreadsheet=this.o_spreadsheet||{},owl);
|