@odoo/o-spreadsheet 18.4.11 → 18.4.12
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.
|
@@ -1871,7 +1871,7 @@
|
|
|
1871
1871
|
background: #e7f2f6;
|
|
1872
1872
|
}
|
|
1873
1873
|
}
|
|
1874
|
-
`;class Pk extends t.Component{static template="o_spreadsheet.PivotHTMLRenderer";static components={Checkbox:oR};static props={pivotId:String,onCellClicked:Function};pivot=this.env.model.getters.getPivot(this.props.pivotId);data={columns:[],rows:[],values:[]};state=t.useState({showMissingValuesOnly:!1});setup(){const e=this.pivot.getExpandedTableStructure(),t=this.env.model.getters.getPivotFormulaId(this.props.pivotId);this.data={columns:this._buildColHeaders(t,e),rows:this._buildRowHeaders(t,e),values:this._buildValues(t,e)}}get tracker(){return this.env.model.getters.getPivotPresenceTracker(this.props.pivotId)}getTableData(){if(!this.state.showMissingValuesOnly)return this.data;const e=this.getColumnsIndexes(),t=this.getRowsIndexes();return{columns:this.buildColumnsMissing(e),rows:this.buildRowsMissing(t),values:this.buildValuesMissing(e,t)}}addRecursiveRow(e){const t=this.pivot.getExpandedTableStructure().rows,o=[...t[e].values];if(o.length<=1)return[e];o.pop();const s=t.findIndex((e=>JSON.stringify(e.values)===JSON.stringify(o)));return[e].concat(this.addRecursiveRow(s))}buildColumnsMissing(e){const t=[];for(const e of this.data.columns){const o=[];for(const t in e)for(let s=0;s<e[t].span;s++)o.push(parseInt(t,10));t.push(o)}for(let o=t[t.length-1].length;o>=0;o--)if(!e.includes(o))for(const e of t)e.splice(o,1);const o=[];for(const e in t){const s=[];let i,n=1;for(let o=0;o<t[e].length;o++)i!==t[e][o]?(void 0!==i&&s.push(Object.assign({},this.data.columns[e][i],{span:n})),i=t[e][o],n=1):n++;void 0!==i&&s.push(Object.assign({},this.data.columns[e][i],{span:n})),o.push(s)}return o}buildRowsMissing(e){return e.map((e=>this.data.rows[e]))}buildValuesMissing(e,t){const o=e.map((()=>[]));for(const s of t)for(const t in e)o[t].push(this.data.values[e[t]][s]);return o}getColumnsIndexes(){const e=new Set;for(let t=0;t<this.data.columns.length;t++){const o=[];for(let e=0;e<this.data.columns[t].length;e++)for(let s=0;s<this.data.columns[t][e].span;s++)o.push(this.data.columns[t][e]);for(let t=0;t<o.length;t++)o[t].isMissing&&e.add(t)}for(let t=0;t<this.data.columns[this.data.columns.length-1].length;t++){this.data.values[t].find((e=>e.isMissing))&&e.add(t)}return Array.from(e).sort(((e,t)=>e-t))}getRowsIndexes(){const e=new Set;for(let t=0;t<this.data.rows.length;t++){this.data.rows[t].isMissing&&e.add(t);for(const o of this.data.values)o[t].isMissing&&this.addRecursiveRow(t).forEach((t=>e.add(t)))}return Array.from(e).sort(((e,t)=>e-t))}_buildColHeaders(e,t){const o=[];for(const s of t.columns){const t=[];for(const o of s){const s=[];for(let e=0;e<o.fields.length;e++)s.push({value:o.fields[e]},{value:o.values[e]});const i=this.pivot.parseArgsToPivotDomain(s),n=this.env.model.getters.getLocale();if("measure"===i.at(-1)?.field){const{value:s,format:r}=this.pivot.getPivotMeasureValue(wi(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${Bc(e,i).join(",")})`,value:In(s,{format:r,locale:n}),span:o.width,isMissing:!this.tracker?.isHeaderPresent(i)})}else{const{value:s,format:r}=this.pivot.getPivotHeaderValueAndFormat(i);t.push({formula:`=PIVOT.HEADER(${Bc(e,i).join(",")})`,value:In(s,{format:r,locale:n}),span:o.width,isMissing:!this.tracker?.isHeaderPresent(i)})}}o.push(t)}const s=o[o.length-1];return o[o.length-1]=s.map((e=>(e.isMissing||(e.style="color: #756f6f;"),e))),o}_buildRowHeaders(e,t){const o=[];for(const s of t.rows){const t=[];for(let e=0;e<s.fields.length;e++)t.push({value:s.fields[e]},{value:s.values[e]});const i=this.pivot.parseArgsToPivotDomain(t),{value:n,format:r}=this.pivot.getPivotHeaderValueAndFormat(i),a=this.env.model.getters.getLocale(),l={formula:`=PIVOT.HEADER(${Bc(e,i).join(",")})`,value:In(n,{format:r,locale:a}),isMissing:!this.tracker?.isHeaderPresent(i)};s.indent>1&&(l.style=`padding-left: ${s.indent-10}px`),o.push(l)}return o}_buildValues(e,t){const o=[];for(const s of t.columns.at(-1)||[]){const i=[],n=wi(s.values[s.values.length-1]);for(const o of t.rows){const t=[];for(let e=0;e<o.fields.length;e++)t.push({value:o.fields[e]},{value:o.values[e]});for(let e=0;e<s.fields.length-1;e++)t.push({value:s.fields[e]},{value:s.values[e]});const r=this.pivot.parseArgsToPivotDomain(t),{value:a,format:l}=this.pivot.getPivotCellValueAndFormat(n,r),c=this.env.model.getters.getLocale();i.push({formula:`=PIVOT.VALUE(${Bc(e,r,n).join(",")})`,value:In(a,{format:l,locale:c}),isMissing:!this.tracker?.isValuePresent(n,r)})}o.push(i)}return o}}class Mk{static getters=[];history;constructor(e){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}})}exportForExcel(e){}allowDispatch(e){return"Success"}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map((e=>e.call(this,t))).flat()}chainValidations(...e){return t=>{for(const o of e){let e=o.call(this,t);Array.isArray(e)||(e=[e]);const s=e.filter((e=>"Success"!==e));if(s.length)return s}return"Success"}}checkValidations(e,...t){return this.batchValidations(...t)(e)}}class Nk extends Mk{getters;dispatch;canDispatch;constructor({getters:e,stateObserver:t,range:o,dispatch:s,canDispatch:i}){super(t),o.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.dispatch=s,this.canDispatch=i}import(e){}export(e){}adaptRanges(e,t,o){}garbageCollectExternalResources(){}}class kk{id;format;style;sheetId;getRangeString;isFormula=!0;compiledFormula;constructor(e,t,o,s,i,n,r){this.id=e,this.format=o,this.style=s,this.sheetId=n,this.getRangeString=r;let a=0;const l=t.tokens.map((e=>{if("REFERENCE"===e.type){const e=a++;return new Vk(i,e,this.sheetId,this.getRangeString)}return e}));this.compiledFormula={...t,dependencies:i,tokens:l}}get content(){return dt(this.compiledFormula.tokens.map((e=>e.value)))}get contentWithFixedReferences(){let e=0;return dt(this.compiledFormula.tokens.map((t=>{if("REFERENCE"===t.type){const t=e++;return this.getRangeString(this.compiledFormula.dependencies[t],this.sheetId,{useBoundedReference:!0})}return t.value})))}}class Vk{ranges;rangeIndex;sheetId;getRangeString;type="REFERENCE";constructor(e,t,o,s){this.ranges=e,this.rangeIndex=t,this.sheetId=o,this.getRangeString=s}get value(){const e=this.ranges[this.rangeIndex];return this.getRangeString(e,this.sheetId)}}function Lk(e){return""===e?NaN:Number(e)}function Hk(e){return Object.entries(e).map((([e,t])=>t?Uk(parseInt(e,10),t):void 0)).filter(lt).map((e=>Po(e.left,e.top)+":"+Po(e.right,e.bottom)))}function Uk(e,t){return{...t.zone,id:e}}class Bk{getters;providers=[];constructor(e){this.getters=e}static getters=["adaptFormulaStringDependencies","copyFormulaStringForSheet","extendRange","getRangeString","getRangeFromSheetXC","createAdaptedRanges","getRangeData","getRangeDataFromXc","getRangeDataFromZone","getRangeFromRangeData","getRangeFromZone","getRangesUnion","recomputeRanges","isRangeValid","removeRangesSheetPrefix"];allowDispatch(e){return"MOVE_RANGES"===e.type?1===e.target.length?"Success":"InvalidZones":"Success"}beforeHandle(e){}handle(e){const t=Ia(e);t?.applyChange&&this.executeOnAllRanges(t.applyChange,t.sheetId,t.sheetName)}finalize(){}verifyRangeRemoved(e){return t=>{const o=e(t);return"NONE"===o.changeType||pr(o.range.zone)?o:{range:o.range,changeType:"REMOVE"}}}executeOnAllRanges(e,t,o){const s=this.verifyRangeRemoved(e);for(const e of this.providers)e(s,t,o)}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,o,s){return e.map((e=>{if(!pr(e.zone))return e;const i=e.prefixSheet?e.sheetId:s,n=ba(e),r=va(e),a={...e.unboundedZone,left:n&&!e.unboundedZone.hasHeader?e.unboundedZone.left:e.unboundedZone.left+(e.parts[0].colFixed?0:t),right:n?e.unboundedZone.right:e.unboundedZone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:r&&!e.unboundedZone.hasHeader?e.unboundedZone.top:e.unboundedZone.top+(e.parts[0].rowFixed?0:o),bottom:r?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:o)};return function(e){if(mr(e.zone))return e;const t={...e.unboundedZone},o={...e.zone};let s=e.parts;if(void 0!==t.right&&t.right<t.left){const e=t.right;t.right=t.left,t.left=e,o.right=o.left,o.left=e,s=[{colFixed:s[1]?.colFixed||!1,rowFixed:s[0]?.rowFixed||!1},{colFixed:s[0]?.colFixed||!1,rowFixed:s[1]?.rowFixed||!1}]}if(void 0!==t.bottom&&t.bottom<t.top){const e=t.bottom;t.bottom=t.top,t.top=e,o.bottom=o.top,o.top=e,s=[{colFixed:s[0]?.colFixed||!1,rowFixed:s[1]?.rowFixed||!1},{colFixed:s[1]?.colFixed||!1,rowFixed:s[0]?.rowFixed||!1}]}return{unboundedZone:t,zone:o,parts:s,invalidXc:e.invalidXc,prefixSheet:e.prefixSheet,invalidSheetName:e.invalidSheetName,sheetId:e.sheetId}}(pa({...e,sheetId:i,zone:a},this.getters.getSheetSize))}))}removeRangesSheetPrefix(e,t){return t.map((t=>t.prefixSheet&&t.sheetId===e?{...t,prefixSheet:!1}:t))}extendRange(e,t,o){const s="COL"===t?e.zone.right+o:e.zone.right,i="ROW"===t?e.zone.bottom+o:e.zone.bottom,n={left:e.zone.left,top:e.zone.top,right:ba(e)?void 0:s,bottom:va(e)?void 0:i};return pa({...e,zone:n},this.getters.getSheetSize)}getRangeFromSheetXC(e,t){if(!ta.test(t)||!this.getters.tryGetSheet(e))return fa(t);const{sheetName:o}=ra(t);return ma({xc:t,sheetId:this.getters.getSheetIdByName(o)||e,invalidSheetName:o&&!this.getters.getSheetIdByName(o)?o:void 0},this.getters.getSheetSize)}getRangeString(e,t,o={useBoundedReference:!1,useFixedReference:!1}){return e?e.invalidXc?e.invalidXc:this.getters.tryGetSheet(e.sheetId)?Sa(e,t,this.getters.getSheetName,o):ti.InvalidReference:ti.InvalidReference}getRangeDataFromXc(e,t){const o=this.getters.getRangeFromSheetXC(e,t);return this.getRangeDataFromZone(o.sheetId,o.unboundedZone)}getRangeDataFromZone(e,t){return{_sheetId:e,_zone:t=this.getters.getUnboundedZone(e,t)}}getRangeData(e){return this.getRangeDataFromZone(e.sheetId,e.unboundedZone)}getRangeFromZone(e,t){return pa({sheetId:e,zone:t,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}],prefixSheet:!1},this.getters.getSheetSize)}recomputeRanges(e,t){const o=e.map((e=>e.unboundedZone)),s=t.map((e=>e.unboundedZone));return nr(o,s).map((t=>this.getRangeFromZone(e[0].sheetId,t)))}getRangeFromRangeData(e){if(!this.getters.tryGetSheet(e._sheetId))return fa(ti.InvalidReference);return pa({prefixSheet:!1,zone:e._zone,sheetId:e._sheetId,invalidSheetName:void 0,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}]},this.getters.getSheetSize)}isRangeValid(e){if(!e)return!1;const{xc:t,sheetName:o}=ra(e);return null!==t.match(ta)&&(!o||void 0!==this.getters.getSheetIdByName(o))}getRangesUnion(e){const t=e.map((e=>e.unboundedZone)),o=function(...e){return{top:Math.min(...e.map((e=>e.top))),left:Math.min(...e.map((e=>e.left))),bottom:e.some((e=>void 0===e.bottom))?void 0:Math.max(...e.map((e=>e.bottom))),right:e.some((e=>void 0===e.right))?void 0:Math.max(...e.map((e=>e.right)))}}(...t);return this.getRangeFromZone(e[0].sheetId,o)}adaptFormulaStringDependencies(e,t,o){if(!t.startsWith("="))return t;const s=HS(t),i=s.dependencies.map((t=>{const s=this.getters.getRangeFromSheetXC(e,t),i=o(s);return"NONE"===i.changeType?s:i.range}));return this.getters.getFormulaString(e,s.tokens,i)}copyFormulaStringForSheet(e,t,o,s){if(!o.startsWith("="))return o;const i=HS(o),n=i.dependencies.map((o=>{const i=this.getters.getRangeFromSheetXC(e,o);return"keepSameReference"===s?i:Ca(e,t,i)}));return this.getters.getFormulaString(t,i.tokens,n)}}function zk(e,t){if(!e)return;const o=t(e);switch(o.changeType){case"NONE":return e;case"REMOVE":return;default:return o.range}}class $k extends Mk{getters;constructor({getters:e,stateObserver:t}){super(t),this.getters=e}}const Gk=new n;Gk.add("pivots",(e=>{for(const t of e.getPivotIds()){const o=e.getPivot(t);o.markAsDirtyForEvaluation?.()}}));const Wk=RS.mapping;function qk(e,t,o){return new Zk(e,t,o).getParameters()}class Zk{getters;computeCell;evalContext;rangeCache={};constructor(e,t,o){this.getters=t,this.computeCell=o,this.evalContext=Object.assign(Object.create(Wk),e,{getters:this.getters,locale:this.getters.getLocale()})}getParameters(){return{referenceDenormalizer:this.refFn.bind(this),ensureRange:this.range.bind(this),evalContext:this.evalContext}}refFn(e,t){const o=this.getRangeError(e);if(o)return o;if(t){return{value:aa(this.getters.getSheetName(e.sheetId),fr(e.zone))}}const s={sheetId:e.sheetId,col:e.zone.left,row:e.zone.top};return this.computeCell(s)}range(e){const t=this.getRangeError(e);if(t)return[[t]];const o=e.sheetId,s=e.zone,i=wr(s,this.getters.getSheetZone(o));if(!i)return[[]];const{top:n,left:r,bottom:a,right:l}=s,c=`${o}-${n}-${r}-${a}-${l}`;if(c in this.rangeCache)return this.rangeCache[c];const h=i.bottom-i.top+1,d=i.right-i.left+1,u=new Array(d);for(let e=i.left;e<=i.right;e++){const t=e-i.left;u[t]=new Array(h);for(let s=i.top;s<=i.bottom;s++){const n=s-i.top;u[t][n]=this.computeCell({sheetId:o,col:e,row:s})}}return this.rangeCache[c]=u,u}getRangeError(e){return pr(e.zone)?e.invalidSheetName?new si(Ho("Invalid sheet name: %s",e.invalidSheetName)):void 0:new ri}}function jk(e,t,o,s,i){Yk(e,t,o||0,s||e.length-1,i||Kk)}function Yk(e,t,o,s,i){for(;s>o;){if(s-o>600){var n=s-o+1,r=t-o+1,a=Math.log(n),l=.5*Math.exp(2*a/3),c=.5*Math.sqrt(a*l*(n-l)/n)*(r-n/2<0?-1:1);Yk(e,t,Math.max(o,Math.floor(t-r*l/n+c)),Math.min(s,Math.floor(t+(n-r)*l/n+c)),i)}var h=e[t],d=o,u=s;for(Xk(e,o,t),i(e[s],h)>0&&Xk(e,o,s);d<u;){for(Xk(e,d,u),d++,u--;i(e[d],h)<0;)d++;for(;i(e[u],h)>0;)u--}0===i(e[o],h)?Xk(e,o,u):Xk(e,++u,s),u<=t&&(o=u+1),t<=u&&(s=u-1)}}function Xk(e,t,o){var s=e[t];e[t]=e[o],e[o]=s}function Kk(e,t){return e<t?-1:e>t?1:0}class Jk{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(e){let t=this.data;const o=[];if(!cV(e,t))return o;const s=this.toBBox,i=[];for(;t;){for(let n=0;n<t.children.length;n++){const r=t.children[n],a=t.leaf?s(r):r;cV(e,a)&&(t.leaf?o.push(r):lV(e,a)?this._all(r,o):i.push(r))}t=i.pop()}return o}collides(e){let t=this.data;if(!cV(e,t))return!1;const o=[];for(;t;){for(let s=0;s<t.children.length;s++){const i=t.children[s],n=t.leaf?this.toBBox(i):i;if(cV(e,n)){if(t.leaf||lV(e,n))return!0;o.push(i)}}t=o.pop()}return!1}load(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(let t=0;t<e.length;t++)this.insert(e[t]);return this}let t=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===t.height)this._splitRoot(this.data,t);else{if(this.data.height<t.height){const e=this.data;this.data=t,t=e}this._insert(t,this.data.height-t.height-1,!0)}else this.data=t;return this}insert(e){return e&&this._insert(e,this.data.height-1),this}clear(){return this.data=hV([]),this}remove(e,t){if(!e)return this;let o=this.data;const s=this.toBBox(e),i=[],n=[];let r,a,l;for(;o||i.length;){if(o||(o=i.pop(),a=i[i.length-1],r=n.pop(),l=!0),o.leaf){const s=Qk(e,o.children,t);if(-1!==s)return o.children.splice(s,1),i.push(o),this._condense(i),this}l||o.leaf||!lV(o,s)?a?(r++,o=a.children[r],l=!1):o=null:(i.push(o),n.push(r),r=0,a=o,o=o.children[0])}return this}toBBox(e){return e}compareMinX(e,t){return e.minX-t.minX}compareMinY(e,t){return e.minY-t.minY}toJSON(){return this.data}fromJSON(e){return this.data=e,this}_all(e,t){const o=[];for(;e;)e.leaf?t.push(...e.children):o.push(...e.children),e=o.pop();return t}_build(e,t,o,s){const i=o-t+1;let n,r=this._maxEntries;if(i<=r)return n=hV(e.slice(t,o+1)),eV(n,this.toBBox),n;s||(s=Math.ceil(Math.log(i)/Math.log(r)),r=Math.ceil(i/Math.pow(r,s-1))),n=hV([]),n.leaf=!1,n.height=s;const a=Math.ceil(i/r),l=a*Math.ceil(Math.sqrt(r));dV(e,t,o,l,this.compareMinX);for(let i=t;i<=o;i+=l){const t=Math.min(i+l-1,o);dV(e,i,t,a,this.compareMinY);for(let o=i;o<=t;o+=a){const i=Math.min(o+a-1,t);n.children.push(this._build(e,o,i,s-1))}}return eV(n,this.toBBox),n}_chooseSubtree(e,t,o,s){for(;s.push(t),!t.leaf&&s.length-1!==o;){let o,s=1/0,r=1/0;for(let a=0;a<t.children.length;a++){const l=t.children[a],c=nV(l),h=(i=e,n=l,(Math.max(n.maxX,i.maxX)-Math.min(n.minX,i.minX))*(Math.max(n.maxY,i.maxY)-Math.min(n.minY,i.minY))-c);h<r?(r=h,s=c<s?c:s,o=l):h===r&&c<s&&(s=c,o=l)}t=o||t.children[0]}var i,n;return t}_insert(e,t,o){const s=o?e:this.toBBox(e),i=[],n=this._chooseSubtree(s,this.data,t,i);for(n.children.push(e),oV(n,s);t>=0&&i[t].children.length>this._maxEntries;)this._split(i,t),t--;this._adjustParentBBoxes(s,i,t)}_split(e,t){const o=e[t],s=o.children.length,i=this._minEntries;this._chooseSplitAxis(o,i,s);const n=this._chooseSplitIndex(o,i,s),r=hV(o.children.splice(n,o.children.length-n));r.height=o.height,r.leaf=o.leaf,eV(o,this.toBBox),eV(r,this.toBBox),t?e[t-1].children.push(r):this._splitRoot(o,r)}_splitRoot(e,t){this.data=hV([e,t]),this.data.height=e.height+1,this.data.leaf=!1,eV(this.data,this.toBBox)}_chooseSplitIndex(e,t,o){let s,i=1/0,n=1/0;for(let r=t;r<=o-t;r++){const t=tV(e,0,r,this.toBBox),a=tV(e,r,o,this.toBBox),l=aV(t,a),c=nV(t)+nV(a);l<i?(i=l,s=r,n=c<n?c:n):l===i&&c<n&&(n=c,s=r)}return s||o-t}_chooseSplitAxis(e,t,o){const s=e.leaf?this.compareMinX:sV,i=e.leaf?this.compareMinY:iV;this._allDistMargin(e,t,o,s)<this._allDistMargin(e,t,o,i)&&e.children.sort(s)}_allDistMargin(e,t,o,s){e.children.sort(s);const i=this.toBBox,n=tV(e,0,t,i),r=tV(e,o-t,o,i);let a=rV(n)+rV(r);for(let s=t;s<o-t;s++){const t=e.children[s];oV(n,e.leaf?i(t):t),a+=rV(n)}for(let s=o-t-1;s>=t;s--){const t=e.children[s];oV(r,e.leaf?i(t):t),a+=rV(r)}return a}_adjustParentBBoxes(e,t,o){for(let s=o;s>=0;s--)oV(t[s],e)}_condense(e){for(let t,o=e.length-1;o>=0;o--)0===e[o].children.length?o>0?(t=e[o-1].children,t.splice(t.indexOf(e[o]),1)):this.clear():eV(e[o],this.toBBox)}}function Qk(e,t,o){if(!o)return t.indexOf(e);for(let s=0;s<t.length;s++)if(o(e,t[s]))return s;return-1}function eV(e,t){tV(e,0,e.children.length,t,e)}function tV(e,t,o,s,i){i||(i=hV(null)),i.minX=1/0,i.minY=1/0,i.maxX=-1/0,i.maxY=-1/0;for(let n=t;n<o;n++){const t=e.children[n];oV(i,e.leaf?s(t):t)}return i}function oV(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 sV(e,t){return e.minX-t.minX}function iV(e,t){return e.minY-t.minY}function nV(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function rV(e){return e.maxX-e.minX+(e.maxY-e.minY)}function aV(e,t){const o=Math.max(e.minX,t.minX),s=Math.max(e.minY,t.minY),i=Math.min(e.maxX,t.maxX),n=Math.min(e.maxY,t.maxY);return Math.max(0,i-o)*Math.max(0,n-s)}function lV(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function cV(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function hV(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function dV(e,t,o,s,i){const n=[t,o];for(;n.length;){if((o=n.pop())-(t=n.pop())<=s)continue;const r=t+Math.ceil((o-t)/s/2)*s;jk(e,r,t,o,i),n.push(t,r,r,o)}}class uV{rTrees={};constructor(e=[]){const t={};for(const o of e){const e=o.boundingBox.sheetId;t[e]||(t[e]=[]),t[e].push(o)}for(const e in t)this.rTrees[e]=new gV,this.rTrees[e].load(t[e])}insert(e){const t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new gV),this.rTrees[t].insert(e)}search({zone:e,sheetId:t}){return this.rTrees[t]?this.rTrees[t].search({minX:e.left,minY:e.top,maxX:e.right,maxY:e.bottom}):[]}remove(e){const t=e.boundingBox.sheetId;this.rTrees[t]&&this.rTrees[t].remove(e,this.rtreeItemComparer)}rtreeItemComparer(e,t){return e.data===t.data&&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}}class gV extends Jk{toBBox({boundingBox:e}){const t=e.zone;return{minX:t.left,minY:t.top,maxX:t.right,maxY:t.bottom}}compareMinX(e,t){return e.boundingBox.zone.left-t.boundingBox.zone.left}compareMinY(e,t){return e.boundingBox.zone.top-t.boundingBox.zone.top}}class pV{createEmptyPositionSet;dependencies=new $D;rTree;constructor(e,t=[]){this.createEmptyPositionSet=e,this.rTree=new uV(t)}removeAllDependencies(e){const t=this.dependencies.get(e);if(t){for(const e of t)this.rTree.remove(e);this.dependencies.delete(e)}}addDependencies(e,t){const o=t.map((({sheetId:t,zone:o})=>({data:e,boundingBox:{zone:o,sheetId:t}})));for(const e of o)this.rTree.insert(e);const s=this.dependencies.get(e);s?s.push(...o):this.dependencies.set(e,o)}getCellsDependingOn(e){const t=this.createEmptyPositionSet(),o=Array.from(e).reverse();for(;o.length>0;){const e=o.pop(),s=e.zone,i=e.sheetId;for(let e=s.left;e<=s.right;e++)for(let o=s.top;o<=s.bottom;o++)t.add({sheetId:i,col:e,row:o});const n=this.rTree.search(e).map((e=>e.data)),r={};for(const e of n)t.has(e)||(r[e.sheetId]||(r[e.sheetId]=[]),r[e.sheetId].push(Mr(e)));for(const e in r){const t=nr(r[e],[]);o.push(...t.map((t=>({sheetId:e,zone:t}))))}}for(const o of e){const e=o.zone,s=o.sheetId;for(let o=e.left;o<=e.right;o++)for(let i=e.top;i<=e.bottom;i++)t.delete({sheetId:s,col:o,row:i})}return t}}class mV extends Uint32Array{columnOffset=0;cols=0;rows=0;static create(e,t){const o=function(e){if(0===e)return-1/0;if(e<0)return NaN;return 32-Math.clz32(--e)}(t),s=new this((e<<o>>5)+1);return s.columnOffset=o,s.cols=t,s.rows=e,s}getValue(e){const[t,o]=this.getCoordinates(e);return this[t]>>o&1}setValue(e,t){const[o,s]=this.getCoordinates(e),i=0===(this[o]>>s&1)&&1===t;return this[o]=this[o]&~(1<<s)|t<<s,i}isEmpty(){return!this.some((e=>0!==e))}fillAllPositions(){this.fill(-1>>>0)}clear(){this.fill(0)}getCoordinates(e){const{row:t,col:o}=e,s=(t<<this.columnOffset)+o,i=s>>5;return[i,s-(i<<5)]}}class fV{sheets={};insertions=[];maxSize=0;constructor(e){for(const t in e){const o=e[t].cols,s=e[t].rows;this.maxSize+=o*s,this.sheets[t]=mV.create(s,o)}}add(e){this.sheets[e.sheetId].setValue(e,1)&&this.insertions.push(e)}addMany(e){for(const t of e)this.add(t)}delete(e){this.sheets[e.sheetId].setValue(e,0)}deleteMany(e){for(const t of e)this.delete(t)}has(e){return 1===this.sheets[e.sheetId].getValue(e)}clear(){const e=[...this];this.insertions=[];for(const e in this.sheets)this.sheets[e].clear();return e}isEmpty(){if(0===this.insertions.length)return!0;for(const e in this.sheets)if(!this.sheets[e].isEmpty())return!1;return!0}fillAllPositions(){this.insertions=new Array(this.maxSize);let e=0;for(const t in this.sheets){const o=this.sheets[t];o.fillAllPositions();for(let s=0;s<o.rows;s++)for(let i=0;i<o.cols;i++)this.insertions[e++]={sheetId:t,row:s,col:i}}}*[Symbol.iterator](){for(const e of this.insertions)1===this.sheets[e.sheetId].getValue(e)&&(yield e)}}class vV{resultsToArrayFormulas=new uV;arrayFormulasToResults=new $D;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map((e=>e.data))||bV}getArrayResultZone(e){return this.arrayFormulasToResults.get(e)}removeNode(e){this.resultsToArrayFormulas.remove({boundingBox:{sheetId:e.sheetId,zone:Mr(e)},data:e}),this.arrayFormulasToResults.delete(e)}addRelation({arrayFormulaPosition:e,resultZone:t}){this.resultsToArrayFormulas.insert({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.set(e,t)}isArrayFormula(e){return this.arrayFormulasToResults.has(e)}}const bV=[],SV=Object.freeze(Jn(new ni)),CV=Object.freeze(Jn({value:null}));class yV{context;getters;compilationParams;evaluatedCells=new $D;formulaDependencies=ut(new pV(this.createEmptyPositionSet.bind(this)));blockedArrayFormulas=new fV({});spreadingRelations=new vV;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=qk(this.context,this.getters,this.computeAndSave.bind(this))}getEvaluatedCell(e){return this.evaluatedCells.get(e)||CV}getSpreadZone(e,t={ignoreSpillError:!1}){const o=this.spreadingRelations.getArrayResultZone(e);if(!o)return;const s=this.evaluatedCells.get(e);return s?.type!==_s.error||t.ignoreSpillError&&s?.value===ti.SpilledBlocked?yr(Mr(e),o):Mr(e)}getEvaluatedPositions(){return this.evaluatedCells.keys()}getEvaluatedPositionsInSheet(e){return this.evaluatedCells.keysForSheet(e)}getArrayFormulaSpreadingOn(e){if(this.getEvaluatedCell(e).type===_s.empty)return;const t=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e.sheetId,Mr(e));return Array.from(t).find((e=>!this.blockedArrayFormulas.has(e)))}updateDependencies(e){this.formulaDependencies().removeAllDependencies(e);const t=this.getDirectDependencies(e);this.formulaDependencies().addDependencies(e,t)}addDependencies(e,t){this.formulaDependencies().addDependencies(e,t);for(const e of t){const t=e.sheetId,{left:o,bottom:s,right:i,top:n}=e.zone;for(let e=o;e<=i;e++)for(let o=n;o<=s;o++)this.computeAndSave({sheetId:t,col:e,row:o})}}updateCompilationParameters(){this.compilationParams=qk(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.updateDependencies=this.updateDependencies.bind(this),this.compilationParams.evalContext.addDependencies=this.addDependencies.bind(this),this.compilationParams.evalContext.lookupCaches={forwardSearch:new Map,reverseSearch:new Map}}createEmptyPositionSet(){const e={};for(const t of this.getters.getSheetIds())e[t]={rows:this.getters.getNumberRows(t),cols:this.getters.getNumberCols(t)};return new fV(e)}evaluateCells(e){const t=performance.now(),o=this.createEmptyPositionSet();o.addMany(e);const s=this.getArrayFormulasImpactedByChangesOf(e);o.addMany(this.getCellsDependingOn(e)),o.addMany(s),o.addMany(this.getCellsDependingOn(s)),this.evaluate(o),console.debug("evaluate Cells",performance.now()-t,"ms")}getArrayFormulasImpactedByChangesOf(e){const t=this.createEmptyPositionSet();for(const o of e){const e=this.getters.getCell(o)?.content,s=this.getArrayFormulaSpreadingOn(o);void 0!==s&&t.add(s),e||t.add(o)}const o=Dr(t);for(const e in o)for(const s of o[e])t.addMany(this.getArrayFormulasBlockedBy(e,s));return t}buildDependencyGraph(){this.blockedArrayFormulas=this.createEmptyPositionSet(),this.spreadingRelations=new vV,this.formulaDependencies=ut((()=>{const e=[...this.getAllCells()].flatMap((e=>this.getDirectDependencies(e).filter((e=>!e.invalidSheetName&&!e.invalidXc)).map((t=>({data:e,boundingBox:{zone:t.zone,sheetId:t.sheetId}})))));return new pV(this.createEmptyPositionSet.bind(this),e)}))}evaluateAllCells(){const e=performance.now();this.evaluatedCells=new $D,this.evaluate(this.getAllCells()),console.debug("evaluate all cells",performance.now()-e,"ms")}evaluateFormulaResult(e,t){const o=HS(t),s=o.dependencies.map((t=>this.getters.getRangeFromSheetXC(e,t)));return this.updateCompilationParameters(),this.evaluateCompiledFormula(e,{...o,dependencies:s})}evaluateCompiledFormula(e,t,o){try{const s=xV(t,this.compilationParams,e,this.buildSafeGetSymbolValue(o),this.compilationParams.evalContext.__originCellPosition);return js(s)?ki(s,IV):IV(s)}catch(e){return TS(e,"")}}getAllCells(){const e=this.createEmptyPositionSet();return e.fillAllPositions(),e}getArrayFormulasBlockedBy(e,t){const o=this.createEmptyPositionSet(),s=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e,t);o.addMany(s);const i=[...s].filter((e=>!this.blockedArrayFormulas.has(e)));return i.length&&o.deleteMany(i),o.addMany(this.getCellsDependingOn(o)),o}nextPositionsToUpdate=new fV({});cellsBeingComputed=new Set;symbolsBeingComputed=new Set;evaluate(e){this.cellsBeingComputed=new Set,this.nextPositionsToUpdate=e;let t=0;for(;!this.nextPositionsToUpdate.isEmpty()&&t++<30;){this.updateCompilationParameters();const e=this.nextPositionsToUpdate.clear();for(let t=0;t<e.length;++t)this.evaluatedCells.delete(e[t]);for(let t=0;t<e.length;++t){const o=e[t];if(this.nextPositionsToUpdate.has(o))continue;const s=this.computeCell(o);s!==CV&&this.evaluatedCells.set(o,s)}Gk.getAll().forEach((e=>e(this.getters)))}t>=30&&console.warn("Maximum iteration reached while evaluating cells")}computeCell(e){const t=this.evaluatedCells.get(e);if(t)return t;this.blockedArrayFormulas.has(e)||this.invalidateSpreading(e),this.spreadingRelations.isArrayFormula(e)&&this.spreadingRelations.removeNode(e);const o=this.getters.getCell(e);if(void 0===o)return CV;const s=o.id,i={format:o.format,locale:this.getters.getLocale()};try{return this.cellsBeingComputed.has(s)?SV:(this.cellsBeingComputed.add(s),o.isFormula?this.computeFormulaCell(e,o):Xn(o,i))}catch(e){return e.value=e?.value||ti.GenericError,e.message=e?.message||DS,Jn(e)}finally{this.cellsBeingComputed.delete(s)}}computeAndSave(e){const t=this.computeCell(e);return this.evaluatedCells.has(e)||this.evaluatedCells.set(e,t),t}computeFormulaCell(e,t){const o=xV(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e);if(!js(o)){const s=Jn(IV(o),this.getters.getLocale(),t);return s.type===_s.error&&(s.errorOriginPosition=o.errorOriginPosition??e),s}this.assertSheetHasEnoughSpaceToSpreadFormulaResult(e,o);const s=o.length,i=o[0].length,n={top:e.row,bottom:e.row+i-1,left:e.col,right:e.col+s-1};return this.spreadingRelations.addRelation({resultZone:n,arrayFormulaPosition:e}),this.assertNoMergedCellsInSpreadZone(e,o),wV(s,i,this.checkCollision(e)),wV(s,i,this.spreadValues(e,o)),this.invalidatePositionsDependingOnSpread(e.sheetId,n),Jn(IV(o[0][0]),this.getters.getLocale(),t)}invalidatePositionsDependingOnSpread(e,t){const o=this.formulaDependencies().getCellsDependingOn(function(e){const{top:t,left:o,bottom:s,right:i}=e;if(1===Lr(e))return[];const n={top:t+1,bottom:s,left:o,right:o};if(i===o)return[n];const r={top:t,bottom:s,left:o+1,right:i};return t===s?[r]:[n,r]}(t).map((t=>({sheetId:e,zone:t}))));o.delete({sheetId:e,col:t.left,row:t.top}),this.nextPositionsToUpdate.addMany(o)}assertSheetHasEnoughSpaceToSpreadFormulaResult({sheetId:e,col:t,row:o},s){const i=this.getters.getNumberCols(e),n=this.getters.getNumberRows(e),r=t+s.length<=i,a=o+s[0].length<=n;if(!r||!a){if(r)throw new ci(Ho("Result couldn't be automatically expanded. Please insert more rows."));if(a)throw new ci(Ho("Result couldn't be automatically expanded. Please insert more columns."));throw new ci(Ho("Result couldn't be automatically expanded. Please insert more columns and rows."))}}assertNoMergedCellsInSpreadZone({sheetId:e,col:t,row:o},s){if(0!==this.getters.getMergesInZone(e,{top:o,bottom:o+s[0].length-1,left:t,right:t+s.length-1}).length)throw new ci(Ho("Merged cells found in the spill zone. Please unmerge cells before using array formulas."))}checkCollision(e){const{sheetId:t,col:o,row:s}=e;return(i,n)=>{const r={sheetId:t,col:i+o,row:n+s},a=this.getters.getCell(r);if(a?.content||this.getters.getEvaluatedCell(r).type!==_s.empty)throw this.blockedArrayFormulas.add(e),new ci(Ho("Array result was not expanded because it would overwrite data in %s.",Po(r.col,r.row)));this.blockedArrayFormulas.delete(e)}}spreadValues({sheetId:e,col:t,row:o},s){return(i,n)=>{const r={sheetId:e,col:i+t,row:n+o},a=this.getters.getCell(r),l=Jn(IV(s[i][n]),this.getters.getLocale(),a);l.type===_s.error&&(l.errorOriginPosition=s[i][n].errorOriginPosition??r),this.evaluatedCells.set(r,l)}}invalidateSpreading(e){const t=this.spreadingRelations.getArrayResultZone(e);if(!t)return;for(let o=t.left;o<=t.right;o++)for(let s=t.top;s<=t.bottom;s++){const t={sheetId:e.sheetId,col:o,row:s},i=this.getters.getCell(t)?.content;i||this.evaluatedCells.delete(t)}const o=e.sheetId;this.invalidatePositionsDependingOnSpread(o,t),this.nextPositionsToUpdate.addMany(this.getArrayFormulasBlockedBy(o,t))}buildSafeGetSymbolValue(e){return t=>{if(this.symbolsBeingComputed.has(t))return SV;this.symbolsBeingComputed.add(t);try{const o=e?.(t);return o||new ii(Ho("Invalid formula"))}finally{this.symbolsBeingComputed.delete(t)}}}getDirectDependencies(e){const t=this.getters.getCell(e);return t?.isFormula?t.compiledFormula.dependencies:[]}getCellsDependingOn(e){const t=[],o=Dr(e);for(const e in o)t.push(...o[e].map((t=>({sheetId:e,zone:t}))));return this.formulaDependencies().getCellsDependingOn(t)}}function wV(e,t,o){for(let s=0;s<e;++s)for(let e=0;e<t;++e)0===s&&0===e||o(s,e)}function IV(e){return null===e.value||void 0===e.value?{...e,value:0}:e}function xV(e,t,o,s,i){return t.evalContext.__originCellPosition=i,t.evalContext.__originSheetId=o,e.execute(e.dependencies,t.referenceDenormalizer,t.ensureRange,s,t.evalContext)}const EV=/"(#[0-9a-fA-F]{6})"/g;const RV={isValid:!0};const TV=new n;function AV(e,t){const o=t.model.getters.getPivotCellFromPosition(e),s=t.model.getters.getPivotIdFromPosition(e);if(!s||"HEADER"!==o.type)return;const i=t.model.getters.getPivotCoreDefinition(s),n=i.collapsedDomains?.[o.dimension]?[...i.collapsedDomains[o.dimension]]:[],r=n.findIndex((e=>mt(e,o.domain)));-1!==r?n.splice(r,1):n.push(o.domain);const a=i.collapsedDomains?{...i.collapsedDomains}:{COL:[],ROW:[]};a[o.dimension]=n,t.model.dispatch("UPDATE_PIVOT",{pivotId:s,pivot:{...i,collapsedDomains:a}})}TV.add("data_validation_checkbox",((e,t)=>{if(e.isCellValidCheckbox(t)){const o=!!e.getEvaluatedCell(t).value;return{svg:o?jR:qR,hoverSvg:o?jR:ZR,priority:2,horizontalAlign:"center",size:17,margin:2,position:t,type:"data_validation_checkbox",onClick:(e,t)=>{const s=t.model.getters.getCell(e);if(t.model.getters.isReadonly()||!!s?.isFormula)return;const i=o?"FALSE":"TRUE";t.model.dispatch("UPDATE_CELL",{...e,content:i})}}}})),TV.add("data_validation_chip_icon",((e,t)=>{const o=e.getDataValidationChipStyle(t);if(o){const s=e.getCellComputedStyle(t);return{svg:GR(o),hoverSvg:WR(o),priority:10,horizontalAlign:"right",size:$a(s),margin:4,position:t,onClick:(e,t)=>{const{col:o,row:s}=e;t.model.selection.selectCell(o,s),t.startCellEdition()},type:"data_validation_chip_icon"}}})),TV.add("data_validation_list_icon",((e,t)=>{if(!e.isReadonly()&&e.cellHasListDataValidationIcon(t)){const s=e.getCellComputedStyle(t);return{svg:(o=s,{name:"CARET_DOWN",width:512,height:512,paths:[{fillColor:o.textColor||N,path:"M120 195 h270 l-135 130"}]}),hoverSvg:zR(s),priority:2,horizontalAlign:"right",size:17,margin:2,position:t,onClick:(e,t)=>{const{col:o,row:s}=e;t.model.selection.selectCell(o,s),t.startCellEdition()},type:"data_validation_list_icon"}}var o})),TV.add("filter_icon",((e,t)=>{if(e.isFilterHeader(t)){const o=e.isFilterActive(t),s=jt(e.getCellComputedStyle(t).fillColor||"#fff")<.45;return{type:"filter_icon",svg:XR(o,s,!1),hoverSvg:XR(o,s,!0),priority:3,horizontalAlign:"right",size:17,margin:2,position:t,onClick:(e,t)=>{const o=t.getStore(jx),s=o.persistentCellPopover;s.isOpen&&s.col===e.col&&s.row===e.row&&"FilterMenu"===s.type?o.close():o.open(e,"FilterMenu")}}}})),TV.add("conditional_formatting",((e,t)=>{const o=e.getConditionalIcon(t);if(o){const s=e.getCellStyle(t);return{type:"conditional_formatting",svg:KR[o].svg,priority:1,horizontalAlign:"left",size:$a(s),margin:4,position:t}}})),TV.add("pivot_collapse",((e,t)=>{if(!e.isSpillPivotFormula(t))return;const o=e.getPivotCellFromPosition(t),s=e.getPivotIdFromPosition(t);if("HEADER"===o.type&&s&&o.domain.length){const i=e.getPivotCoreDefinition(s),n=e.isDashboard(),r="COL"===o.dimension?i.columns:i.rows,a=!n&&o.domain.length!==r.length,l=(i.collapsedDomains?.[o.dimension]??[]).some((e=>mt(e,o.domain))),c="ROW"===o.dimension?15*(o.domain.length-1):0;return{type:"pivot_collapse",priority:4,horizontalAlign:"left",size:a||!n&&"ROW"===o.dimension&&i.rows.length>1?12:0,margin:a?4+c:c,svg:a?YR(l,!1):void 0,hoverSvg:a?YR(l,!0):void 0,position:t,onClick:AV}}}));const DV="0.00%";function _V(e){return class extends e{getters;cache={};rankAsc={};rankDesc={};runningTotal={};runningTotalInPercent={};constructor(e,t){super(e,t),this.getters=t.getters}markAsDirtyForEvaluation(){this.cache={},this.rankAsc={},this.rankDesc={},this.runningTotal={},this.runningTotalInPercent={},super.markAsDirtyForEvaluation?.()}getPivotCellValueAndFormat(e,t){return this.getMeasureDisplayValue(e,t)}_getPivotCellValueAndFormat(e,t){const o=`${e}-${t.map((e=>e.field+"="+e.value)).join(",")}`;if(this.cache[o])return this.cache[o];const s=this.getMeasure(e),i=s.computedBy?this.computeMeasure(s,t):super.getPivotCellValueAndFormat(e,t);return s.format?this.cache[o]={...i,format:s.format}:this.cache[o]=i,this.cache[o]}computeMeasure(e,t){if(!e.computedBy)return{value:0};const{columns:o,rows:s}=super.definition;if(e.aggregator&&o.length+s.length!==t.length){const o=this.getValuesToAggregate(e,t),s=Nc[e.aggregator];if(!s)return{value:0};try{return s([o],this.getters.getLocale())}catch(t){return TS(t,e.aggregator.toUpperCase())}}const i=this.getters.getMeasureCompiledFormula(e),n=this.getters.evaluateCompiledFormula(e.computedBy.sheetId,i,(e=>{const{columns:o,rows:s}=this.definition;if(o.find((t=>t.nameWithGranularity===e))){const{colDomain:o}=NO(this,t),s=o.findIndex((t=>t.field===e));return-1===s?new ai:this.getPivotHeaderValueAndFormat(o.slice(0,s+1))}if(s.find((t=>t.nameWithGranularity===e))){const{rowDomain:o}=NO(this,t),s=o.findIndex((t=>t.field===e));return-1===s?new ai:this.getPivotHeaderValueAndFormat(o.slice(0,s+1))}return this.getPivotCellValueAndFormat(e,t)}));return js(n)?n[0][0]:n}getValuesToAggregate(e,t){const{rowDomain:o,colDomain:s}=NO(this,t),i=super.getExpandedTableStructure(),n=[];if(0===s.length&&o.length<this.definition.rows.length&&this.definition.rows.length&&this.definition.columns.length){const t=this.treeToLeafDomains(i.getColTree()),s=this.getSubTreeMatchingDomain(i.getRowTree(),o),r=this.treeToLeafDomains(s);for(const s of t)for(const t of r)n.push(this._getPivotCellValueAndFormat(e.id,o.concat(t).concat(s)));return n}if(o.length===this.definition.rows.length&&0===s.length){const t=i.getColTree(),r=this.getSubTreeMatchingDomain(t,s),a=this.treeToLeafDomains(r,s);for(const t of a)n.push(this._getPivotCellValueAndFormat(e.id,o.concat(t)));return n}if(o.length===this.definition.rows.length&&s.length&&s.length<this.definition.columns.length){const t=this.getSubTreeMatchingDomain(i.getColTree(),s),r=this.treeToLeafDomains(t,s);for(const t of r)n.push(this._getPivotCellValueAndFormat(e.id,o.concat(t)));return n}{const t=i.getRowTree(),r=this.getSubTreeMatchingDomain(t,o),a=this.treeToLeafDomains(r,o);for(const t of a)n.push(this._getPivotCellValueAndFormat(e.id,t.concat(s)));return n}}getSubTreeMatchingDomain(e,t,o=0){if(o>t.length)return[];if(t.length===o)return e;for(const s of e){const e=Gc(this.definition.getDimension(s.field),t[o]?.value);if(s.field===t[o]?.field&&s.value===e)return this.getSubTreeMatchingDomain(s.children,t,o+1)}return[]}treeToLeafDomains(e,t=[]){const o=[];for(const s of e){const e=this.definition.getDimension(s.field),i=[...t,{field:s.field,value:s.value,type:e.type}];0===s.children.length?o.push(i):o.push(...this.treeToLeafDomains(s.children,i))}return o}getMeasureDisplayValue(e,t){const o=this.getMeasure(e),s=this._getPivotCellValueAndFormat(e,t);if(!o.display||"no_calculations"===o.display.type||s.message)return s;const i=o.display.fieldNameWithGranularity;if(i&&!this.isFieldInPivot(i))return{value:ti.NotAvailable,message:Ho('Field "%s" not found in pivot for measure display calculation',i)};try{const e=o.display;switch(e.type){case"%_of_grand_total":return this.asPercentOfGrandTotal(s,o);case"%_of_col_total":return this.asPercentOfColumnTotal(s,o,t);case"%_of_row_total":return this.asPercentOfRowTotal(s,o,t);case"%_of_parent_row_total":return this.asPercentOfParentRowTotal(s,o,t);case"%_of_parent_col_total":return this.asPercentOfParentColumnTotal(s,o,t);case"index":return this.asIndex(s,o,t);case"%_of_parent_total":return this.asPercentOfParentTotal(s,o,t,e);case"running_total":return this.asRunningTotal(s,o,t,e,"running_total");case"%_running_total":return this.asRunningTotal(s,o,t,e,"%_running_total");case"rank_asc":return this.asRank(s,o,t,e,"asc");case"rank_desc":return this.asRank(s,o,t,e,"desc");case"%_of":return this.asPercentOf(s,o,t,e);case"difference_from":return this.asDifferenceFrom(s,o,t,e);case"%_difference_from":return this.asDifferenceFromInPercent(s,o,t,e)}return s}catch(e){return TS(e,"COMPUTE_MEASURE_DISPLAY_VALUE")}}asPercentOfGrandTotal(e,t){const o=this.getGrandTotal(t.id);return 0===o?{value:ti.DivisionByZero}:{value:this.measureValueToNumber(e)/o,format:DV}}asPercentOfRowTotal(e,t,o){const s=this.getRowTotal(t.id,o);return 0===s?{value:ti.DivisionByZero}:{value:this.measureValueToNumber(e)/s,format:DV}}asPercentOfColumnTotal(e,t,o){const s=this.getColumnTotal(t.id,o);return 0===s?{value:ti.DivisionByZero}:{value:this.measureValueToNumber(e)/s,format:DV}}asPercentOfParentRowTotal(e,t,o){const s=function(e,t){const{colDomain:o,rowDomain:s}=NO(e,t);return[...o,...s.slice(0,s.length-1)]}(this,o),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,s));return 0===i?{value:""}:{value:this.measureValueToNumber(e)/i,format:DV}}asPercentOfParentColumnTotal(e,t,o){const s=function(e,t){const{colDomain:o,rowDomain:s}=NO(e,t);return[...o.slice(0,o.length-1),...s]}(this,o),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,s));return 0===i?{value:""}:{value:this.measureValueToNumber(e)/i,format:DV}}asPercentOfParentTotal(e,t,o,s){const{fieldNameWithGranularity:i}=s;if(!i)return e;if(!UO(i,o))return{value:""};const n=function(e,t,o){let{rowDomain:s,colDomain:i}=NO(e,o);if("row"===BO(e,t)){const e=s.findIndex((e=>e.field===t));if(-1===e)return o;s=s.slice(0,e+1)}else{const e=i.findIndex((e=>e.field===t));if(-1===e)return o;i=i.slice(0,e+1)}return[...s,...i]}(this,i,o),r=this._getPivotCellValueAndFormat(t.id,n),a=this.measureValueToNumber(r);return 0===a?{value:""}:{value:this.measureValueToNumber(e)/a,format:DV}}asIndex(e,t,o){const s=this.measureValueToNumber(e),i=this.getRowTotal(t.id,o),n=this.getColumnTotal(t.id,o),r=this.getGrandTotal(t.id);return 0===i||0===n?{value:ti.DivisionByZero}:{value:s*r/(n*i),format:void 0}}asRunningTotal(e,t,o,s,i){const{fieldNameWithGranularity:n}=s;if(!n)return e;const r="running_total"===i?this.runningTotal:this.runningTotalInPercent;let a=r[t.id]?.[n];a||(a=this.computeRunningTotal(t,n,i),r[t.id]||(r[t.id]={}),r[t.id][n]=a);const{rowDomain:l,colDomain:c}=NO(this,o),h=zO(c),d=zO(l),u=a[h]?.[d];return{value:u??"",format:"running_total"===i?e.format:DV}}asPercentOf(e,t,o,s){const{fieldNameWithGranularity:i,value:n}=s;if(void 0===n||!i)return e;if(!UO(i,o))return{value:""};const r=this.getComparisonValue(t,o,i,n),a=this.strictMeasureValueToNumber(e);return 0===r||"sameValue"===r&&0===a?{value:ti.DivisionByZero}:!r||"sameValue"===r&&!a?{value:""}:"sameValue"===r?{value:1,format:DV}:void 0===a?{value:ti.NullError}:{value:a/r,format:DV}}asDifferenceFrom(e,t,o,s){const{fieldNameWithGranularity:i,value:n}=s;if(void 0===n||!i)return e;if(!UO(i,o))return{value:""};const r=this.getComparisonValue(t,o,i,n)||0;return"sameValue"===r?{value:""}:{value:this.measureValueToNumber(e)-r,format:e.format}}asDifferenceFromInPercent(e,t,o,s){const{fieldNameWithGranularity:i,value:n}=s;if(void 0===n||!i)return e;if(!UO(i,o))return{value:""};const r=this.getComparisonValue(t,o,i,n),a=this.strictMeasureValueToNumber(e);return 0===r?{value:ti.DivisionByZero}:r&&"sameValue"!==r?void 0===a?{value:ti.NullError}:{value:(a-r)/r,format:DV}:{value:""}}asRank(e,t,o,s,i){const{fieldNameWithGranularity:n}=s;if(!n)return e;if(!UO(n,o))return{value:""};const r="asc"===i?this.rankAsc:this.rankDesc;let a=r[t.id]?.[n];a||(a=this.computeRank(t,n,i),r[t.id]||(r[t.id]={}),r[t.id][n]=a);const{rowDomain:l,colDomain:c}=NO(this,o),h=zO(c),d=zO(l),u=a[h]?.[d];return{value:u??""}}computeRank(e,t,o){const s={},i=BO(this,t),n="row"===i?"column":"row";let r=this.getPivotValueCells(e.id);"column"===i&&(r=Vi(r));for(const a of r){const r=zO(kO(this,n,a[0].domain)),l=a.map((t=>({...t,value:this.strictMeasureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain)),rowDomain:kO(this,i,t.domain)}))).filter((e=>UO(t,e.rowDomain))),c=Object.groupBy(l,(e=>GO(e.rowDomain,t)));for(const e in c)c[e]=Nt(c[e]||[],(e=>e.value)).filter((e=>void 0!==e.value)).sort(((e,t)=>"asc"===o?e.value-t.value:t.value-e.value));s[r]={};for(const e of l){const o=zO(kO(this,i,e.domain)),n=c[GO(e.rowDomain,t)];if(!n)continue;const a=n.findIndex((t=>t.value===e.value));-1!==a&&(s[r][o]=a+1)}}return"row"===i?s:kt(s)}computeRunningTotal(e,t,o){const s={},i=BO(this,t),n="row"===i?"column":"row";let r=this.getPivotValueCells(e.id);"column"===i&&(r=Vi(r));for(const a of r){const r=zO(kO(this,n,a[0].domain));s[r]={};const l={},c=a.map((t=>({...t,rowDomain:kO(this,i,t.domain),value:this.measureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain))}))).filter((e=>UO(t,e.rowDomain)));for(const e of c){const o=zO(e.rowDomain),i=WO(e.rowDomain,t),n=(l[i]||0)+e.value;l[i]=n,s[r][o]=n}if("%_running_total"===o)for(const e of c){const o=e.rowDomain,i=zO(o),n=WO(o,t),a=s[r][i]||0,c=l[n];s[r][i]=c?a/c:void 0}}return"row"===i?s:kt(s)}getGrandTotal(e){const t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){const o=NO(this,t).rowDomain,s=this._getPivotCellValueAndFormat(e,o);return this.measureValueToNumber(s)}getColumnTotal(e,t){const o=NO(this,t).colDomain,s=this._getPivotCellValueAndFormat(e,o);return this.measureValueToNumber(s)}isFieldInPivot(e){return this.definition.columns.some((t=>t.nameWithGranularity===e))||this.definition.rows.some((t=>t.nameWithGranularity===e))}getComparisonValue(e,t,o,s){const i=s===PO||s===MO?function(e,t,o,s){const i=BO(e,o),n="row"===i?e.getExpandedTableStructure().getRowTree():e.getExpandedTableStructure().getColTree(),r=LO(kO(e,i,t),n,o),a=r?.map((e=>e.value))??[],l=function(e,t){const o=t.find((t=>t.field===e));return o?.value}(o,t);if(void 0===l)return;const c=a.indexOf(l);if(void 0===l||-1===c)return;return HO(t,o,a[Ze(c+(s===PO?-1:1),0,a.length-1)])}(this,t,o,s):HO(t,o,s);if(mt(i,t))return"sameValue";if(!i||!function(e,t){for(const o of t)if(void 0===e.definition.rows.find((e=>e.nameWithGranularity===o.field))&&void 0===e.definition.columns.find((e=>e.nameWithGranularity===o.field)))return!1;const{rowDomain:o,colDomain:s}=NO(e,t);return VO(o,e.getExpandedTableStructure().getRowTree())&&VO(s,e.getExpandedTableStructure().getColTree())}(this,i))throw new ai;const n=this._getPivotCellValueAndFormat(e.id,i);return this.strictMeasureValueToNumber(n)}getPivotValueCells(e){return this.getCollapsedTableStructure().getPivotCells().map((t=>t.filter((t=>"VALUE"===t.type&&t.measure===e)))).filter((e=>e.length>0))}measureValueToNumber(e){if("number"==typeof e.value)return e.value;if(!e.value)return 0;throw new Error(`Value ${e.value} is not a number`)}strictMeasureValueToNumber(e){if("number"==typeof e.value)return e.value;if(e.value)throw new Error(`Value ${e.value} is not a number`)}getCollapsedTableStructure(){const e=super.getCollapsedTableStructure();return this.sortTableStructure(e),e}getExpandedTableStructure(){const e=super.getExpandedTableStructure();return this.sortTableStructure(e),e}sortTableStructure(e){if(!this.definition.sortedColumn||e.isSorted)return;const t=this.definition.sortedColumn.measure;Kc(this.definition.sortedColumn,this)&&e.sort(t,this.definition.sortedColumn,((e,t)=>this._getPivotCellValueAndFormat(e,t)))}}}const OV=["ADD_PIVOT","UPDATE_PIVOT","REMOVE_PIVOT"];function FV(e){return OV.includes(e.type)}const PV=new n;PV.add("ALPHANUMERIC_INCREMENT_MODIFIER",{apply:(e,t)=>{e.current+=e.increment;const o=`${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:o},tooltip:{props:{content:o}}}}}).add("INCREMENT_MODIFIER",{apply:(e,t,o)=>{e.current+=e.increment;const s=e.current.toString(),i=o.getLocale(),n=In(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:s},tooltip:s?{props:{content:n}}:void 0}}}).add("DATE_INCREMENT_MODIFIER",{apply:(e,t,o)=>{const s=Ri(e.current,o.getLocale());s.setFullYear(s.getFullYear()+e.increment.years||0),s.setMonth(s.getMonth()+e.increment.months||0),s.setDate(s.getDate()+e.increment.days||0);const i=ps(s);e.current=i;const n=o.getLocale(),r=In(i,{format:t.cell?.format,locale:n});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:i.toString()},tooltip:i?{props:{content:r}}:void 0}}}).add("COPY_MODIFIER",{apply:(e,t,o)=>{const s=t.cell?.content||"",i={locale:o.getLocale(),format:t.cell?.format};return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:s},tooltip:s?{props:{content:t.cell?Xn(t.cell,i).formattedValue:""}}:void 0}}}).add("FORMULA_MODIFIER",{apply:(e,t,o,s)=>{e.current+=e.increment;let i=0,n=0;switch(s){case"up":i=0,n=-e.current;break;case"down":i=0,n=e.current;break;case"left":i=-e.current,n=0;break;case"right":i=e.current,n=0}const r=t.cell;if(!r||!r.isFormula)return{cellData:{}};const a=t.sheetId,l=o.getTranslatedCellFormula(a,i,n,r.compiledFormula.tokens);return{cellData:{border:t.border,style:r.style,format:r.format,content:l},tooltip:l?{props:{content:l}}:void 0}}});const MV=new n,NV=/(\d+)$/,kV=/^(.*\D+)/,VV=/^(.*\D+)(\d+)$/;function LV(e,t,o){let s=[],i=!1;for(const n of t){n===e&&(i=!0);const t=void 0===n||n.isFormula?void 0:Xn(n,{locale:qs,format:n.format});if(t&&o(t))s.push(t);else{if(i)return s;s=[]}}return s}function HV(e){let t=1;return e.length>=2&&(t=function(e){const t=[];let o=e[0];for(let s=1;s<e.length;s++){const i=e[s];t.push(i-o),o=i}return t.reduce(((e,t)=>e+t),0)/t.length}(e)*e.length),t}function UV(e){if(e.length<2)return 1;const t=e.map((e=>Ri(e,qs))),o=function(e){if(e.length<2)return[{years:0,months:0,days:0}];const t=e.map(((t,o)=>{if(0===o)return{years:0,months:0,days:0};const s=Yo.fromTimestamp(e[o-1].getTime()),i=ws(s,t),n=Cs(s,t)%12;s.setFullYear(s.getFullYear()+i),s.setMonth(s.getMonth()+n);return{years:i,months:n,days:ys(s,t)}}));return t.slice(1)}(t),s=(i=o).length<2?i[0]||{years:0,months:0,days:0}:i.every((e=>e.years===i[0].years&&e.months===i[0].months&&e.days===i[0].days))?i[0]:void 0;var i;if(void 0===s)return;const n=1===Object.values(s).filter((e=>0!==e)).length,r=Object.values(s).every((e=>0===e));if(!n||r){const o=t.map(((e,o)=>{if(0===o)return 0;const s=t[o-1];return Math.floor(e.getTime())-Math.floor(s.getTime())})).slice(1);if(o.every((e=>e===o[0])))return e.length*(e[1]-e[0])}return{years:s.years*e.length,months:s.months*e.length,days:s.days*e.length}}MV.add("simple_value_copy",{condition:(e,t)=>!(1!==t.length||e.isFormula||e.format&&On(e.format)),generateRule:()=>({type:"COPY_MODIFIER"}),sequence:10}).add("increment_alphanumeric_value",{condition:e=>!e.isFormula&&Xn(e,{locale:qs}).type===_s.text&&VV.test(e.content),generateRule:(e,t,o)=>{const s=parseInt(e.content.match(NV)[0]),i=e.content.match(kV)[0],n=e.content.length-i.length,r=LV(e,t,(e=>e.type===_s.text&&VV.test(e.value))).filter((e=>i===(e.value??"").toString().match(kV)[0])).map((e=>parseInt((e.value??"").toString().match(NV)[0])));let a=HV(r);return["up","left"].includes(o)&&1===r.length&&(a=-a),{type:"ALPHANUMERIC_INCREMENT_MODIFIER",prefix:i,current:s,increment:a,numberPostfixLength:n}},sequence:15}).add("copy_text",{condition:e=>!e.isFormula&&Xn(e,{locale:qs}).type===_s.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&&Xn(e,{locale:qs}).type===_s.number&&!!e.format&&On(e.format),generateRule:(e,t)=>{const o=UV(LV(e,t,(e=>e.type===_s.number&&!!e.format&&On(e.format))).map((e=>Number(e.value))));if(void 0===o)return{type:"COPY_MODIFIER"};const s=Xn(e,{locale:qs});return"object"==typeof o?{type:"DATE_INCREMENT_MODIFIER",increment:o,current:s.type===_s.number?s.value:0}:{type:"INCREMENT_MODIFIER",increment:o,current:s.type===_s.number?s.value:0}},sequence:25}).add("increment_number",{condition:e=>!e.isFormula&&Xn(e,{locale:qs}).type===_s.number,generateRule:(e,t,o)=>{const s=LV(e,t,(e=>e.type===_s.number&&!On(e.format||""))).map((e=>Number(e.value)));let i=HV(s);["up","left"].includes(o)&&1===s.length&&(i=-i);const n=Xn(e,{locale:qs});return{type:"INCREMENT_MODIFIER",increment:i,current:n.type===_s.number?n.value:0}},sequence:40});class BV extends Mk{static layers=[];getters;ui;selection;dispatch;canDispatch;constructor({getters:e,stateObserver:t,dispatch:o,canDispatch:s,uiActions:i,selection:n}){super(t),this.getters=e,this.ui=i,this.selection=n,this.dispatch=o,this.canDispatch=s}drawLayer(e,t){}}class zV{cells;getters;index=0;direction;constructor(e,t,o){this.cells=e,this.getters=t,this.direction=o}next(){const e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:o,tooltip:s}=PV.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:o,tooltip:s,origin:{col:e.data.col,row:e.data.row}}}}const $V=new class extends n{addTransformation(e,t,o){this.content[e]||(this.content[e]=new Map);for(const s of t)this.content[e].set(s,o);return this}getTransformation(e,t){return this.content[t]&&this.content[t].get(e)}};const GV=new class extends n{add(e,t){return super.add(e,t),this}replace(e,t){return super.replace(e,t),this}get(e){return this.content[e]}};function WV(e,t){if("SPREADSHEET"!==e.pivot.type)return e;if(e.pivot.dataSet?.sheetId!==t.sheetId)return e;const o=th(e.pivot.dataSet.zone,t),s=o?{...e.pivot.dataSet,zone:o}:void 0;return{...e,pivot:{...e.pivot,dataSet:s}}}function qV(e,t){if(e.sheetId!==t.sheetId)return e;if(("FREEZE_COLUMNS"===e.type?"COL":"ROW")!==t.dimension)return e;let o=e.quantity;if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));for(const t of e)o>t&&o--}if("ADD_COLUMNS_ROWS"===t.type){o=o>("before"===t.position?t.base-1:t.base)?o+t.quantity:o}return o>0?{...e,quantity:o}:void 0}function ZV(e,t){if(e.sheetId!==t.sheetId)return e;const o=th(e.zone,t);if(!o)return;const s=e.newTableRange?oh(e.newTableRange,t):void 0;return{...e,newTableRange:s,zone:o}}function jV(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let o;if("REMOVE_COLUMNS_ROWS"===t.type)o=ha(t.elements,[e.base])[0];else if("ADD_COLUMNS_ROWS"===t.type){o=ca(pt(t.position,t.base),t.quantity,[e.base])[0]}return void 0!==o?{...e,base:o}:void 0}function YV(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;const o=je(e.start,e.end+1);let s=[];if("REMOVE_COLUMNS_ROWS"===t.type)s=ha(t.elements,o);else if("ADD_COLUMNS_ROWS"===t.type){s=ca(pt(t.position,t.base),t.quantity,o)}return 0!==s.length?{...e,start:Math.min(...s),end:Math.max(...s)}:void 0}function XV(e,t){return(e=ze(e)).pivot.measures.map((e=>{e.computedBy&&(e.computedBy.formula=WS(e.computedBy.sheetId,e.computedBy.formula,t))})),e}function KV(e,t){return{...e,definition:hx(e.sheetId,e.definition,t)}}$V.addTransformation("ADD_COLUMNS_ROWS",["ADD_COLUMNS_ROWS"],jV),$V.addTransformation("REMOVE_COLUMNS_ROWS",["ADD_COLUMNS_ROWS"],jV),$V.addTransformation("DELETE_SHEET",["MOVE_RANGES"],(function(e,t){const o=t.sheetId;if(e.targetSheetId===o||e.sheetId===o)return;return e})),$V.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART"],(function(e,t){if(e.figureId===t.figureId)return;return e})),$V.addTransformation("CREATE_SHEET",["CREATE_SHEET"],(function(e,t){e.sheetId===t.sheetId&&(e={...e,sheetId:`${e.sheetId}~`});if(e.name===t.name)return{...e,name:e.name?.match(/\d+/)?e.name.replace(/\d+/,(e=>(parseInt(e)+1).toString())):`${e.name}~`,position:e.position+1};return e})),$V.addTransformation("ADD_MERGE",["ADD_MERGE","REMOVE_MERGE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;const o=[];for(const s of e.target)t.target.every((e=>!xr(s,e)))&&o.push(s);if(o.length)return{...e,target:o};return})),$V.addTransformation("ADD_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],qV),$V.addTransformation("REMOVE_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],qV),$V.addTransformation("ADD_COLUMNS_ROWS",["UPDATE_TABLE"],ZV),$V.addTransformation("REMOVE_COLUMNS_ROWS",["UPDATE_TABLE"],ZV),$V.addTransformation("REMOVE_TABLE_STYLE",["CREATE_TABLE","UPDATE_TABLE"],(function(e,t){if(e.config?.styleId!==t.tableStyleId)return e;return{...e,config:{...e.config,styleId:wR.styleId}}})),$V.addTransformation("ADD_COLUMNS_ROWS",["GROUP_HEADERS","UNGROUP_HEADERS","FOLD_HEADER_GROUP","UNFOLD_HEADER_GROUP"],YV),$V.addTransformation("REMOVE_COLUMNS_ROWS",["GROUP_HEADERS","UNGROUP_HEADERS","FOLD_HEADER_GROUP","UNFOLD_HEADER_GROUP"],YV),$V.addTransformation("REMOVE_PIVOT",["RENAME_PIVOT","DUPLICATE_PIVOT","INSERT_PIVOT","UPDATE_PIVOT"],(function(e,t){if(e.pivotId===t.pivotId)return;return e})),$V.addTransformation("DELETE_SHEET",["ADD_PIVOT","UPDATE_PIVOT"],(function(e,t){if("SPREADSHEET"!==e.pivot.type)return e;if(e.pivot.dataSet?.sheetId===t.sheetId)return{...e,pivot:{...e.pivot,dataSet:void 0}};return e})),$V.addTransformation("ADD_COLUMNS_ROWS",["ADD_PIVOT","UPDATE_PIVOT"],WV),$V.addTransformation("REMOVE_COLUMNS_ROWS",["ADD_PIVOT","UPDATE_PIVOT"],WV),GV.add("UPDATE_CELL",(function(e,t){const o=e.content&&WS(e.sheetId,e.content,t);return{...e,content:o}})),GV.add("ADD_CONDITIONAL_FORMAT",(function(e,t){const o=e.cf.rule;if(e={...e,cf:{...e.cf}},"CellIsRule"===o.type)e.cf.rule={...o,values:o.values.map((o=>WS(e.sheetId,o,t)))};else if("ColorScaleRule"===o.type){const{minimum:s,maximum:i,midpoint:n}=o;e.cf.rule={...o,minimum:{...s,value:s.value&&WS(e.sheetId,s.value,t)},maximum:{...i,value:i.value&&WS(e.sheetId,i.value,t)},midpoint:n?{...n,value:WS(e.sheetId,n.value,t)}:void 0}}else if("IconSetRule"===o.type){const{upperInflectionPoint:s,lowerInflectionPoint:i}=o;e.cf.rule={...o,upperInflectionPoint:{...s,value:WS(e.sheetId,s.value,t)},lowerInflectionPoint:{...i,value:WS(e.sheetId,i.value,t)}}}else"DataBarRule"===o.type&&(e.cf.rule={...o,rangeValues:o.rangeValues?qS(e.sheetId,o.rangeValues,t):void 0});return e})),GV.add("ADD_DATA_VALIDATION_RULE",(function(e,t){return(e={...e,rule:{...e.rule,criterion:{...e.rule.criterion}}}).rule.criterion.values=e.rule.criterion.values.map((o=>WS(e.sheetId,o,t))),e})),GV.add("ADD_PIVOT",XV),GV.add("UPDATE_PIVOT",XV),GV.add("CREATE_CHART",KV),GV.add("UPDATE_CHART",KV);const JV=[{match:function(e){return"sheetId"in e},fn:tL},{match:function(e){return"target"in e&&"sheetId"in e},fn:function(e,t){const o=tL(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;const s=[];for(const o of e.target){const e=th(o,t);e&&s.push(e)}if(!s.length)return"IGNORE_COMMAND";return{...e,target:s}}},{match:function(e){return"sheetId"in e&&"zone"in e},fn:function(e,t){const o=tL(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;const s=th(e.zone,t);if(s)return{...e,zone:s};return"IGNORE_COMMAND"}},{match:function(e){return"col"in e&&"row"in e&&"sheetId"in e},fn:function(e,t){const o=tL(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type)return function(e,t){const o="COL"===t.dimension?"col":"row";let s=e[o];if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));if(e.includes(s))return"IGNORE_COMMAND";for(const t of e)s>=t&&s--}"ADD_COLUMNS_ROWS"===t.type&&(s>t.base||s===t.base&&"before"===t.position)&&(s+=t.quantity);return{...e,[o]:s}}(e,t);if("ADD_MERGE"===t.type)return function(e,t){for(const o of t.target){if(!(e.col===o.left&&e.row===o.top)&&Er(e.col,e.row,o))return"IGNORE_COMMAND"}return e}(e,t);return"SKIP_TRANSFORMATION"}},{match:function(e){return"dimension"in e&&"sheetId"in e&&"elements"in e},fn:function(e,t){const o=tL(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"!==t.type&&"REMOVE_COLUMNS_ROWS"!==t.type)return"SKIP_TRANSFORMATION";if(t.dimension!==e.dimension)return e;let s=[];if("REMOVE_COLUMNS_ROWS"===t.type)s=ha(t.elements,e.elements);else if("ADD_COLUMNS_ROWS"===t.type){s=ca(pt(t.position,t.base),t.quantity,e.elements)}if(0===s.length)return"IGNORE_COMMAND";return{...e,elements:s}}},{match:function(e){return"ranges"in e},fn:function(e,t){if(!("sheetId"in t))return e;const o=e.ranges.map((e=>oh(e,t))).filter(lt);if(!o.length)return"IGNORE_COMMAND";return{...e,ranges:o}}}];function QV(e,t){const o=$V.getTransformation(e.type,t.type),s=o?o(e,t):function(e,t){for(const{match:o,fn:s}of JV)if(o(e)){const o=s(e,t);if("SKIP_TRANSFORMATION"===o)continue;if("IGNORE_COMMAND"===o)return;e=o}return e}(e,t);return s?function(e,t){const o=GV.get(e.type);if(!o)return e;const s=Ia(t);if(s)return o(e,s);return e}(s,t):s}function eL(e,t){let o=[...e];const s=new Set($V.getKeys());for(const e of t)(s.has(e.type)||xa.contains(e.type))&&(o=o.reduce(((t,o)=>{const s=QV(o,e);return s&&t.push(s),t}),[]));return o}function tL(e,t){if(!("sheetId"in t))return e;const o="DELETE_SHEET"===t.type&&t.sheetId;return e.sheetId===o?"IGNORE_COMMAND":"CREATE_SHEET"===e.type||"CREATE_SHEET"===t.type||e.sheetId!==t.sheetId?e:"SKIP_TRANSFORMATION"}class oL{rootCommand;timestamp;id;clientId;_commands=[];_changes=[];constructor(e,t,o,s,i,n){this.rootCommand=s,this.timestamp=n,this.id=e,this.clientId=t,this._commands=[...o],this._changes=i?[...i]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}}class sL extends Error{}class iL extends sh{revisions;transportService;serverRevisionId;clients={};clientId="local";debouncedMove;pendingMessages=[];awaitingClientPosition;waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;uuidGenerator=new Ka;lastLocalOperation;constructor(e,t,o=Se){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=o,this.debouncedMove=ht(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,o){if(!t.length||!o.length||!this.canApplyOptimisticUpdate())return;const s=new oL(this.uuidGenerator.uuidv4(),this.clientId,t,e,o,Date.now());this.revisions.append(s.id,s),"REQUEST_REDO"!==e.type&&(this.lastLocalOperation=s),this.trigger("new-local-state-update",{id:s.id}),this.sendUpdateMessage({type:"REMOTE_REVISION",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:s.id,clientId:s.clientId,commands:s.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:"REVISION_UNDONE",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:"REVISION_REDONE",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}move(e){this.debouncedMove(e)}join(e){e?(this.clients[e.id]=e,this.clientId=e.id):(this.clients.local={id:"local",name:"local"},this.clientId="local"),this.transportService.onNewMessage(this.clientId,this.onMessageReceived.bind(this)),this.awaitingClientPosition&&(this._move(this.awaitingClientPosition),this.awaitingClientPosition=void 0)}loadInitialMessages(e){const t=performance.now(),o=e.reduce(((e,t)=>e+("REMOTE_REVISION"===t.type?t.commands.length:1)),0);this.isReplayingInitialRevisions=!0;for(const t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1,console.debug("Replayed",o,"commands in",performance.now()-t,"ms")}async leave(e){e&&1===Object.keys(this.clients).length&&this.lastRevisionMessage&&"SNAPSHOT_CREATED"!==this.lastRevisionMessage?.type&&await this.snapshot(e()),delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.transportService.sendMessage({type:"CLIENT_LEFT",clientId:this.clientId,version:1})}async snapshot(e){if(0!==this.pendingMessages.length)return;const t=this.uuidGenerator.uuidv4();await this.transportService.sendMessage({type:"SNAPSHOT",nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getCurrentClient(){return this.getClient(this.clientId)}getClient(e){const t=this.clients[e];if(!t)throw new sL("The client left the session");return t}getConnectedClients(){return new Set(Object.values(this.clients).filter(lt))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return 0===this.pendingMessages.length}getLastLocalNonEmptyRevision(){return this.lastLocalOperation}_move(e){if(!this.clients[this.clientId])return void(this.awaitingClientPosition=e);const t=this.clients[this.clientId]?.position;if(t?.col===e.col&&t.row===e.row&&t.sheetId===e.sheetId)return;const o=t?"CLIENT_MOVED":"CLIENT_JOINED",s=this.getCurrentClient();this.clients[this.clientId]={...s,position:e},this.transportService.sendMessage({type:o,version:1,client:{...s,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e))if(this.isWrongServerRevisionId(e))this.trigger("unexpected-revision-id");else{switch(e.type){case"CLIENT_MOVED":this.onClientMoved(e);break;case"CLIENT_JOINED":this.onClientJoined(e);break;case"CLIENT_LEFT":this.onClientLeft(e);break;case"REVISION_REDONE":this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-redone",{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case"REVISION_UNDONE":this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-undone",{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case"REMOTE_REVISION":const{clientId:t,commands:o,timestamp:s}=e,i=new oL(e.nextRevisionId,t,o,void 0,void 0,s);if(i.clientId!==this.clientId){this.revisions.insert(i.id,i,e.serverRevisionId);const t=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.commands)).flat();this.trigger("remote-revision-received",{commands:eL(o,t)})}break;case"SNAPSHOT_CREATED":{const t=new oL(e.nextRevisionId,"server",[],void 0,void 0,Date.now());this.revisions.insert(t.id,t,e.serverRevisionId),this.dropPendingHistoryMessages(),this.trigger("snapshot"),this.lastLocalOperation=void 0;break}}this.acknowledge(e),this.trigger("collaborative-event-received")}}onClientMoved(e){e.client.id!==this.clientId&&(this.clients[e.client.id]=e.client)}onClientJoined(e){if(e.client.id!==this.clientId){this.clients[e.client.id]=e.client;const t=this.clients[this.clientId];if(t){const{position:e}=t;e&&this.transportService.sendMessage({type:"CLIENT_MOVED",version:1,client:{...t,position:e}})}}}onClientLeft(e){e.clientId!==this.clientId&&delete this.clients[e.clientId]}sendUpdateMessage(e){this.pendingMessages.push(e),this.waitingAck||this.sendPendingMessage()}sendPendingMessage(){let e=this.pendingMessages[0];if(e){if("REMOTE_REVISION"===e.type){let t=this.revisions.get(e.nextRevisionId);0===t.commands.length&&(this.revisions.rebase(t.id),t=this.revisions.get(e.nextRevisionId)),e={...e,clientId:t.clientId,commands:t.commands}}if(this.isReplayingInitialRevisions)throw new Error(`Trying to send a new revision while replaying initial revision. This can lead to endless dispatches every time the spreadsheet is open.\n ${JSON.stringify(e)}`);this.waitingAck=!0,this.transportService.sendMessage({...e,serverRevisionId:this.serverRevisionId})}}acknowledge(e){switch("REVISION_UNDONE"!==e.type&&"REVISION_REDONE"!==e.type||(this.waitingUndoRedoAck=!1),e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"SNAPSHOT_CREATED":this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter((t=>t.nextRevisionId!==e.nextRevisionId)),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.lastRevisionMessage=e,this.sendPendingMessage();break;case"REVISION_UNDONE":{this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter((t=>t.nextRevisionId!==e.nextRevisionId));const t=this.pendingMessages.findIndex((e=>"REMOTE_REVISION"===e.type));-1!==t&&this.revisions.rebase(this.pendingMessages[t].nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.sendPendingMessage();break}}}isAlreadyProcessed(e){if("CLIENT_MOVED"===e.type&&e.client.id===this.clientId)return!0;switch(e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":case"SNAPSHOT_CREATED":return this.processedRevisions.has(e.nextRevisionId);default:return!1}}isWrongServerRevisionId(e){switch(e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":case"SNAPSHOT_CREATED":return e.serverRevisionId!==this.serverRevisionId;default:return!1}}dropPendingHistoryMessages(){this.waitingUndoRedoAck=!1,this.pendingMessages=this.pendingMessages.filter((({type:e})=>"REVISION_REDONE"!==e&&"REVISION_UNDONE"!==e))}}const nL=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 rL(e){return nL.has(e.type)}const aL=[lL,function(e,t){return"target"in t&&Array.isArray(t.target)?{...ze(t),target:e.getSelectedZones()}:t},hL,function(e,t){return"ranges"in t?{...ze(t),ranges:e.getSelectedZones().map((t=>e.getRangeDataFromZone(e.getActiveSheetId(),t)))}:t}];function lL(e,t){return"sheetId"in t?{...ze(t),sheetId:e.getActiveSheetId()}:t}function cL(e,t){return"zone"in t?{...ze(t),zone:e.getSelectedZone()}:t}function hL(e,t){if(!("row"in t)||!("col"in t))return t;const{col:o,row:s}=e.getActivePosition();return{...ze(t),col:o,row:s}}const dL=new Ka;function uL(e,t){const o=e.getSelectedZone();return{...lL(e,t),elements:"COL"===t.dimension?je(o.left,o.right+1):je(o.top,o.bottom+1)}}function gL(e,t){const o=e.getSelectedZone();return{...ze(t),zone:o}}function pL(e,t){const o=ze(t),s=e.getSelectedZone(),{top:i,bottom:n,left:r,right:a}=s;return"cols"in o?o.cols=je(r,a+1):"rows"in o&&(o.rows=je(i,n+1)),o}function mL(e,t){const o=e.getSelectedZone();return{...lL(e,t),start:"COL"===t.dimension?o.left:o.top,end:"COL"===t.dimension?o.right:o.bottom}}const fL=new n;fL.add("UPDATE_CELL",bL),fL.add("CLEAR_CELL",bL),fL.add("CLEAR_CELLS",bL),fL.add("DELETE_CONTENT",bL),fL.add("ADD_MERGE",bL),fL.add("REMOVE_MERGE",bL),fL.add("SET_FORMATTING",bL),fL.add("CLEAR_FORMATTING",bL),fL.add("SET_BORDER",bL),fL.add("CREATE_TABLE",bL),fL.add("REMOVE_TABLE",bL),fL.add("HIDE_SHEET",bL),fL.add("ADD_COLUMNS_ROWS",(function(e,t){const o=e.getActivePosition();return{...lL(e,t),base:"COL"===t.dimension?o.col:o.row}})),fL.add("REMOVE_COLUMNS_ROWS",uL),fL.add("HIDE_COLUMNS_ROWS",uL),fL.add("RESIZE_COLUMNS_ROWS",uL),fL.add("CREATE_SHEET",(function(e,t){const o=ze(t);o.sheetId=dL.smallUuid();const s=t.name||e.getSheet(e.getActiveSheetId()).name,i=s.match(/(.+?)\d*$/)?.[1]||s;return o.name=e.getNextSheetName(i),o})),fL.add("CREATE_FIGURE",(function(e,t){const o=hL(e,lL(e,t));return o.figureId=dL.smallUuid(),o})),fL.add("CREATE_CHART",(function(e,t){return{...lL(e,t),figureId:dL.smallUuid()}})),fL.add("CREATE_IMAGE",(function(e,t){return{...lL(e,t),figureId:dL.smallUuid()}})),fL.add("GROUP_HEADERS",mL),fL.add("UNGROUP_HEADERS",mL),fL.add("UNFOLD_HEADER_GROUPS_IN_ZONE",cL),fL.add("FOLD_HEADER_GROUPS_IN_ZONE",cL);const vL=new n;function bL(e,t){let o=ze(t);for(const t of aL)o=t(e,o);return o}function SL(e,t){if(e.rootCommand&&"object"==typeof e.rootCommand)return Hs(e.rootCommand)?function(e,t){if(!t)return;if(!fL.contains(t.type))return;return fL.get(t.type)(e,t)}(t,e.rootCommand):function(e,t,o){if(!vL.contains(t.type))return;return vL.get(t.type)(e,t,o)}(t,e.rootCommand,e.commands)}vL.add("PASTE",(function(e,t){return{type:"REPEAT_PASTE",pasteOption:ze(t.pasteOption),target:e.getSelectedZones()}})),vL.add("INSERT_CELL",gL),vL.add("DELETE_CELL",gL),vL.add("AUTORESIZE_COLUMNS",pL),vL.add("AUTORESIZE_ROWS",pL),vL.add("SORT_CELLS",(function(e,t){const o=e.getSelectedZone();return{...lL(e,t),col:o.left,row:o.top,zone:o}})),vL.add("SUM_SELECTION",bL),vL.add("SET_DECIMAL",bL),vL.add("DELETE_UNFILTERED_CONTENT",bL);class CL{trackedValues=new Set;domainToArray(e){return e.flatMap((e=>[e.field,wi(e.value)]))}isValuePresent(e,t){const o=JSON.stringify({measure:e,domain:this.domainToArray(t)});return this.trackedValues.has(o)}isHeaderPresent(e){const t=JSON.stringify({domain:this.domainToArray(e)});return this.trackedValues.has(t)}trackValue(e,t){const o=JSON.stringify({measure:e,domain:this.domainToArray(t)});this.trackedValues.add(o)}trackHeader(e){const t=JSON.stringify({domain:this.domainToArray(e)});this.trackedValues.add(t)}}const yL=5242880;const wL={filterType:"criterion",type:"none",values:[]};class IL{getters;sheetId;boundaries;top;bottom;left;right;offsetX;offsetY;canScrollVertically;canScrollHorizontally;viewportWidth;viewportHeight;offsetCorrectionX;offsetCorrectionY;constructor(e,t,o,s,i,n){if(this.getters=e,this.sheetId=t,this.boundaries=o,s.width<0||s.height<0)throw new Error("Viewport size cannot be negative");this.viewportWidth=s.height&&s.width,this.viewportHeight=s.width&&s.height,this.top=o.top,this.bottom=o.bottom,this.left=o.left,this.right=o.right,this.offsetX=n.x,this.offsetY=n.y,this.canScrollVertically=i.canScrollVertically,this.canScrollHorizontally=i.canScrollHorizontally,this.offsetCorrectionX=this.getters.getColDimensions(this.sheetId,this.boundaries.left).start,this.offsetCorrectionY=this.getters.getRowDimensions(this.sheetId,this.boundaries.top).start,this.adjustViewportOffsetX(),this.adjustViewportOffsetY()}getMaxSize(){const e=this.getters.findLastVisibleColRowIndex(this.sheetId,"COL",{first:this.boundaries.left,last:this.boundaries.right}),t=this.getters.findLastVisibleColRowIndex(this.sheetId,"ROW",{first:this.boundaries.top,last:this.boundaries.bottom}),{end:o}=this.getters.getColDimensions(this.sheetId,e),{end:s}=this.getters.getRowDimensions(this.sheetId,t);let i=o-this.offsetCorrectionX;this.canScrollHorizontally&&(i=Math.max(i,this.viewportWidth));let n=s-this.offsetCorrectionY;return this.canScrollVertically&&(n=Math.max(n,this.viewportHeight),s+he>n&&!this.getters.isReadonly()&&(n+=he)),{width:i,height:n}}getColIndex(e){return e<this.offsetCorrectionX||e>this.offsetCorrectionX+this.viewportWidth?-1:this.searchHeaderIndex("COL",e-this.offsetCorrectionX+this.snapCorrection.x,this.left)}getRowIndex(e){return e<this.offsetCorrectionY||e>this.offsetCorrectionY+this.viewportHeight?-1:this.searchHeaderIndex("ROW",e-this.offsetCorrectionY+this.snapCorrection.y,this.top)}adjustPosition(e){const t=this.sheetId,o=this.getters.getMainCellPosition({sheetId:t,...e}),{col:s,row:i}=this.getters.getNextVisibleCellPosition(o);Er(s,this.boundaries.top,this.boundaries)&&this.adjustPositionX(s),Er(this.boundaries.left,i,this.boundaries)&&this.adjustPositionY(i)}adjustPositionX(e){const t=this.sheetId,{start:o,end:s}=this.getters.getColDimensions(t,e);this.offsetX+this.viewportWidth+this.offsetCorrectionX<s?this.offsetX=s-this.viewportWidth:this.offsetX+this.offsetCorrectionX>o&&(this.offsetX=o-this.offsetCorrectionX),this.adjustViewportZoneX()}adjustPositionY(e){const t=this.sheetId,{start:o,end:s}=this.getters.getRowDimensions(t,e);this.offsetY+this.viewportHeight+this.offsetCorrectionY<s?this.offsetY=s-this.viewportHeight:this.offsetY+this.offsetCorrectionY>o&&(this.offsetY=o-this.offsetCorrectionY),this.adjustViewportZoneY()}willNewOffsetScrollViewport(e,t){return this.canScrollHorizontally&&this.offsetX!==e||this.canScrollVertically&&this.offsetY!==t}setViewportOffset(e,t){this.setViewportOffsetX(e),this.setViewportOffsetY(t)}adjustViewportZone(){this.adjustViewportZoneX(),this.adjustViewportZoneY()}getVisibleRect(e){const t=wr(e,this),o=this.snapCorrection.x,s=this.snapCorrection.y;if(t){return{x:this.getters.getColRowOffset("COL",this.left,t.left)+this.offsetCorrectionX-(this.left!==t.left?o:0),y:this.getters.getColRowOffset("ROW",this.top,t.top)+this.offsetCorrectionY-(this.top!==t.top?s:0),width:Math.min(this.getters.getColRowOffset("COL",t.left,t.right+1)-(this.left===t.left?o:0),this.viewportWidth),height:Math.min(this.getters.getColRowOffset("ROW",t.top,t.bottom+1)-(this.top===t.top?s:0),this.viewportHeight)}}}getFullRect(e){const t=wr(e,this.boundaries),o=this.snapCorrection.x,s=this.snapCorrection.y;if(t){return{x:this.getters.getColRowOffset("COL",this.left,e.left)+this.offsetCorrectionX-o,y:this.getters.getColRowOffset("ROW",this.top,e.top)+this.offsetCorrectionY-s,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,o=0){if(this.viewportWidth<=0||this.viewportHeight<=0)return-1;const s=this.sheetId,i=this.getters.getNumberHeaders(s,e);let n=o,r=i;for(;n<=r&&n!==i&&-1!==r;){const i=Math.floor((n+r)/2),a=this.getters.getColRowOffset(e,o,i),l=this.getters.getHeaderSize(s,e,i);if(t>=a&&t<a+l)return i;t>=a+l?n=i+1:r=i-1}return-1}setViewportOffsetX(e){this.canScrollHorizontally&&(this.offsetX=e,this.adjustViewportZoneX())}setViewportOffsetY(e){this.canScrollVertically&&(this.offsetY=e,this.adjustViewportZoneY())}adjustViewportOffsetX(){if(this.canScrollHorizontally){const{width:e}=this.getMaxSize();this.viewportWidth+this.offsetX>e&&(this.offsetX=Math.max(0,e-this.viewportWidth))}this.adjustViewportZoneX()}adjustViewportOffsetY(){if(this.canScrollVertically){const{height:e}=this.getMaxSize();this.viewportHeight+this.offsetY>e&&(this.offsetY=Math.max(0,e-this.viewportHeight))}this.adjustViewportZoneY()}adjustViewportZoneX(){this.left=this.searchHeaderIndex("COL",this.offsetX,this.boundaries.left),this.right=Math.min(this.boundaries.right,this.searchHeaderIndex("COL",Math.max(this.viewportWidth+this.snapCorrection.x-.1),this.left)),this.viewportWidth&&(-1===this.left&&(this.left=this.boundaries.left),-1===this.right&&(this.right=this.boundaries.right))}adjustViewportZoneY(){this.top=this.searchHeaderIndex("ROW",this.offsetY,this.boundaries.top),this.bottom=Math.min(this.boundaries.bottom,this.searchHeaderIndex("ROW",Math.max(this.viewportHeight+this.snapCorrection.y-.1,0),this.top)),this.viewportHeight&&(-1===this.top&&(this.top=this.boundaries.top),-1===this.bottom&&(this.bottom=this.boundaries.bottom))}get snapCorrection(){return{x:Math.abs(this.offsetX-this.getters.getColRowOffset("COL",this.boundaries.left,Math.max(0,this.left))),y:Math.abs(this.offsetY-this.getters.getColRowOffset("ROW",this.boundaries.top,Math.max(0,this.top)))}}}const xL=(new n).add("settings",class extends Nk{static getters=["getLocale"];locale=qs;allowDispatch(e){return"UPDATE_LOCALE"===e.type?El(e.locale)?"Success":"InvalidLocale":"Success"}handle(e){if("UPDATE_LOCALE"===e.type){const t=this.locale,o=e.locale;this.history.update("locale",o),this.changeCellsDateFormatWithLocale(t,o)}}getLocale(){return this.locale}changeCellsDateFormatWithLocale(e,t){for(const o of this.getters.getSheetIds())for(const[s,i]of Object.entries(this.getters.getCells(o))){let o;if(i.format===e.dateFormat&&(o=t.dateFormat),i.format===e.timeFormat&&(o=t.timeFormat),i.format===Hl(e)&&(o=Hl(t)),o){const{col:e,row:t,sheetId:i}=this.getters.getCellPosition(s);this.dispatch("UPDATE_CELL",{col:e,row:t,sheetId:i,format:o})}}}import(e){this.locale=e.settings?.locale??qs}export(e){e.settings={locale:this.locale}}}).add("sheet",class extends Nk{static getters=["getSheetName","tryGetSheetName","getSheet","tryGetSheet","getSheetIdByName","getSheetIds","getVisibleSheetIds","isSheetVisible","doesHeaderExist","doesHeadersExist","getCell","getCellPosition","getColsZone","getRowCells","getRowsZone","getNumberCols","getNumberRows","getNumberHeaders","getGridLinesVisibility","getNextSheetName","getSheetSize","getSheetZone","getPaneDivisions","checkZonesExistInSheet","getCommandZones","getUnboundedZone","checkElementsIncludeAllNonFrozenHeaders","getDuplicateSheetName"];sheetIdsMapName={};orderedSheetIds=[];sheets={};cellPosition={};allowDispatch(e){const t=this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e);if("Success"!==t)return t;switch(e.type){case"HIDE_SHEET":return 1===this.getVisibleSheetIds().length?"NotEnoughSheets":"Success";case"CREATE_SHEET":return this.checkValidations(e,this.checkSheetName,this.checkSheetPosition);case"DUPLICATE_SHEET":return this.sheets[e.sheetIdTo]?"DuplicatedSheetId":this.orderedSheetIds.map(this.getSheetName.bind(this)).includes(e.sheetNameTo)?"DuplicatedSheetName":"Success";case"MOVE_SHEET":try{const t=this.orderedSheetIds.findIndex((t=>t===e.sheetId));return this.findIndexOfTargetSheet(t,e.delta),"Success"}catch(e){return"WrongSheetMove"}case"RENAME_SHEET":return this.isRenameAllowed(e);case"COLOR_SHEET":return!e.color||Wt(e.color)?"Success":"InvalidColor";case"DELETE_SHEET":return this.getVisibleSheetIds().length>1?"Success":"NotEnoughSheets";case"ADD_COLUMNS_ROWS":return this.doesHeaderExist(e.sheetId,e.dimension,e.base)?e.quantity<=0?"InvalidQuantity":"Success":"InvalidHeaderIndex";case"REMOVE_COLUMNS_ROWS":{const t=Pt(e.elements),o=Ft(e.elements);return t<0||!this.doesHeaderExist(e.sheetId,e.dimension,o)?"InvalidHeaderIndex":this.checkElementsIncludeAllNonFrozenHeaders(e.sheetId,e.dimension,e.elements)?"NotEnoughElements":"Success"}case"FREEZE_ROWS":return this.checkValidations(e,this.checkRowFreezeQuantity,this.checkRowFreezeOverlapMerge);case"FREEZE_COLUMNS":return this.checkValidations(e,this.checkColFreezeQuantity,this.checkColFreezeOverlapMerge);default:return"Success"}}handle(e){switch(e.type){case"SET_GRID_LINES_VISIBILITY":this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);break;case"CREATE_SHEET":const t=this.createSheet(e.sheetId,e.name||this.getNextSheetName(),e.cols||26,e.rows||100,e.position);this.history.update("sheetIdsMapName",t.name,t.id);break;case"MOVE_SHEET":this.moveSheet(e.sheetId,e.delta);break;case"RENAME_SHEET":this.renameSheet(this.sheets[e.sheetId],e.newName);break;case"COLOR_SHEET":this.history.update("sheets",e.sheetId,"color",e.color);break;case"HIDE_SHEET":this.hideSheet(e.sheetId);break;case"SHOW_SHEET":this.showSheet(e.sheetId);break;case"DUPLICATE_SHEET":this.duplicateSheet(e.sheetId,e.sheetIdTo,e.sheetNameTo);break;case"DELETE_SHEET":this.deleteSheet(this.sheets[e.sheetId]);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case"UPDATE_CELL_POSITION":this.updateCellPosition(e);break;case"FREEZE_COLUMNS":this.setPaneDivisions(e.sheetId,e.quantity,"COL");break;case"FREEZE_ROWS":this.setPaneDivisions(e.sheetId,e.quantity,"ROW");break;case"UNFREEZE_ROWS":this.setPaneDivisions(e.sheetId,0,"ROW");break;case"UNFREEZE_COLUMNS":this.setPaneDivisions(e.sheetId,0,"COL");break;case"UNFREEZE_COLUMNS_ROWS":this.setPaneDivisions(e.sheetId,0,"COL"),this.setPaneDivisions(e.sheetId,0,"ROW")}}import(e){for(const t of e.sheets)this.sheetIdsMapName[t.name]=t.id;for(const t of e.sheets){const e=t.name||"Sheet"+(Object.keys(this.sheets).length+1),{colNumber:o,rowNumber:s}=this.getImportedSheetSize(t),i={id:t.id,name:e,numberOfCols:o,rows:la(s),areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible,isVisible:t.isVisible,panes:{xSplit:t.panes?.xSplit||0,ySplit:t.panes?.ySplit||0},color:t.color};this.orderedSheetIds.push(i.id),this.sheets[i.id]=i}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(lt).map((e=>{const t=this.sheets[e],o={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},styles:{},formats:{},borders:{},conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible,isVisible:t.isVisible,color:t.color};return(t.panes.xSplit||t.panes.ySplit)&&(o.panes=t.panes),o}))}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){const t=this.sheets[e];if(!t)throw new Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){return this.tryGetSheet(e)?.name}getSheetIdByName(e){if(e){const t=$e(e);for(const e in this.sheetIdsMapName)if(ga(e,t))return this.sheetIdsMapName[e]}}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}doesHeaderExist(e,t,o){return"COL"===t?o>=0&&o<this.getNumberCols(e):o>=0&&o<this.getNumberRows(e)}doesHeadersExist(e,t,o){return o.every((o=>this.doesHeaderExist(e,t,o)))}getCell({sheetId:e,col:t,row:o}){const s=this.tryGetSheet(e),i=s?.rows[o]?.cells[t];if(void 0!==i)return this.getters.getCellById(i)}getColsZone(e,t,o){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:o}}getRowCells(e,t){return Object.values(this.getSheet(e).rows[t]?.cells).filter(lt)}getRowsZone(e,t,o){return{top:t,bottom:o,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){const t=this.cellPosition[e];if(!t)throw new Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return"COL"===t?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e="Sheet"){return da(this.orderedSheetIds.map(this.getSheetName.bind(this)),e)}getSheetSize(e){return{numberOfRows:this.getNumberRows(e),numberOfCols:this.getNumberCols(e)}}getSheetZone(e){return{top:0,left:0,bottom:this.getNumberRows(e)-1,right:this.getNumberCols(e)-1}}getUnboundedZone(e,t){if(void 0===t.bottom||void 0===t.right)return t;const o=0===t.left&&t.right===this.getNumberCols(e)-1,s=0===t.top&&t.bottom===this.getNumberRows(e)-1;return{...t,bottom:s?void 0:t.bottom,right:o&&!s?void 0:t.right}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,o){const s={...this.getPaneDivisions(e)};"COL"===o?s.xSplit=t:"ROW"===o&&(s.ySplit=t),this.history.update("sheets",e,"panes",s)}checkElementsIncludeAllNonFrozenHeaders(e,t,o){const s=this.getters.getPaneDivisions(e),i="ROW"===t?s.ySplit:s.xSplit,n=this.getters.getNumberHeaders(e,t);if(!i)return!1;return vt(o,je(i,n))}getCommandZones(e){const t=[];return"zone"in e&&t.push(e.zone),"target"in e&&t.push(...e.target),"ranges"in e&&t.push(...e.ranges.map((e=>this.getters.getRangeFromRangeData(e).zone))),"col"in e&&void 0!==e.col&&"row"in e&&void 0!==e.row&&t.push({top:e.row,left:e.col,bottom:e.row,right:e.col}),t}checkZonesExistInSheet(e,t){if(!t.every(pr))return"InvalidRange";if(t.length){const o=this.getSheetZone(e);return t.every((e=>Rr(e,o)))?"Success":"TargetOutOfSheet"}return"Success"}updateCellPosition(e){const{sheetId:t,cellId:o,col:s,row:i}=e;o?this.setNewPosition(o,t,s,i):this.clearPosition(t,s,i)}setNewPosition(e,t,o,s){const i=this.cellPosition[e];i&&this.clearPosition(t,i.col,i.row),this.history.update("cellPosition",e,{row:s,col:o,sheetId:t}),this.history.update("sheets",t,"rows",s,"cells",o,e)}clearPosition(e,t,o){const s=this.sheets[e]?.rows[o].cells[t];s&&(this.history.update("cellPosition",s,void 0),this.history.update("sheets",e,"rows",o,"cells",t,void 0))}setGridLinesVisibility(e,t){this.history.update("sheets",e,"areGridLinesVisible",t)}createSheet(e,t,o,s,i){const n={id:e,name:t,numberOfCols:o,rows:la(s),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0}},r=this.orderedSheetIds.slice();r.splice(i,0,n.id);const a=this.sheets;return this.history.update("orderedSheetIds",r),this.history.update("sheets",Object.assign({},a,{[n.id]:n})),n}moveSheet(e,t){const o=this.orderedSheetIds.slice(),s=o.findIndex((t=>t===e)),i=o.splice(s,1),n=this.findIndexOfTargetSheet(s,t);o.splice(n,0,i[0]),this.history.update("orderedSheetIds",o)}findIndexOfTargetSheet(e,t){for(;0!==t&&0<=e&&e<=this.orderedSheetIds.length;)t>0?(e++,this.isSheetVisible(this.orderedSheetIds[e])&&t--):t<0&&(e--,this.isSheetVisible(this.orderedSheetIds[e])&&t++);if(0===t)return e;throw new Error("There is not enough visible sheets")}checkSheetName(e){const t=this.getters.tryGetSheetName(e.sheetId),o="RENAME_SHEET"===e.type?e.newName:e.name;if(void 0!==t&&o===t)return"UnchangedSheetName";const{orderedSheetIds:s,sheets:i}=this,n=o&&o.trim().toLowerCase();return s.find((t=>ga(i[t]?.name,n)&&t!==e.sheetId))?"DuplicatedSheetName":_e.test(n)?"ForbiddenCharactersInSheetName":"Success"}checkSheetPosition(e){const{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?"WrongSheetPosition":"Success"}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?"Success":"InvalidFreezeQuantity"}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?"Success":"InvalidFreezeQuantity"}checkRowFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(const o of t)if(o.top<e.quantity&&e.quantity<=o.bottom)return"MergeOverlap";return"Success"}checkColFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(const o of t)if(o.left<e.quantity&&e.quantity<=o.right)return"MergeOverlap";return"Success"}isRenameAllowed(e){return e.newName&&e.newName.trim().toLowerCase()?this.checkSheetName(e):"MissingSheetName"}renameSheet(e,t){const o=e.name;this.history.update("sheets",e.id,"name",t.trim());const s=Object.assign({},this.sheetIdsMapName);delete s[o],s[t]=e.id,this.history.update("sheetIdsMapName",s)}hideSheet(e){this.history.update("sheets",e,"isVisible",!1)}showSheet(e){this.history.update("sheets",e,"isVisible",!0)}duplicateSheet(e,t,o){const s=ze(this.getSheet(e));s.id=t,s.name=o;for(let e=0;e<=s.numberOfCols;e++)for(let t=0;t<=s.rows.length;t++)s.rows[t]&&(s.rows[t].cells[e]=void 0);const i=this.orderedSheetIds.slice(),n=i.indexOf(e);i.splice(n+1,0,s.id),this.history.update("orderedSheetIds",i),this.history.update("sheets",Object.assign({},this.sheets,{[s.id]:s}));for(const t of Object.values(this.getters.getCells(e))){const{col:e,row:o}=this.getCellPosition(t.id);this.dispatch("UPDATE_CELL",{sheetId:s.id,col:e,row:o,content:t.content,format:t.format,style:t.style})}const r=Object.assign({},this.sheetIdsMapName);r[s.name]=s.id,this.history.update("sheetIdsMapName",r)}getDuplicateSheetName(e){return ua(e,this.orderedSheetIds.map(this.getSheetName.bind(this)))}deleteSheet(e){const t=e.name,o=Object.assign({},this.sheets);delete o[e.id],this.history.update("sheets",o);const s=this.orderedSheetIds.slice(),i=s.indexOf(e.id);s.splice(i,1),this.history.update("orderedSheetIds",s);const n=Object.assign({},this.sheetIdsMapName);delete n[t],this.history.update("sheetIdsMapName",n)}removeColumns(e,t){t.sort(((e,t)=>t-e));for(const o of t)this.moveCellOnColumnsDeletion(e,o);const o=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",o-t.length);const s=t.filter((t=>t<e.panes.xSplit)).length;s&&this.setPaneDivisions(e.id,e.panes.xSplit-s,"COL")}removeRows(e,t){t.sort(((e,t)=>t-e));for(const o of Ye(t)){const t=o[o.length-1],s=o[0];this.moveCellOnRowsDeletion(e,t,s),this.updateRowsStructureOnDeletion(e,t,s)}const o=t.filter((t=>t<e.panes.ySplit)).length;o&&this.setPaneDivisions(e.id,e.panes.ySplit-o,"ROW")}addColumns(e,t,o,s){const i="before"===o?t:t+1;this.moveCellsOnAddition(e,i,s,"columns");const n=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",n+s),i<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+s,"COL")}addRows(e,t,o,s){const i="before"===o?t:t+1;this.addEmptyRows(e,s),this.moveCellsOnAddition(e,i,s,"rows"),i<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+s,"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 o=0;o<e.rows.length;o++){const s=e.rows[o];for(const i in s.cells){const n=Number(i),r=s.cells[i];r&&n>t&&this.setNewPosition(r,e.id,n-1,o)}}}moveCellsOnAddition(e,t,o,s){const i=[];for(let n=0;n<e.rows.length;n++){const r=e.rows[n];if("rows"!==s||n>=t)for(const a in r.cells){const l=Number(a),c=r.cells[a];c&&("rows"===s||l>=t)&&i.push({sheetId:e.id,cellId:c,col:l+("columns"===s?o:0),row:n+("rows"===s?o:0),type:"UPDATE_CELL_POSITION"})}}for(const e of i.reverse())this.updateCellPosition(e)}moveCellOnRowsDeletion(e,t,o){this.dispatch("CLEAR_CELLS",{sheetId:e.id,target:[{left:0,top:t,right:this.getters.getNumberCols(e.id),bottom:o}]});const s=o-t+1;for(let t=0;t<e.rows.length;t++){const i=e.rows[t];if(t>o)for(const o in i.cells){const n=Number(o),r=i.cells[o];r&&this.setNewPosition(r,e.id,n,t-s)}}}updateRowsStructureOnDeletion(e,t,o){const s=[],i=e.rows.map((e=>e.cells)).reverse();for(const n in e.rows){const e=Number(n);e>=t&&e<=o||s.push({cells:i.pop()})}this.history.update("sheets",e.id,"rows",s)}addEmptyRows(e,t){const o=e.rows.slice();for(let e=0;e<t;e++)o.push({cells:{}});this.history.update("sheets",e.id,"rows",o)}getImportedSheetSize(e){const t=Object.keys(e.cells).map(Fo);let o=e.rowNumber,s=e.colNumber;for(const{col:e,row:i}of t)o=Math.max(o,i+1),s=Math.max(s,e+1);return{rowNumber:o,colNumber:s}}checkSheetExists(e){return"CREATE_SHEET"!==e.type&&"sheetId"in e&&void 0===this.sheets[e.sheetId]?"InvalidSheetId":"CREATE_SHEET"===e.type&&void 0!==this.sheets[e.sheetId]?"DuplicatedSheetId":"Success"}checkZonesAreInSheet(e){return"sheetId"in e?"ranges"in e&&e.ranges.some((e=>""!==e._sheetId&&!this.getters.tryGetSheet(e._sheetId)))?"InvalidSheetId":this.checkZonesExistInSheet(e.sheetId,this.getCommandZones(e)):"Success"}}).add("header grouping",class extends Nk{static getters=["getHeaderGroups","getGroupsLayers","getVisibleGroupLayers","getHeaderGroup","getHeaderGroupsInZone","isGroupFolded","isRowFolded","isColFolded"];groups={};allowDispatch(e){switch(e.type){case"GROUP_HEADERS":{const{start:t,end:o,sheetId:s}=e;if(!this.getters.tryGetSheet(s))return"InvalidSheetId";if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,o]))return"InvalidHeaderGroupStartEnd";if(t>o)return"InvalidHeaderGroupStartEnd";if(this.findGroupWithStartEnd(e.sheetId,e.dimension,t,o))return"HeaderGroupAlreadyExists";break}case"UNGROUP_HEADERS":{const{start:t,end:o,sheetId:s}=e;if(!this.getters.tryGetSheet(s))return"InvalidSheetId";if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,o]))return"InvalidHeaderGroupStartEnd";if(t>o)return"InvalidHeaderGroupStartEnd";break}case"UNFOLD_HEADER_GROUP":case"FOLD_HEADER_GROUP":if(!this.getters.tryGetSheet(e.sheetId))return"InvalidSheetId";const t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);if(!t)return"UnknownHeaderGroup";if(je(0,this.getters.getNumberHeaders(e.sheetId,e.dimension)).every((o=>o>=t.start&&o<=t.end||this.getters.isHeaderHiddenByUser(e.sheetId,e.dimension,o))))return"NotEnoughElements"}return"Success"}handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("groups",e.sheetId,{ROW:[],COL:[]});break;case"GROUP_HEADERS":this.groupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case"UNGROUP_HEADERS":this.unGroupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case"DUPLICATE_SHEET":{const t=ze(this.groups[e.sheetId]);this.history.update("groups",e.sheetIdTo,t);break}case"DELETE_SHEET":{const t={...this.groups};delete t[e.sheetId],this.history.update("groups",t);break}case"ADD_COLUMNS_ROWS":const t=pt(e.position,e.base);this.moveGroupsOnHeaderInsertion(e.sheetId,e.dimension,t,e.quantity);break;case"REMOVE_COLUMNS_ROWS":this.moveGroupsOnHeaderDeletion(e.sheetId,e.dimension,e.elements);break;case"UNFOLD_HEADER_GROUP":{const t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.unfoldHeaderGroup(e.sheetId,e.dimension,t);break}case"FOLD_HEADER_GROUP":{const t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.foldHeaderGroup(e.sheetId,e.dimension,t);break}case"UNFOLD_ALL_HEADER_GROUPS":{const t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(const o of t)this.unfoldHeaderGroup(e.sheetId,e.dimension,o);break}case"FOLD_ALL_HEADER_GROUPS":{const t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(const o of t)this.foldHeaderGroup(e.sheetId,e.dimension,o);break}case"FOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_HEADER_GROUPS_IN_ZONE":{const t="UNFOLD_HEADER_GROUPS_IN_ZONE"===e.type?"unfold":"fold",o=this.getGroupsLayers(e.sheetId,e.dimension);"fold"===t&&o.reverse();const s=o.flat(),i="ROW"===e.dimension?e.zone.top:e.zone.left,n="ROW"===e.dimension?e.zone.bottom:e.zone.right,r=new Set;for(let e=i;e<=n;e++){const o=s.filter((t=>t.start-1<=e&&e<=t.end));for(const e of o)if(!("fold"===t&&e.isFolded||"unfold"===t&&!e.isFolded)){r.add(e);break}}for(const o of r)"unfold"===t?this.unfoldHeaderGroup(e.sheetId,e.dimension,o):this.foldHeaderGroup(e.sheetId,e.dimension,o);break}}}getHeaderGroups(e,t){return this.groups[e][t]}getHeaderGroup(e,t,o,s){return this.getHeaderGroups(e,t).find((e=>e.start===o&&e.end===s))}getHeaderGroupsInZone(e,t,o){return this.getHeaderGroups(e,t).filter((e=>{const s="ROW"===t?o.top:o.left,i="ROW"===t?o.bottom:o.right;return this.doGroupOverlap(e,s,i)}))}getGroupsLayers(e,t){const o=this.getHeaderGroups(e,t);return this.bricksFallingAlgorithm(o,0,0)}getVisibleGroupLayers(e,t){const o=this.getGroupsLayers(e,t);for(const s of o)for(let o=s.length-1;o>=0;o--){const i=s[o];if(0===i.start)continue;je(i.start-1,i.end+1).every((o=>this.getters.isHeaderHiddenByUser(e,t,o)))&&s.splice(o,1)}return o.filter((e=>e.length>0))}isGroupFolded(e,t,o,s){return this.getHeaderGroup(e,t,o,s)?.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,o,s=0){const i={};for(const t of e)i[this.getGroupId(t)]=t.isFolded;const n={};for(const t of e)for(let e=t.start;e<=t.end;e++)n[e]=n[e]?n[e]+1:1;for(let e=t;e<=o;e++)n[e]=n[e]?n[e]+s:s;const r=Math.max(...Object.values(n),0),a=Array.from({length:r},(()=>[])),l=Math.max(o,...e.map((e=>e.end)));for(let o=Math.min(t,...e.map((e=>e.start)));o<=l;o++){const e=n[o]||0;for(let t=0;t<e;t++){const e=a[t].at(-1);if(e&&xt([e.end,o]))e.end++;else{const e={start:o,end:o};a[t].push(e)}}}for(const e of a)for(const t of e)t.isFolded=i[this.getGroupId(t)];return a}groupHeaders(e,t,o,s){const i=this.getHeaderGroups(e,t),n=this.bricksFallingAlgorithm(i,o,s,1).flat();this.history.update("groups",e,t,this.removeDuplicateGroups(n))}unGroupHeaders(e,t,o,s){const i=this.getHeaderGroups(e,t),n=this.bricksFallingAlgorithm(i,o,s,-1).flat();this.history.update("groups",e,t,this.removeDuplicateGroups(n))}moveGroupsOnHeaderInsertion(e,t,o,s){const i=this.groups[e][t];for(let n=0;n<i.length;n++){const r=i[n],[a,l]=ca(o,s,[r.start,r.end]);a===r.start&&l===r.end||this.history.update("groups",e,t,n,{...r,start:a,end:l})}}moveGroupsOnHeaderDeletion(e,t,o){const s=this.getHeaderGroups(e,t),i=[];for(const e of s){const t=ha(o,je(e.start,e.end+1));0!==t.length&&i.push({...e,start:Math.min(...t),end:Math.max(...t)})}this.history.update("groups",e,t,this.bricksFallingAlgorithm(i,0,0).flat())}doGroupOverlap(e,t,o){return e.start<=o&&e.end>=t}removeDuplicateGroups(e){const t={};for(const o of e)t[this.getGroupId(o)]=o;return Object.values(t)}findGroupWithStartEnd(e,t,o,s){return this.getHeaderGroups(e,t).find((e=>e.start===o&&e.end===s))}foldHeaderGroup(e,t,o){const s=this.getGroupIndex(e,t,o.start,o.end);if(void 0===s)return;this.history.update("groups",e,t,s,"isFolded",!0);const i=this.getters.getHeaderGroups(e,t);for(let s=0;s<i.length;s++){const n=i[s];n.start===o.start&&n.end<=o.end&&this.history.update("groups",e,t,s,"isFolded",!0)}}unfoldHeaderGroup(e,t,o){const s=this.getGroupIndex(e,t,o.start,o.end);if(void 0===s)return;this.history.update("groups",e,t,s,"isFolded",!1);const i=this.getters.getHeaderGroups(e,t);for(let s=0;s<i.length;s++){const n=i[s];n.start===o.start&&n.end>=o.end&&this.history.update("groups",e,t,s,"isFolded",!1)}}getGroupIndex(e,t,o,s){const i=this.groups[e][t].findIndex((e=>e.start===o&&e.end===s));return-1===i?void 0:i}import(e){for(const t of e.sheets)if(this.groups[t.id]={ROW:[],COL:[]},t.headerGroups)for(const e of["ROW","COL"])for(const o of t.headerGroups[e]||[])this.groups[t.id][e].push({...o})}export(e){for(const t of e.sheets)t.headerGroups=this.groups[t.id]}exportForExcel(e){for(const t of e.sheets)for(const e of["ROW","COL"]){const o=this.getGroupsLayers(t.id,e);for(let s=0;s<o.length;s++){const i=o[s];for(const o of i){for(let i=o.start;i<=o.end;i++){const n=MT(t,e,i);n.outlineLevel=s+1,o.isFolded&&(n.isHidden=!0)}if(o.isFolded){MT(t,e,o.end+1).collapsed=!0}}}}}}).add("header visibility",class extends Nk{static getters=["checkElementsIncludeAllVisibleHeaders","getHiddenColsGroups","getHiddenRowsGroups","isHeaderHiddenByUser","isRowHiddenByUser","isColHiddenByUser"];hiddenHeaders={};allowDispatch(e){switch(e.type){case"HIDE_COLUMNS_ROWS":{if(!this.getters.tryGetSheet(e.sheetId))return"InvalidSheetId";const t="COL"===e.dimension?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),o="COL"===e.dimension?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=o?"TooManyHiddenElements":Pt(e.elements)<0||Ft(e.elements)>o?"InvalidHeaderIndex":"Success"}case"REMOVE_COLUMNS_ROWS":return this.getters.tryGetSheet(e.sheetId)?this.checkElementsIncludeAllVisibleHeaders(e.sheetId,e.dimension,e.elements)?"NotEnoughElements":"Success":"InvalidSheetId"}return"Success"}handle(e){switch(e.type){case"CREATE_SHEET":const t={COL:Array(this.getters.getNumberCols(e.sheetId)).fill(!1),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(!1)};this.history.update("hiddenHeaders",e.sheetId,t);break;case"DUPLICATE_SHEET":this.history.update("hiddenHeaders",e.sheetIdTo,ze(this.hiddenHeaders[e.sheetId]));break;case"DELETE_SHEET":this.history.update("hiddenHeaders",e.sheetId,void 0);break;case"REMOVE_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(const o of[...e.elements].sort(((e,t)=>t-e)))t.splice(o,1);this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]],o=pt(e.position,e.base);t.splice(o,0,...Array(e.quantity).fill(!1)),this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);break}case"HIDE_COLUMNS_ROWS":for(const t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!0);break;case"UNHIDE_COLUMNS_ROWS":for(const t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!1)}}checkElementsIncludeAllVisibleHeaders(e,t,o){return vt(o,this.getAllVisibleHeaders(e,t))}isHeaderHiddenByUser(e,t,o){return"COL"===t?this.isColHiddenByUser(e,o):this.isRowHiddenByUser(e,o)}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]||this.getters.isRowFolded(e,t)}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]||this.getters.isColFolded(e,t)}getHiddenColsGroups(e){const t=[[]],o=this.hiddenHeaders[e].COL;for(let e=0;e<o.length;e++){o[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getHiddenRowsGroups(e){const t=[[]],o=this.hiddenHeaders[e].ROW;for(let e=0;e<o.length;e++){o[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getAllVisibleHeaders(e,t){const o=je(0,this.getters.getNumberHeaders(e,t)),s=[];return this.getters.getHeaderGroups(e,t).forEach((e=>{e.isFolded&&s.push(...je(e.start,e.end+1))})),o.filter((o=>!this.hiddenHeaders[e][t][o]&&!s.includes(o)))}import(e){for(const t of e.sheets){this.hiddenHeaders[t.id]={COL:[],ROW:[]};for(let e=0;e<t.rowNumber;e++)this.hiddenHeaders[t.id].ROW[e]=Boolean(t.rows[e]?.isHidden);for(let e=0;e<t.colNumber;e++)this.hiddenHeaders[t.id].COL[e]=Boolean(t.cols[e]?.isHidden)}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(const o of e.sheets){void 0===o.rows&&(o.rows={});for(let e=0;e<this.getters.getNumberRows(o.id);e++)(t||this.hiddenHeaders[o.id].ROW[e])&&(void 0===o.rows[e]&&(o.rows[e]={}),o.rows[e].isHidden||=this.hiddenHeaders[o.id].ROW[e]);void 0===o.cols&&(o.cols={});for(let e=0;e<this.getters.getNumberCols(o.id);e++)(t||this.hiddenHeaders[o.id].COL[e])&&(void 0===o.cols[e]&&(o.cols[e]={}),o.cols[e].isHidden||=this.hiddenHeaders[o.id].COL[e])}}}).add("tables",class extends Nk{static getters=["getCoreTable","getCoreTables","getCoreTableMatchingTopLeft"];tables={};nextTableId=1;adaptRanges(e,t){for(const o of this.getCoreTables(t))this.applyRangeChangeOnTable(t,o,e)}allowDispatch(e){switch(e.type){case"CREATE_TABLE":if(e.ranges.some((t=>!this.getters.tryGetSheet(t._sheetId)||t._sheetId!==e.sheetId)))return"InvalidSheetId";const t=e.ranges.map((e=>this.getters.getRangeFromRangeData(e).zone));return Ur(t)?this.checkValidations(e,(e=>this.getTablesOverlappingZones(e.sheetId,t).length?"TableOverlap":"Success"),(e=>this.checkTableConfigUpdateIsValid(e.config))):"NonContinuousTargets";case"UPDATE_TABLE":return this.getCoreTableMatchingTopLeft(e.sheetId,e.zone)?this.checkValidations(e,this.checkUpdatedTableZoneIsValid,(e=>this.checkTableConfigUpdateIsValid(e.config))):"TableNotFound";case"ADD_MERGE":for(const t of this.getCoreTables(e.sheetId)){const o=t.range.zone;for(const t of e.target)if(xr(o,t))return"MergeInTable"}}return"Success"}handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("tables",e.sheetId,{});break;case"DELETE_SHEET":{const t={...this.tables};delete t[e.sheetId],this.history.update("tables",t);break}case"DUPLICATE_SHEET":{const t={};for(const o of this.getCoreTables(e.sheetId))t[o.id]="dynamic"===o.type?this.copyDynamicTableForSheet(e.sheetIdTo,o):this.copyStaticTableForSheet(e.sheetIdTo,o);this.history.update("tables",e.sheetIdTo,t);break}case"CREATE_TABLE":{const t=e.ranges.map((e=>this.getters.getRangeFromRangeData(e))),o=this.getters.getRangesUnion(t),s=this.getters.getMergesInZone(e.sheetId,o.zone);s.length&&this.dispatch("REMOVE_MERGE",{sheetId:e.sheetId,target:s});const i=this.consumeNextId(),n=e.config||wR,r="dynamic"===e.tableType?this.createDynamicTable(i,o,n):this.createStaticTable(i,e.tableType,o,n);this.history.update("tables",e.sheetId,r.id,r);break}case"REMOVE_TABLE":{const t={};for(const o of this.getCoreTables(e.sheetId))e.target.every((e=>!wr(o.range.zone,e)))&&(t[o.id]=o);this.history.update("tables",e.sheetId,t);break}case"UPDATE_TABLE":this.updateTable(e);break;case"UPDATE_CELL":{const t=e.sheetId;for(const o of this.getCoreTables(t)){if("dynamic"===o.type)continue;const s=this.canUpdateCellCmdExtendTable(e,o);"down"===s?this.extendTableDown(t,o):"right"===s&&this.extendTableRight(t,o)}break}case"DELETE_CONTENT":{const t={...this.tables[e.sheetId]};for(const o in t){const s=t[o];s&&e.target.some((e=>Rr(s.range.zone,e)))&&this.dispatch("REMOVE_TABLE",{sheetId:e.sheetId,target:[s.range.zone]})}break}}}getCoreTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(lt):[]}getCoreTable({sheetId:e,col:t,row:o}){return this.getCoreTables(e).find((e=>Er(t,o,e.range.zone)))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter((e=>t.some((t=>xr(e.range.zone,t)))))}extendTableDown(e,t){const o=this.getters.extendRange(t.range,"ROW",1);this.history.update("tables",e,t.id,this.updateStaticTable(t,o))}extendTableRight(e,t){const o=this.getters.extendRange(t.range,"COL",1);this.history.update("tables",e,t.id,this.updateStaticTable(t,o))}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:o,row:s},i){if(!e)return"none";const n=i.range.zone;let r="none";if(n.bottom+1===s&&o>=n.left&&o<=n.right?r="down":n.right+1===o&&s>=n.top&&s<=n.bottom&&(r="right"),"none"===r)return"none";const a="down"===r?{...n,bottom:n.bottom+1,top:n.bottom+1}:{...n,right:n.right+1,left:n.right+1};for(let e=a.top;e<=a.bottom;e++)for(let o=a.left;o<=a.right;o++){const s={sheetId:t,col:o,row:e},i=this.getters.getCell(s)?.content;if(i||this.getters.isInMerge(s)||this.getTablesOverlappingZones(t,[Mr(s)]).length)return"none"}return r}getCoreTableMatchingTopLeft(e,t){for(const o of this.getCoreTables(e)){const e=o.range.zone;if(e.left===t.left&&e.top===t.top)return o}}checkUpdatedTableZoneIsValid(e){if(!e.newTableRange)return"Success";const t=this.getters.getRangeFromRangeData(e.newTableRange).zone,o=this.getters.checkZonesExistInSheet(e.sheetId,[t]);if("Success"!==o)return o;const s=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!s)return"TableNotFound";return this.getTablesOverlappingZones(e.sheetId,[t]).filter((e=>e.id!==s.id)).length?"TableOverlap":"Success"}checkTableConfigUpdateIsValid(e){return e&&(void 0!==e.numberOfHeaders&&e.numberOfHeaders<0||e.hasFilters&&0===e.numberOfHeaders)?"InvalidTableConfig":"Success"}createStaticTable(e,t,o,s,i){const n=o.zone;if(!i){i=[];for(const e of je(n.left,n.right+1)){const t={...n,left:e,right:e},r=this.consumeNextId();i.push(this.createFilterFromZone(r,o.sheetId,t,s))}}return{id:e,range:o,filters:i,config:s,type:t}}createDynamicTable(e,t,o){const s=Nr(t.zone);return{id:e,range:this.getters.getRangeFromZone(t.sheetId,s),config:o,type:"dynamic"}}updateTable(e){const t=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return;const o=e.newTableRange?this.getters.getRangeFromRangeData(e.newTableRange):void 0;if(o){const t=this.getters.getMergesInZone(e.sheetId,o.zone);this.dispatch("REMOVE_MERGE",{sheetId:e.sheetId,target:t})}const s=o||t.range,i=this.updateTableConfig(e.config,t.config),n=e.tableType??t.type;if("dynamic"===n&&"dynamic"!==t.type||"dynamic"!==n&&"dynamic"===t.type){const o="dynamic"===n?this.createDynamicTable(t.id,s,i):this.createStaticTable(t.id,n,s,i);this.history.update("tables",e.sheetId,t.id,o)}else{const o="dynamic"===t.type?this.updateDynamicTable(t,s,i):this.updateStaticTable(t,s,i,n);this.history.update("tables",e.sheetId,t.id,o)}}updateStaticTable(e,t,o,s=e.type){if("dynamic"===s)throw new Error("Cannot use updateStaticTable to update a dynamic table");const i=t||e.range,n=i.zone,r=this.updateTableConfig(o,e.config),a=r||e.config,l=[];if(t||r&&"numberOfHeaders"in r)for(const t of je(n.left,n.right+1)){const o=n.top===e.range.zone.top?e.filters.find((e=>e.col===t)):void 0,s={...n,left:t,right:t},r=o?.id||this.consumeNextId();l.push(this.createFilterFromZone(r,i.sheetId,s,a))}return{...e,range:i,config:a,filters:l.length?l:e.filters,type:s}}updateDynamicTable(e,t,o){const s=t?this.getters.getRangeFromZone(t.sheetId,Nr(t.zone)):e.range,i=o||e.config;return{...e,range:s,config:i}}updateTableConfig(e,t){if(!e)return t;const o={...t,...e};return 0===e.numberOfHeaders?o.hasFilters=!1:!0===e.hasFilters&&(o.numberOfHeaders||=1),o}createFilterFromZone(e,t,o,s){return C_(e,this.getters.getRangeFromZone(t,o),s,this.getters.getRangeFromZone)}copyStaticTableForSheet(e,t){const o=this.getters.getRangeFromZone(e,t.range.zone),s=t.filters.map((o=>{const s=this.getters.getRangeFromZone(e,o.rangeWithHeaders.zone);return C_(o.id,s,t.config,this.getters.getRangeFromZone)}));return{id:t.id,range:o,filters:s,config:ze(t.config),type:t.type}}copyDynamicTableForSheet(e,t){const o=this.getters.getRangeFromZone(e,t.range.zone);return{id:t.id,range:o,config:ze(t.config),type:"dynamic"}}applyRangeChangeOnTable(e,t,o){const s=o(t.range);let i;switch(s.changeType){case"REMOVE":return void this.history.update("tables",e,t.id,void 0);case"NONE":return;default:i=s.range}if("dynamic"===t.type){const o=this.updateDynamicTable(t,i);return void this.history.update("tables",e,t.id,o)}const n=[];for(const e of t.filters){const s=o(e.rangeWithHeaders);switch(s.changeType){case"REMOVE":continue;case"NONE":n.push(e);break;default:const o=s.range,i=C_(e.id,o,t.config,this.getters.getRangeFromZone);n.push(i)}}const r=i.zone;if(n.length<Tr(r).numberOfCols){for(let o=r.left;o<=r.right;o++)if(!n.find((e=>e.col===o))){const s=this.consumeNextId(),i={...r,left:o,right:o};n.push(this.createFilterFromZone(s,e,i,t.config))}n.sort(((e,t)=>e.col-t.col))}const a=this.createStaticTable(t.id,t.type,i,t.config,n);this.history.update("tables",e,t.id,a)}consumeNextId(){const e=`${this.nextTableId}`;return this.history.update("nextTableId",this.nextTableId+1),e}import(e){for(const t of e.sheets)for(const e of t.tables||[]){const o=this.consumeNextId(),s=e.config||wR,i=this.getters.getRangeFromSheetXC(t.id,e.range),n=e.type||"static",r="dynamic"===n?this.createDynamicTable(o,i,s):this.createStaticTable(o,n,i,s);this.history.update("tables",t.id,r.id,r)}}export(e){for(const t of e.sheets)for(const e of this.getCoreTables(t.id)){const o={range:fr(e.range.zone),type:e.type};mt(e.config,wR)||(o.config=e.config),t.tables.push(o)}}exportForExcel(e){for(const t of e.sheets)for(const e of this.getCoreTables(t.id)){const o=fr(e.range.zone);t.tables.push({range:o,filters:[],config:e.config})}}}).add("dataValidation",class extends Nk{static getters=["cellHasListDataValidationIcon","getDataValidationRule","getDataValidationRules","getValidationRuleForCell"];rules={};adaptRanges(e,t){this.adaptDVRanges(t,e),this.adaptDVFormulas(e)}adaptDVFormulas(e){for(const t in this.rules){for(let o=this.rules[t].length-1;o>=0;o--){const s=this.rules[t][o];for(let i=0;i<s.criterion.values.length;i++){const n=this.getters.adaptFormulaStringDependencies(t,s.criterion.values[i],e);this.history.update("rules",t,o,"criterion","values",i,n)}}}}adaptDVRanges(e,t){for(let o=this.rules[e].length-1;o>=0;o--){const s=this.rules[e][o];for(let i=s.ranges.length-1;i>=0;i--){const n=t(s.ranges[i]);switch(n.changeType){case"REMOVE":if(1===s.ranges.length)this.removeDataValidationRule(e,s.id);else{const t=s.ranges.slice();t.splice(i,1),this.history.update("rules",e,o,"ranges",t)}break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("rules",e,o,"ranges",i,n.range)}}}}allowDispatch(e){switch(e.type){case"ADD_DATA_VALIDATION_RULE":return this.getters.tryGetSheet(e.sheetId)?e.ranges.some((e=>!this.getters.tryGetSheet(e._sheetId)))?"InvalidSheetId":this.checkValidations(e,this.chainValidations(this.checkEmptyRange,this.checkValidRange,this.checkCriterionTypeIsValid,this.checkCriterionHasValidNumberOfValues,this.checkCriterionValuesAreValid)):"InvalidSheetId";case"REMOVE_DATA_VALIDATION_RULE":if(!this.getters.tryGetSheet(e.sheetId))return"InvalidSheetId";if(!this.rules[e.sheetId].find((t=>t.id===e.id)))return"UnknownDataValidationRule"}return"Success"}handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("rules",e.sheetId,[]);break;case"DUPLICATE_SHEET":{const t=ze(this.rules[e.sheetId]).map((t=>({...t,ranges:t.ranges.map((t=>Ca(e.sheetId,e.sheetIdTo,t)))})));this.history.update("rules",e.sheetIdTo,t);break}case"DELETE_SHEET":{const t={...this.rules};delete t[e.sheetId],this.history.update("rules",t);break}case"REMOVE_DATA_VALIDATION_RULE":this.removeDataValidationRule(e.sheetId,e.id);break;case"ADD_DATA_VALIDATION_RULE":{const t=e.ranges.map((e=>this.getters.getRangeFromRangeData(e)));this.addDataValidationRule(e.sheetId,{...e.rule,ranges:t});break}case"DELETE_CONTENT":{const t=nr(e.target),o=e.sheetId;for(const e of t)for(let t=e.top;t<=e.bottom;t++)for(let s=e.left;s<=e.right;s++){const e=this.getValidationRuleForCell({sheetId:o,col:s,row:t});if(e&&("isBoolean"===e.criterion.type||"isValueInList"===e.criterion.type&&!this.getters.getCell({sheetId:o,col:s,row:t})?.content)){const e=this.rules[o],i=[this.getters.getRangeFromSheetXC(o,Po(s,t))],n=this.removeRangesFromRules(o,i,e);this.history.update("rules",o,n)}}}}}getDataValidationRules(e){return this.rules[e]}getDataValidationRule(e,t){return this.rules[e].find((e=>e.id===t))}getValidationRuleForCell({sheetId:e,col:t,row:o}){if(this.rules[e])for(const s of this.rules[e])for(const e of s.ranges)if(Er(t,o,e.zone))return s}cellHasListDataValidationIcon(e){const t=this.getValidationRuleForCell(e);return!!t&&!("isValueInList"!==t.criterion.type&&"isValueInRange"!==t.criterion.type||"arrow"!==t.criterion.displayStyle&&"chip"!==t.criterion.displayStyle)}addDataValidationRule(e,t){const o=this.rules[e];"isBoolean"===t.criterion.type?this.setCenterStyleToBooleanCells(t):"isValueInList"===t.criterion.type&&(t.criterion.values=Array.from(new Set(t.criterion.values)));const s=this.removeRangesFromRules(e,t.ranges,o,t.id),i=s.findIndex((e=>e.id===t.id));-1!==i?(s[i]=t,this.history.update("rules",e,s)):this.history.update("rules",e,[...s,t])}removeRangesFromRules(e,t,o,s){o=ze(o);for(const e of o)e.id!==s&&(e.ranges=this.getters.recomputeRanges(e.ranges,t));return o.filter((e=>e.ranges.length>0))}removeDataValidationRule(e,t){const o=this.rules[e].filter((e=>e.id!==t));this.history.update("rules",e,o)}setCenterStyleToBooleanCells(e){for(const t of wa(e.ranges)){const e=this.getters.getCell(t),o={...e?.style,align:e?.style?.align??"center",verticalAlign:e?.style?.verticalAlign??"middle"};this.dispatch("UPDATE_CELL",{...t,style:o})}}checkEmptyRange(e){return e.ranges.length?"Success":"EmptyRange"}import(e){for(const t of e.sheets)if(this.rules[t.id]=[],t.dataValidationRules)for(const e of t.dataValidationRules)this.rules[t.id].push({...e,ranges:e.ranges.map((e=>this.getters.getRangeFromSheetXC(t.id,e)))})}export(e){if(e.sheets)for(const t of e.sheets){t.dataValidationRules=[];for(const e of this.rules[t.id])t.dataValidationRules.push({...e,ranges:e.ranges.map((e=>this.getters.getRangeString(e,t.id)))})}}exportForExcel(e){if(e.sheets)for(const t of e.sheets){t.dataValidationRules=[];for(const e of this.rules[t.id]){const o={...ze(e),ranges:e.ranges.map((e=>this.getters.getRangeString(e,t.id,{useBoundedReference:!0})))};"isValueInRange"===e.criterion.type&&(o.criterion.values=e.criterion.values.map((e=>{const o=this.getters.getRangeFromSheetXC(t.id,e);return this.getters.getRangeString(o,t.id,{useBoundedReference:!0,useFixedReference:!0})}))),t.dataValidationRules.push(o)}}}checkCriterionTypeIsValid(e){return eE.contains(e.rule.criterion.type)?"Success":"UnknownDataValidationCriterionType"}checkCriterionHasValidNumberOfValues(e){const t=e.rule.criterion,o=eE.get(t.type).numberOfValues(t);return void 0!==o&&t.values.length!==o?"InvalidNumberOfCriterionValues":"Success"}checkCriterionValuesAreValid(e){const t=e.rule.criterion,o=eE.get(t.type);return t.values.some((e=>"onlyFormulas"===o.allowedValues&&!e.startsWith("=")||(e.startsWith("=")?"onlyLiterals"===o.allowedValues||HS(e).isBadExpression:!o.isCriterionValueValid(e))))?"InvalidDataValidationCriterionValue":"Success"}checkValidRange(e){const t=e.ranges.map((e=>this.getters.getRangeFromRangeData(e))),o=t.map((t=>this.getters.getRangeString(t,e.sheetId)));return o.some((e=>!this.getters.isRangeValid(e)))?"InvalidRange":"Success"}}).add("cell",class extends Nk{static getters=["zoneToXC","getCells","getTranslatedCellFormula","getCellStyle","getCellById","getFormulaString","getFormulaMovedInSheet"];nextId=1;cells={};adaptRanges(e,t,o){for(const s of Object.keys(this.cells))for(const i of Object.values(this.cells[s]||{}))if(i.isFormula)for(const n of i.compiledFormula.dependencies)if(n.sheetId===t||n.invalidSheetName===o.old){const t=e(n);"NONE"!==t.changeType&&this.history.update("cells",s,i.id,"compiledFormula","dependencies",i.compiledFormula.dependencies.indexOf(n),t.range)}}allowDispatch(e){switch(e.type){case"UPDATE_CELL":return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessUpdateCell);case"CLEAR_CELL":return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessClearCell);case"UPDATE_CELL_POSITION":return!e.cellId||this.cells[e.sheetId]?.[e.cellId]?"Success":"InvalidCellId";default:return"Success"}}handle(e){switch(e.type){case"SET_FORMATTING":"style"in e&&this.setStyle(e.sheetId,e.target,e.style),"format"in e&&void 0!==e.format&&this.setFormatter(e.sheetId,e.target,e.format);break;case"CLEAR_FORMATTING":this.clearFormatting(e.sheetId,e.target);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case"UPDATE_CELL":this.updateCell(e.sheetId,e.col,e.row,e);break;case"CLEAR_CELL":this.dispatch("UPDATE_CELL",{sheetId:e.sheetId,col:e.col,row:e.row,content:"",style:null,format:""});break;case"CLEAR_CELLS":this.clearCells(e.sheetId,e.target);break;case"DELETE_CONTENT":this.clearZones(e.sheetId,e.target);break;case"DELETE_SHEET":this.history.update("cells",e.sheetId,void 0)}}clearZones(e,t){for(const o of nr(t))for(let t=o.left;t<=o.right;t++)for(let s=o.top;s<=o.bottom;s++){const o=this.getters.getCell({sheetId:e,col:t,row:s});(o?.isFormula||o?.content)&&this.dispatch("UPDATE_CELL",{sheetId:e,content:"",col:t,row:s})}}setFormatter(e,t,o){for(const s of nr(t))for(let t=s.top;t<=s.bottom;t++)for(let i=s.left;i<=s.right;i++)this.dispatch("UPDATE_CELL",{sheetId:e,col:i,row:t,format:o})}clearFormatting(e,t){for(const o of nr(t))for(let t=o.left;t<=o.right;t++)for(let s=o.top;s<=o.bottom;s++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:s,style:null,format:""})}clearCells(e,t){for(const o of t)for(let t=o.left;t<=o.right;t++)for(let s=o.top;s<=o.bottom;s++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:s,content:"",style:null,format:""})}handleAddColumnsRows(e,t){let o,s;"before"===e.position?(o=je(e.base,e.base+e.quantity),s=e.base+e.quantity):(o=je(e.base+1,e.base+e.quantity+1),s=e.base),t(e.sheetId,s,o)}import(e){for(const t of e.sheets){const o=t.id,s=new $D;for(const e in t.cells)if(t.cells[e]){const{col:o,row:i}=Fo(e),n={sheetId:t.id,col:o,row:i};s.set(n,{content:t.cells[e]})}for(const[e,o]of[["style",t.styles],["format",t.formats]])for(const[i,n]of qr(t.id,o)){const t=s.get(i);t?t[e]=n:s.set(i,{[e]:n})}for(const i of s.keysForSheet(o)){const o=s.get(i);if(o?.content||o?.format||o?.style){const s=this.importCell(t.id,o?.content,o?.style?e.styles[o?.style]:void 0,o?.format?e.formats[o?.format]:void 0);this.history.update("cells",t.id,s.id,s),this.dispatch("UPDATE_CELL_POSITION",{cellId:s.id,...i})}}}}export(e){const t={},o={};for(const s of e.sheets){const e=[],i=[],n={},r=Object.keys(this.cells[s.id]||{}).map((e=>this.getters.getCellPosition(e))).sort(((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col));for(const s of r){const r=this.getters.getCell(s),a=Po(s.col,s.row),l=this.removeDefaultStyleValues(r.style);if(Object.keys(l).length){const o=Gr(l,t);e[o]??=[],e[o].push(s)}if(r.format){const e=Gr(r.format,o);i[e]??=[],i[e].push(s)}r.content&&(n[a]=r.content)}s.styles=Wr(e),s.formats=Wr(i),s.cells=n}e.styles=t,e.formats=o}importCell(e,t,o,s){const i=this.getNextUid();return this.createCell(i,t||"",s,o,e)}exportForExcel(e){this.export(e);const t=[];for(const o in e.formats||[])jn(e.formats[o])||(t.push(Number(o)),delete e.formats[o]);if(t.length)for(const o of e.sheets)for(const e in o.formats){const s=o.formats[e];s&&t.includes(s)&&delete o.formats[e]}}removeDefaultStyleValues(e){const t={...e};for(const e in de)t[e]===de[e]&&delete t[e];return t}getCells(e){return this.cells[e]||{}}getCellById(e){const t=this.getters.getCellPosition(e);return this.cells[t.sheetId][e]}getFormulaString(e,t,o,s=!1){if(!o.length)return dt(t.map((e=>e.value)));let i=0;return dt(t.map((t=>{if("REFERENCE"===t.type){const t=o[i++];return this.getters.getRangeString(t,e,{useBoundedReference:s})}return t.value})))}getTranslatedCellFormula(e,t,o,s){const i=this.getters.createAdaptedRanges(US(s).dependencies.map((t=>this.getters.getRangeFromSheetXC(e,t))),t,o,e);return this.getFormulaString(e,s,i)}getFormulaMovedInSheet(e,t,o){const s=US(o).dependencies.map((t=>this.getters.getRangeFromSheetXC(e,t))),i=this.getters.removeRangesSheetPrefix(t,s);return this.getFormulaString(t,o,i)}getCellStyle(e){return this.getters.getCell(e)?.style||{}}zoneToXC(e,t,o=[{colFixed:!1,rowFixed:!1}]){const s=Po((t=this.getters.expandZone(e,t)).left,t.top,o[0]),i=Po(t.right,t.bottom,o.length>1?o[1]:o[0]),n=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),r=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),a=n.col===r.col&&n.row===r.row;return s===i||a?s:s+":"+i}setStyle(e,t,o){for(const s of nr(t))for(let t=s.left;t<=s.right;t++)for(let i=s.top;i<=s.bottom;i++){const s=this.getters.getCell({sheetId:e,col:t,row:i});this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,style:o?{...s?.style,...o}:void 0})}}copyColumnStyle(e,t,o){for(let s=0;s<this.getters.getNumberRows(e);s++){const i=this.getFormat(e,t,s);if(i.style||i.format)for(const t of o)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:s,...i})}}copyRowStyle(e,t,o){for(let s=0;s<this.getters.getNumberCols(e);s++){const i=this.getFormat(e,s,t);if(i.style||i.format)for(const t of o)this.dispatch("UPDATE_CELL",{sheetId:e,col:s,row:t,...i})}}getFormat(e,t,o){const s={},i=this.getters.getMainCellPosition({sheetId:e,col:t,row:o}),n=this.getters.getCell(i);return n&&(n.style&&(s.style=n.style),n.format&&(s.format=n.format)),s}getNextUid(){const e=this.nextId.toString();return this.history.update("nextId",this.nextId+1),e}updateCell(e,t,o,s){const i=this.getters.getCell({sheetId:e,col:t,row:o}),n="content"in s||"formula"in s,r=n?It(s?.content):i?.content||"";let a;a=void 0!==s.style?s.style||void 0:i?i.style:void 0;const l="format"in s?s.format:i&&i.format;if((n&&!r&&!s.formula||!n&&(!i||""===i.content))&&!a&&!l)return void(i&&(this.history.update("cells",e,i.id,void 0),this.dispatch("UPDATE_CELL_POSITION",{cellId:void 0,col:t,row:o,sheetId:e})));const c=i?.id||this.getNextUid(),h=this.createCell(c,r,l,a,e);this.history.update("cells",e,h.id,h),this.dispatch("UPDATE_CELL_POSITION",{cellId:h.id,col:t,row:o,sheetId:e})}createCell(e,t,o,s,i){return t.startsWith("=")?this.createFormulaCell(e,t,o,s,i):this.createLiteralCell(e,t,o,s)}createLiteralCell(e,t,o,s){const i=this.getters.getLocale(),n=Kn(t,i);return Yn(o=o||("number"==typeof n?Nn(t,i)||kn(t):void 0))||gi(t)||(t=wi(n)),{id:e,content:t,style:s,format:o,isFormula:!1,parsedValue:n}}createFormulaCell(e,t,o,s,i){const n=HS(t);return n.dependencies.length?this.createFormulaCellWithDependencies(e,n,o,s,i):{id:e,content:t,style:s,format:o,isFormula:!0,compiledFormula:{...n,dependencies:[]}}}createFormulaCellWithDependencies(e,t,o,s,i){const n=[];for(const e of t.dependencies)n.push(this.getters.getRangeFromSheetXC(i,e));return new kk(e,t,o,s,n,i,this.getters.getRangeString)}checkCellOutOfSheet(e){const{sheetId:t,col:o,row:s}=e;if(!this.getters.tryGetSheet(t))return"InvalidSheetId";return Er(o,s,this.getters.getSheetZone(t))?"Success":"TargetOutOfSheet"}checkUselessClearCell(e){const t=this.getters.getCell(e);return t&&(t.content||t.style||t.format)?"Success":"NoChanges"}checkUselessUpdateCell(e){const t=this.getters.getCell(e),o="style"in e,s="format"in e;return("content"in e||"formula"in e)&&t?.content!==e.content||o&&!mt(t?.style,e.style)||s&&t?.format!==e.format?"Success":"NoChanges"}}).add("merge",class extends Nk{static getters=["isInMerge","isInSameMerge","isMergeHidden","getMainCellPosition","expandZone","doesIntersectMerge","doesColumnsHaveCommonMerges","doesRowsHaveCommonMerges","getMerges","getMerge","getMergesInZone","isSingleCellOrMerge","getSelectionRangeString","isMainCellPosition"];nextId=1;merges={};mergeCellMap={};allowDispatch(e){const t="force"in e&&!!e.force;switch(e.type){case"ADD_MERGE":return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case"UPDATE_CELL":return this.checkMergedContentUpdate(e);case"REMOVE_MERGE":return this.checkMergeExists(e);default:return"Success"}}handle(e){switch(e.type){case"CREATE_SHEET":case"DELETE_SHEET":this.history.update("merges",e.sheetId,{}),this.history.update("mergeCellMap",e.sheetId,{});break;case"DUPLICATE_SHEET":const t=this.merges[e.sheetId];if(!t)break;for(const o of Object.values(t).filter(lt))this.addMerge(e.sheetIdTo,o.zone);break;case"ADD_MERGE":for(const t of e.target)this.addMerge(e.sheetId,t);break;case"REMOVE_MERGE":for(const t of e.target)this.removeMerge(e.sheetId,t)}}adaptRanges(e,t){this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map((t=>this.getMergeById(e,parseInt(t,10)))).filter(lt)}getMerge({sheetId:e,col:t,row:o}){const s=this.mergeCellMap[e],i=s?t in s&&s[t]?.[o]:void 0;return i?this.getMergeById(e,i):void 0}getMergesInZone(e,t){const o=this.mergeCellMap[e];if(!o)return[];const s=new Set;for(let e=t.left;e<=t.right;e++)for(let i=t.top;i<=t.bottom;i++){const t=o[e]?.[i];t&&s.add(t)}return Array.from(s).map((t=>this.getMergeById(e,t))).filter(lt)}getSelectionRangeString(e,t){const o=this.getters.expandZone(e.sheetId,e.zone),s=pa({...e,zone:{...o,bottom:va(e)?void 0:o.bottom,right:ba(e)?void 0:o.right}},this.getters.getSheetSize),i=this.getters.getRangeString(s,t);if(this.isSingleCellOrMerge(e.sheetId,e.zone)){const{sheetName:e,xc:t}=ra(i);return aa(e,t.split(":")[0])}return i}doesIntersectMerge(e,t){for(const o of this.getMerges(e))if(xr(t,o))return!0;return!1}doesColumnsHaveCommonMerges(e,t,o){const s=this.getters.getSheet(e);for(let i=0;i<this.getters.getNumberRows(e);i++)if(this.isInSameMerge(s.id,t,i,o,i))return!0;return!1}doesRowsHaveCommonMerges(e,t,o){const s=this.getters.getSheet(e);for(let i=0;i<=this.getters.getNumberCols(e);i++)if(this.isInSameMerge(s.id,i,t,i,o))return!0;return!1}expandZone(e,t){const{left:o,right:s,top:i,bottom:n}=t;let r={left:o,right:s,top:i,bottom:n};for(const t in this.merges[e]){const o=this.getMergeById(e,parseInt(t));o&&xr(o,r)&&(r=yr(o,r))}return Ir(r,t)?r:this.expandZone(e,r)}isInSameMerge(e,t,o,s,i){const n=this.getMerge({sheetId:e,col:t,row:o}),r=this.getMerge({sheetId:e,col:s,row:i});return!(!n||!r)&&Ir(n,r)}isInMerge({sheetId:e,col:t,row:o}){const s=this.mergeCellMap[e];return!!s&&(t in s&&Boolean(s[t]?.[o]))}getMainCellPosition(e){const t=this.getMerge(e);return t?{sheetId:e.sheetId,col:t.left,row:t.top}:e}isMergeHidden(e,t){const o=this.getters.getHiddenColsGroups(e),s=this.getters.getHiddenRowsGroups(e);for(const e of o)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(const e of s)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){const o=this.getMerge({sheetId:e,col:t.left,row:t.top});if(o)return Ir(t,o);const{numberOfCols:s,numberOfRows:i}=Tr(t);return 1===s&&1===i}isMainCellPosition(e){return mt(this.getMainCellPosition(e),e)}isMergeDestructive(e,t){let{left:o,right:s,top:i,bottom:n}=t;s=Ze(s,0,this.getters.getNumberCols(e)-1),n=Ze(n,0,this.getters.getNumberRows(e)-1);for(let t=i;t<=n;t++)for(let n=o;n<=s;n++)if(n!==o||t!==i){const o=this.getters.getCell({sheetId:e,col:n,row:t});if(o&&""!==o.content)return!0}return!1}getMergeById(e,t){const o=this.merges[e]?.[t];return void 0!==o?Uk(t,o):void 0}checkDestructiveMerge({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return"Success";return t.some((t=>this.isMergeDestructive(e,t)))?"MergeIsDestructive":"Success"}checkOverlap({target:e}){for(const t of e)for(const o of e)if(t!==o&&xr(t,o))return"MergeOverlap";return"Success"}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return"Success";const{xSplit:o,ySplit:s}=this.getters.getPaneDivisions(e);return Hr(t,o,s)?"FrozenPaneOverlap":"Success"}checkMergedContentUpdate(e){const{col:t,row:o,content:s}=e;if(void 0===s)return"Success";const{col:i,row:n}=this.getMainCellPosition(e);return i===t&&n===o?"Success":"CellIsMerged"}checkMergeExists(e){const{sheetId:t,target:o}=e;for(const e of o){const{left:o,top:s}=e,i=this.getMerge({sheetId:t,col:o,row:s});if(void 0===i||!Ir(e,i))return"InvalidTarget"}return"Success"}addMerge(e,t){let{left:o,right:s,top:i,bottom:n}=t;s=Ze(s,0,this.getters.getNumberCols(e)-1),n=Ze(n,0,this.getters.getNumberRows(e)-1);if(Po(o,i)===Po(s,n))return;const r=this.getters.getCell({sheetId:e,col:o,row:i}),a=this.nextId++;this.history.update("merges",e,a,this.getters.getRangeFromSheetXC(e,fr({left:o,top:i,right:s,bottom:n})));const l=new Set;for(let t=i;t<=n;t++)for(let n=o;n<=s;n++){n===o&&t===i||this.dispatch("UPDATE_CELL",{sheetId:e,col:n,row:t,style:r?r.style:null,content:""});const s=this.getMerge({sheetId:e,col:n,row:t});s&&l.add(s.id),this.history.update("mergeCellMap",e,n,t,a)}for(const t of l){const{top:o,bottom:s,left:i,right:n}=this.getMergeById(e,t);for(let t=o;t<=s;t++)for(let o=i;o<=n;o++){const s={sheetId:e,col:o,row:t},i=this.getMerge(s);i&&i.id===a||(this.history.update("mergeCellMap",e,o,t,void 0),this.dispatch("CLEAR_CELL",s))}this.history.update("merges",e,t,void 0)}}removeMerge(e,t){const{left:o,top:s,bottom:i,right:n}=t,r=this.getMerge({sheetId:e,col:o,row:s});if(void 0!==r&&Ir(t,r)){this.history.update("merges",e,r.id,void 0);for(let t=s;t<=i;t++)for(let s=o;s<=n;s++)this.history.update("mergeCellMap",e,s,t,void 0)}}applyRangeChangeOnSheet(e,t){const o=Object.entries(this.merges[e]||{});for(const[s,i]of o)if(i){const o=i.zone,n=t(i);switch(n.changeType){case"NONE":break;case"REMOVE":this.removeMerge(e,o);break;default:const{numberOfCols:t,numberOfRows:i}=Tr(n.range.zone);1===t&&1===i?this.removeMerge(e,o):this.history.update("merges",e,parseInt(s,10),n.range)}}this.history.update("mergeCellMap",e,{});for(const t of this.getMerges(e))for(const{col:o,row:s}of _r(t))this.history.update("mergeCellMap",e,o,s,t.id)}import(e){const t=e.sheets||[];for(const e of t)this.history.update("merges",e.id,{}),this.history.update("mergeCellMap",e.id,{}),e.merges&&this.importMerges(e.id,e.merges)}importMerges(e,t){for(const o of t)this.addMerge(e,ur(o))}export(e){for(const t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...Hk(e))}}exportForExcel(e){this.export(e)}}).add("headerSize",class extends Nk{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,ze(this.sizes[e.sheetId]));break;case"DELETE_SHEET":const t={...this.sizes};delete t[e.sheetId],this.history.update("sizes",t);break;case"REMOVE_COLUMNS_ROWS":{const t=Rt(this.sizes[e.sheetId][e.dimension],e.elements);this.history.update("sizes",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{const t=[...this.sizes[e.sheetId][e.dimension]],o=pt(e.position,e.base),s=t[e.base];t.splice(o,0,...Array(e.quantity).fill(s)),this.history.update("sizes",e.sheetId,e.dimension,t);break}case"RESIZE_COLUMNS_ROWS":if("ROW"===e.dimension)for(const t of e.elements)this.history.update("sizes",e.sheetId,e.dimension,t,e.size||void 0);else for(const t of e.elements)this.history.update("sizes",e.sheetId,e.dimension,t,e.size||void 0)}}getColSize(e,t){return Math.round(this.sizes[e]?.COL[t]||se)}getUserRowSize(e,t){const o=this.sizes[e]?.ROW[t];return o?Math.round(o):void 0}import(e){for(const t of e.sheets){const e={COL:Array(t.colNumber).fill(void 0),ROW:Array(t.rowNumber).fill(void 0)};for(const[o,s]of Object.entries(t.rows))s.size&&(e.ROW[o]=s.size);for(const[o,s]of Object.entries(t.cols))s.size&&(e.COL[o]=s.size);this.sizes[t.id]=e}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(const o of e.sheets){void 0===o.rows&&(o.rows={});for(const e of je(0,this.getters.getNumberRows(o.id)))(t||this.sizes[o.id].ROW[e])&&(o.rows[e]={...o.rows[e],size:this.getUserRowSize(o.id,e)??ie});void 0===o.cols&&(o.cols={});for(const e of je(0,this.getters.getNumberCols(o.id)))(t||this.sizes[o.id].COL[e])&&(o.cols[e]={...o.cols[e],size:this.getColSize(o.id,e)})}}}).add("borders",class extends Nk{static getters=["getCellBorder","getBordersColors"];borders={};allowDispatch(e){return"SET_BORDER"===e.type?this.checkBordersUnchanged(e):"Success"}handle(e){switch(e.type){case"ADD_MERGE":for(const t of e.target)this.addBordersToMerge(e.sheetId,t);break;case"DUPLICATE_SHEET":const t=this.borders[e.sheetId];if(t){const o=t.slice().map((e=>e?.slice().map((e=>ze(e)))));this.history.update("borders",e.sheetIdTo,o)}break;case"DELETE_SHEET":const o={...this.borders};delete o[e.sheetId],this.history.update("borders",o);break;case"SET_BORDER":this.setBorder(e.sheetId,e.col,e.row,e.border);break;case"SET_BORDERS_ON_TARGET":for(const t of e.target)for(let o=t.top;o<=t.bottom;o++)for(let s=t.left;s<=t.right;s++)this.setBorder(e.sheetId,s,o,e.border);break;case"SET_ZONE_BORDERS":if(e.border){const 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||ve,color:e.border.color||be})}break;case"CLEAR_FORMATTING":this.clearBorders(e.sheetId,e.target);break;case"REMOVE_COLUMNS_ROWS":const s=[...e.elements].sort(((e,t)=>t-e));for(const t of Ye(s))if("COL"===e.dimension){const o=this.getters.getColsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[o]),this.shiftBordersHorizontally(e.sheetId,t[0]+1,-t.length)}else{const o=this.getters.getRowsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[o]),this.shiftBordersVertically(e.sheetId,t[0]+1,-t.length)}break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumns(e):this.handleAddRows(e)}}handleAddColumns(e){let t,o;"before"===e.position?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity),t=e.base-1,o=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity),t=e.base,o=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,o)}handleAddRows(e){let t,o;"before"===e.position?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity),t=e.base-1,o=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity),t=e.base,o=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,o)}getCellBorder({sheetId:e,col:t,row:o}){const s=this.borders[e]?.[t]?.[o];return s?.top||s?.bottom||s?.left||s?.right?ze(s):null}getBordersColors(e){const t=[],o=this.borders[e];if(o)for(const e of o.filter(lt))for(const o of e)if(o)for(const e of["top","bottom","left","right"]){const s=o[e]?.color;s&&t.push(s)}return t}ensureColumnBorderContinuity(e,t,o){const s=je(t+1,o);for(let i=0;i<this.getters.getNumberRows(e);i++){const n=this.getCellBorder({sheetId:e,col:t,row:i}),r=this.getCellBorder({sheetId:e,col:o,row:i});if(n&&r){const t=this.getCommonSides(n,r);for(const o of s)this.addBorder(e,o,i,t)}}}ensureRowBorderContinuity(e,t,o){const s=je(t+1,o);for(let i=0;i<this.getters.getNumberCols(e);i++){const n=this.getCellBorder({sheetId:e,col:i,row:t}),r=this.getCellBorder({sheetId:e,col:i,row:o});if(n&&r){const t=this.getCommonSides(n,r);for(const o of s)this.addBorder(e,i,o,t)}}}getCommonSides(e,t){const o={};for(const s of["top","bottom","left","right"])e[s]&&mt(e[s],t[s])&&(o[s]=e[s]);return o}getColumnsWithBorders(e){const t=this.borders[e];return t?Object.keys(t).map((e=>parseInt(e,10))):[]}getRowsWithBorders(e){const t=this.borders[e]?.filter(lt);if(!t)return[];const o=new Set;for(const e of t)for(const t in e)o.add(parseInt(t,10));return Array.from(o)}getRowsRange(e){return this.borders[e]?je(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,o){this.borders[e]&&this.getColumnsWithBorders(e).filter((e=>e>=t)).sort(((e,t)=>o<0?e-t:t-e)).forEach((t=>{this.moveBordersOfColumn(e,t,o)}))}shiftBordersVertically(e,t,o){this.borders[e]&&(o<0&&this.moveBordersOfRow(e,t,o,{destructive:!1}),this.getRowsWithBorders(e).filter((e=>e>=t)).sort(((e,t)=>o<0?e-t:t-e)).forEach((t=>{this.moveBordersOfRow(e,t,o)})))}moveBordersOfRow(e,t,o,{destructive:s}={destructive:!0}){const i=this.borders[e];i&&this.getColumnsWithBorders(e).forEach((n=>{const r=i[n]?.[t+o],a=i[n]?.[t];this.history.update("borders",e,n,t+o,s?a:a||r),this.history.update("borders",e,n,t,void 0)}))}moveBordersOfColumn(e,t,o,{destructive:s}={destructive:!0}){const i=this.borders[e];i&&this.getRowsRange(e).forEach((n=>{const r=i[t+o]?.[n],a=i[t]?.[n];this.history.update("borders",e,t+o,n,s?a:a||r),s&&this.history.update("borders",e,t,n,void 0)}))}setBorder(e,t,o,s,i=!0){const n=this.getters.getNumberCols(e)-1,r=this.getters.getNumberRows(e)-1;!i&&this.borders[e]?.[t]?.[o]?.left||(this.history.update("borders",e,t,o,"left",s?.left),s?.left&&t>0&&!mt(this.borders[e]?.[t-1]?.[o]?.right,s?.left)&&this.history.update("borders",e,t-1,o,"right",void 0)),!i&&this.borders[e]?.[t]?.[o]?.top||(this.history.update("borders",e,t,o,"top",s?.top),s?.top&&o>0&&!mt(this.borders[e]?.[t]?.[o-1]?.bottom,s?.top)&&this.history.update("borders",e,t,o-1,"bottom",void 0)),!i&&this.borders[e]?.[t]?.[o]?.right||(this.history.update("borders",e,t,o,"right",s?.right),s?.right&&t<n&&!mt(this.borders[e]?.[t+1]?.[o]?.left,s?.right)&&this.history.update("borders",e,t+1,o,"left",void 0)),!i&&this.borders[e]?.[t]?.[o]?.bottom||(this.history.update("borders",e,t,o,"bottom",s?.bottom),s?.bottom&&o<r&&!mt(this.borders[e]?.[t]?.[o+1]?.top,s?.bottom)&&this.history.update("borders",e,t,o+1,"top",void 0))}clearBorders(e,t,o=!1){const s=this.getters.getNumberCols(e)-1,i=this.getters.getNumberRows(e)-1;for(const n of nr(t))for(let t=n.top;t<=n.bottom;t++){o&&(n.left>0&&this.history.update("borders",e,n.left-1,t,"right",void 0),n.right<s&&this.history.update("borders",e,n.right+1,t,"left",void 0));for(let s=n.left;s<=n.right;s++)this.history.update("borders",e,s,t,void 0),o&&(n.top>0&&this.history.update("borders",e,s,n.top-1,"bottom",void 0),n.bottom<i&&this.history.update("borders",e,s,n.bottom+1,"top",void 0))}}clearInsideBorders(e,t){for(const o of t)for(let t=o.top;t<=o.bottom;t++)for(let s=o.left;s<=o.right;s++)this.history.update("borders",e,s,t,void 0)}addBorder(e,t,o,s){this.setBorder(e,t,o,{...this.getCellBorder({sheetId:e,col:t,row:o}),...s})}setBorders(e,t,o,s){if("clear"===o)return this.clearBorders(e,t,!0);for(const i of nr(t)){if("all"===o)for(let t=i.top;t<=i.bottom;t++)for(let o=i.left;o<=i.right;o++)this.addBorder(e,o,t,{top:s,right:s,bottom:s,left:s});if("h"===o||"hv"===o){if(i.top===i.bottom)continue;for(let t=i.left;t<=i.right;t++){this.addBorder(e,t,i.top,{bottom:s});for(let o=i.top+1;o<i.bottom;o++)this.addBorder(e,t,o,{top:s,bottom:s});this.addBorder(e,t,i.bottom,{top:s})}}if("v"===o||"hv"===o){if(i.left===i.right)continue;for(let t=i.top;t<=i.bottom;t++){this.addBorder(e,i.left,t,{right:s});for(let o=i.left+1;o<i.right;o++)this.addBorder(e,o,t,{left:s,right:s});this.addBorder(e,i.right,t,{left:s})}}if("left"===o||"external"===o)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.left,t,{left:s});if("right"===o||"external"===o)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.right,t,{right:s});if("top"===o||"external"===o)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.top,{top:s});if("bottom"===o||"external"===o)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.bottom,{bottom:s})}}addBordersToMerge(e,t){const{left:o,right:s,top:i,bottom:n}=t,r=this.getCellBorder({sheetId:e,col:o,row:i}),a=this.getCellBorder({sheetId:e,col:s,row:n});this.clearBorders(e,[t]),r?.top&&this.setBorders(e,[{...t,bottom:i}],"top",r.top),r?.left&&this.setBorders(e,[{...t,right:o}],"left",r.left),a?.bottom?this.setBorders(e,[{...t,top:n}],"bottom",a.bottom):r?.bottom&&this.setBorders(e,[{...t,top:n}],"bottom",r.bottom),a?.right?this.setBorders(e,[{...t,left:s}],"right",a.right):r?.right&&this.setBorders(e,[{...t,left:s}],"right",r.right)}checkBordersUnchanged(e){const t=this.getCellBorder(e),o=!(e.border?.bottom||e.border?.left||e.border?.right||e.border?.top);return!t&&o||mt(t,e.border)?"NoChanges":"Success"}import(e){if(Object.keys(e.borders||{}).length)for(const t of e.sheets)for(const[o,s]of qr(t.id,t.borders)){const{sheetId:t,col:i,row:n}=o,r=e.borders[s];this.setBorder(t,i,n,r,!1)}for(const t of e.sheets)if(t.merges)for(const e of t.merges)this.addBordersToMerge(t.id,ur(e))}export(e){const t={};for(const o of e.sheets){const e={};for(let s=0;s<o.colNumber;s++)for(let i=0;i<o.rowNumber;i++){const n=this.getCellBorder({sheetId:o.id,col:s,row:i});if(n){const r=Gr(n,t),a={sheetId:o.id,col:s,row:i};e[r]??=[],e[r].push(a)}}o.borders=Wr(e)}e.borders=t}exportForExcel(e){this.export(e)}}).add("conditional formatting",class extends Nk{static getters=["getConditionalFormats","getRulesSelection","getRulesByCell","getAdaptedCfRanges"];cfRules={};adaptCFFormulas(e){for(const t in this.cfRules)for(const o of this.cfRules[t])if("DataBarRule"===o.rule.type&&o.rule.rangeValues){const s=e(o.rule.rangeValues);switch(s.changeType){case"REMOVE":this.history.update("cfRules",t,this.cfRules[t].indexOf(o),"rule","rangeValues",void 0);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",t,this.cfRules[t].indexOf(o),"rule","rangeValues",s.range)}}else if("CellIsRule"===o.rule.type)for(let s=0;s<o.rule.values.length;s++)this.history.update("cfRules",t,this.cfRules[t].indexOf(o),"rule","values",s,this.getters.adaptFormulaStringDependencies(t,o.rule.values[s],e));else if("IconSetRule"===o.rule.type)for(const s of["lowerInflectionPoint","upperInflectionPoint"])"formula"===o.rule[s].type&&this.history.update("cfRules",t,this.cfRules[t].indexOf(o),"rule",s,"value",this.getters.adaptFormulaStringDependencies(t,o.rule[s].value,e));else if("ColorScaleRule"===o.rule.type)for(const s of["minimum","maximum","midpoint"]){const i=o.rule[s];"formula"===i?.type&&i?.value&&this.history.update("cfRules",t,this.cfRules[t].indexOf(o),"rule",s,"value",this.getters.adaptFormulaStringDependencies(t,i.value,e))}}adaptCFRanges(e,t){for(const o of this.cfRules[e])for(const s of o.ranges){const i=t(s);switch(i.changeType){case"REMOVE":const t=o.ranges.slice();t.splice(o.ranges.indexOf(s),1),t.length>=1?this.history.update("cfRules",e,this.cfRules[e].indexOf(o),"ranges",t):this.removeConditionalFormatting(o.id,e);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",e,this.cfRules[e].indexOf(o),"ranges",o.ranges.indexOf(s),i.range)}}}adaptRanges(e,t){const o=t?[t]:Object.keys(this.cfRules);for(const t of o)this.adaptCFRanges(t,e);this.adaptCFFormulas(e)}allowDispatch(e){switch(e.type){case"ADD_CONDITIONAL_FORMAT":return e.ranges.some((e=>!this.getters.tryGetSheet(e._sheetId)))?"InvalidSheetId":this.checkValidations(e,this.checkCFRule,this.checkEmptyRange,this.checkCFHasChanged);case"CHANGE_CONDITIONAL_FORMAT_PRIORITY":return this.checkValidPriorityChange(e.cfId,e.delta,e.sheetId)}return"Success"}handle(e){switch(e.type){case"CREATE_SHEET":this.cfRules[e.sheetId]=[];break;case"DUPLICATE_SHEET":this.history.update("cfRules",e.sheetIdTo,[]);for(const t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case"DELETE_SHEET":const t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update("cfRules",t);break;case"ADD_CONDITIONAL_FORMAT":const o={...e.cf,ranges:e.ranges.map((t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId)))};this.addConditionalFormatting(o,e.sheetId);break;case"REMOVE_CONDITIONAL_FORMAT":this.removeConditionalFormatting(e.id,e.sheetId);break;case"CHANGE_CONDITIONAL_FORMAT_PRIORITY":this.changeCFPriority(e.cfId,e.delta,e.sheetId)}}import(e){for(const t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map((e=>this.mapToConditionalFormatInternal(t.id,e)))}export(e){if(e.sheets)for(const t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map((e=>this.mapToConditionalFormat(t.id,e))))}exportForExcel(e){if(e.sheets)for(const t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map((e=>this.mapToConditionalFormat(t.id,e,{useBoundedReference:!0}))))}getConditionalFormats(e){return this.cfRules[e]?.map((t=>this.mapToConditionalFormat(e,t)))||[]}getRulesSelection(e,t){const o=new Set;return t.forEach((t=>{this.getRulesByZone(e,t).forEach((e=>{o.add(e)}))})),Array.from(o)}getRulesByZone(e,t){const o=new Set;for(let s=t.top;s<=t.bottom;s++)for(let i=t.left;i<=t.right;i++){this.getRulesByCell(e,i,s).forEach((e=>{o.add(e.id)}))}return o}getRulesByCell(e,t,o){const s=[];for(const i of this.cfRules[e])for(const e of i.ranges)Er(t,o,e.zone)&&s.push(i);return new Set(s.map((t=>this.mapToConditionalFormat(e,t))))}getAdaptedCfRanges(e,t,o,s){if(0===o.length&&0===s.length)return;const i=this.getters.getConditionalFormats(e),n=i.findIndex((e=>e.id===t.id));let r=[];n>-1&&(r=i[n].ranges.map(dr));const a=nr(r,s);return nr([...o,...a],[]).map((t=>this.getters.getRangeDataFromZone(e,t)))}mapToConditionalFormat(e,t,{useBoundedReference:o}={useBoundedReference:!1}){const s=t.ranges.map((t=>this.getters.getRangeString(t,e,{useBoundedReference:o})));return"DataBarRule"!==t.rule.type?{...t,rule:{...t.rule},ranges:s}:{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues&&this.getters.getRangeString(t.rule.rangeValues,e,{useBoundedReference:o})},ranges:s}}mapToConditionalFormatInternal(e,t){const o=t.ranges.map((t=>this.getters.getRangeFromSheetXC(e,t)));return"DataBarRule"!==t.rule.type?{...t,rule:{...t.rule},ranges:o}:{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues?this.getters.getRangeFromSheetXC(e,t.rule.rangeValues):void 0},ranges:o}}addConditionalFormatting(e,t){const o=this.cfRules[t].slice(),s=o.findIndex((t=>t.id===e.id)),i=this.mapToConditionalFormatInternal(t,e);s>-1?o.splice(s,1,i):o.push(i),this.history.update("cfRules",t,o)}checkValidPriorityChange(e,t,o){if(!this.cfRules[o])return"InvalidSheetId";const s=this.cfRules[o].findIndex((t=>t.id===e));if(-1===s)return"InvalidConditionalFormatId";const i=s-t;return i<0||i>=this.cfRules[o].length?"InvalidConditionalFormatId":"Success"}checkEmptyRange(e){return e.ranges.length?"Success":"EmptyRange"}checkCFRule(e){const t=e.cf.rule;switch(t.type){case"CellIsRule":return this.checkValidations(t,this.checkOperatorArgsNumber,this.checkCFValues);case"ColorScaleRule":return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case"IconSetRule":return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)))}return"Success"}checkCFHasChanged(e){const t=this.mapToConditionalFormatInternal(e.sheetId,{...e.cf,ranges:e.ranges.map((t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId)))}),o=this.cfRules[e.sheetId]?.find((t=>t.id===e.cf.id));return o&&mt(t,o)?"NoChanges":"Success"}checkOperatorArgsNumber(e){const t=eE.get(e.operator).numberOfValues({type:e.operator,values:e.values});if(void 0===t||t>2)throw new Error("Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.");const o=[],s=e=>void 0===e||""===e;return t>=1&&s(e.values[0])&&o.push("FirstArgMissing"),t>=2&&s(e.values[1])&&o.push("SecondArgMissing"),o.length?o:"Success"}checkNaN(e,t){if(["number","percentage","percentile"].includes(e.type)&&(""===e.value||isNaN(e.value)))switch(t){case"min":return"MinNaN";case"max":return"MaxNaN";case"mid":return"MidNaN";case"upperInflectionPoint":return"ValueUpperInflectionNaN";case"lowerInflectionPoint":return"ValueLowerInflectionNaN"}return"Success"}checkFormulaCompilation(e,t){if("formula"!==e.type)return"Success";if(HS(e.value||"").isBadExpression)switch(t){case"min":return"MinInvalidFormula";case"max":return"MaxInvalidFormula";case"mid":return"MidInvalidFormula";case"upperInflectionPoint":return"ValueUpperInvalidFormula";case"lowerInflectionPoint":return"ValueLowerInvalidFormula"}return"Success"}checkThresholds(e){return this.batchValidations((t=>e(t.minimum,"min")),(t=>e(t.maximum,"max")),(t=>t.midpoint?e(t.midpoint,"mid"):"Success"))}checkInflectionPoints(e){return this.batchValidations((t=>e(t.lowerInflectionPoint,"lowerInflectionPoint")),(t=>e(t.upperInflectionPoint,"upperInflectionPoint")))}checkLowerBiggerThanUpper(e){const t=e.lowerInflectionPoint.value,o=e.upperInflectionPoint.value;return["number","percentage","percentile"].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(o)?"LowerBiggerThanUpper":"Success"}checkMinBiggerThanMax(e){const t=e.minimum.value,o=e.maximum.value;return["number","percentage","percentile"].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&Lk(t)>=Lk(o)?"MinBiggerThanMax":"Success"}checkMidBiggerThanMax(e){const t=e.midpoint?.value,o=e.maximum.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&Lk(t)>=Lk(o)?"MidBiggerThanMax":"Success"}checkMinBiggerThanMid(e){const t=e.minimum.value,o=e.midpoint?.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&Lk(t)>=Lk(o)?"MinBiggerThanMid":"Success"}checkCFValues(e){for(const t of e.values){if(!t.startsWith("="))continue;if(HS(t||"").isBadExpression)return"ValueCellIsInvalidFormula"}return"Success"}removeConditionalFormatting(e,t){const o=this.cfRules[t].findIndex((t=>t.id===e));if(-1!==o){const e=this.cfRules[t].slice();e.splice(o,1),this.history.update("cfRules",t,e)}}changeCFPriority(e,t,o){const s=this.cfRules[o].findIndex((t=>t.id===e)),i=this.cfRules[o][s],n=s-t,r=[...this.cfRules[o]];r.splice(s,1),r.splice(n,0,i),this.history.update("cfRules",o,r)}}).add("figures",class extends Nk{static getters=["getFigures","getFigure","getFigureSheetId"];figures={};insertionOrders=[];adaptRanges(e,t){for(const o of this.getFigures(t)){const s=e(this.getters.getRangeFromZone(t,{left:o.col,right:o.col,top:o.row,bottom:o.row}));if("MOVE"===s.changeType)this.history.update("figures",t,o.id,"col",s.range.zone.right),this.history.update("figures",t,o.id,"row",s.range.zone.bottom);else if("REMOVE"===s.changeType){const s=e(this.getters.getRangeFromZone(t,{left:0,right:o.col-1,top:0,bottom:o.row-1}));let{offset:i,col:n,row:r}=o;"NONE"!==s.changeType&&(n=s.range.zone.right+1,r=s.range.zone.bottom+1),({offset:i,col:n,row:r}=this.getPositionInSheet(t,{...o,col:n,row:r})),this.history.update("figures",t,o.id,"offset",i),this.history.update("figures",t,o.id,"col",n),this.history.update("figures",t,o.id,"row",r)}}}allowDispatch(e){switch(e.type){case"CREATE_FIGURE":return this.checkValidations(e,this.checkFigureDuplicate,this.checkFigureAnchorOffset);case"UPDATE_FIGURE":return this.checkValidations(e,this.checkFigureExists,this.checkFigureAnchorOffset);case"DELETE_FIGURE":return this.checkFigureExists(e);default:return"Success"}}beforeHandle(e){if("DELETE_SHEET"===e.type)this.getters.getFigures(e.sheetId).forEach((t=>{this.dispatch("DELETE_FIGURE",{figureId:t.id,sheetId:e.sheetId})}))}handle(e){switch(e.type){case"CREATE_SHEET":this.figures[e.sheetId]={};break;case"DELETE_SHEET":this.deleteSheet(e.sheetId);break;case"CREATE_FIGURE":const t={id:e.figureId,col:e.col,row:e.row,offset:e.offset,width:e.size.width,height:e.size.height,tag:e.tag};this.addFigure(t,e.sheetId);break;case"UPDATE_FIGURE":this.updateFigure(e);break;case"DELETE_FIGURE":this.removeFigure(e.figureId,e.sheetId);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.onColRemove(e.sheetId):this.onRowRemove(e.sheetId)}}onColRemove(e){const t=this.getters.getNumberCols(e),o=new Array(t+1);o[t]=0;for(let s=t-1;s>=0;s--)o[s]=o[s+1]+this.getters.getColSize(e,s);for(const t of this.getFigures(e))if(t.offset.x+t.width>o[t.col]){let s=t.offset.x,i=t.col;for(s=Math.min(s,o[i]-t.width);s<0&&i>0;)i--,s=o[i]-t.width;s!==t.offset.x&&this.history.update("figures",e,t.id,"offset",{x:Math.max(s,0),y:t.offset.y}),i!==t.col&&this.history.update("figures",e,t.id,"col",i)}}onRowRemove(e){const t=this.getters.getNumberRows(e),o=new Array(t+1);o[t]=0;for(let s=t-1;s>=0;s--)o[s]=o[s+1]+(this.getters.getUserRowSize(e,s)??ie);for(const t of this.getFigures(e))if(t.offset.y+t.height>o[t.row]){let s=t.offset.y,i=t.row;for(let t=this.getters.getUserRowSize(e,i)??ie;t<s;t=this.getters.getUserRowSize(e,i)??ie)i+=1,s-=t;for(s=Math.min(s,o[i]-t.height);s<0&&i>0;)i--,s=o[i]-t.height;s!==t.offset.y&&this.history.update("figures",e,t.id,"offset",{x:t.offset.x,y:Math.max(0,s)}),i!==t.row&&this.history.update("figures",e,t.id,"row",i)}else t.offset.y+t.height>o[0]&&this.history.update("figures",e,t.id,"offset",{x:t.offset.x,y:Math.max(o[0]-t.height,0)})}getPositionInSheet(e,t){const{numberOfRows:o,numberOfCols:s}=this.getters.getSheetSize(e);let i,n,r=0,a=0,{col:l,row:c}=t;const h={...t.offset};for(i=o;r<t.height&&i>0;i--)r+=this.getters.getUserRowSize(e,i-1)??ie;for(c>i?(c=i,h.y=Math.max(r-t.height,0)):c===i&&(h.y=Ze(h.y,0,Math.max(r-t.height,0))),n=s;a<t.width&&n>0;n--)a+=this.getters.getColSize(e,n-1);return l>n?(l=n,h.x=Math.max(a-t.width,0)):n===l&&(h.x=Ze(h.x,0,Math.max(a-t.width,0))),{col:l,row:c,offset:h}}updateFigure(e){if(!("figureId"in e)||!("sheetId"in e))return;const{figureId:t,sheetId:o,...s}=e,i={...this.getFigure(o,t),...s};for(const[e,t]of Object.entries(s))switch(e){case"offset":this.history.update("figures",o,i.id,e,t);break;case"col":case"row":case"width":case"height":void 0!==t&&this.history.update("figures",o,i.id,e,t)}}addFigure(e,t){this.history.update("figures",t,e.id,e),this.history.update("insertionOrders",this.insertionOrders.length,e.id)}deleteSheet(e){this.history.update("insertionOrders",this.insertionOrders.filter((t=>!this.figures[e]?.[t]))),this.history.update("figures",e,void 0)}removeFigure(e,t){this.history.update("insertionOrders",this.insertionOrders.filter((t=>t!==e))),this.history.update("figures",t,e,void 0)}checkFigureExists(e){return void 0===this.figures[e.sheetId]?.[e.figureId]?"FigureDoesNotExist":"Success"}checkFigureDuplicate(e){return Object.values(this.figures).find((t=>t?.[e.figureId]))?"DuplicatedFigureId":"Success"}checkFigureAnchorOffset(e){return e.col<0||e.row<0||e.offset&&(e.offset.x<0||e.offset.y<0)?"WrongSheetPosition":"Success"}getFigures(e){const t=[];for(const o of this.insertionOrders){const s=this.figures[e]?.[o];s&&t.push(s)}return t}getFigure(e,t){return this.figures[e]?.[t]}getFigureSheetId(e){return Object.keys(this.figures).find((t=>void 0!==this.figures[t]?.[e]))}import(e){for(const t of e.sheets)for(const e of t.figures)this.addFigure(e,t.id)}export(e){for(const t of e.sheets)for(const e of this.getFigures(t.id)){const o=void 0;t.figures.push({...e,data:o})}}exportForExcel(e){return this.export(e)}}).add("chart",class extends Nk{static getters=["isChartDefined","getChartDefinition","getChartType","getChartIds","getChart","getContextCreationChart"];charts={};createChart=ax(this.getters);validateChartDefinition=e=>cx(this,e.definition);adaptRanges(e,t,o){for(const[s,i]of Object.entries(this.charts))this.history.update("charts",s,i?.updateRanges(e,t,o))}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,this.checkChartChanged));default:return"Success"}}handle(e){switch(e.type){case"CREATE_CHART":this.addFigure(e.figureId,e.sheetId,e.col,e.row,e.offset,e.size),this.addChart(e.figureId,e.definition);break;case"UPDATE_CHART":this.addChart(e.figureId,e.definition);break;case"DUPLICATE_SHEET":{const t=this.getters.getFigures(e.sheetId);for(const o of t)if("chart"===o.tag){const t=o.id.split(we).pop(),s=`${e.sheetIdTo}${we}${t}`,i=this.charts[o.id]?.duplicateInDuplicatedSheet(e.sheetIdTo);i&&this.dispatch("CREATE_CHART",{figureId:s,col:o.col,row:o.row,offset:o.offset,size:{width:o.width,height:o.height},definition:i.getDefinition(),sheetId:e.sheetIdTo})}break}case"DELETE_FIGURE":this.history.update("charts",e.figureId,void 0);break;case"DELETE_SHEET":for(const t of this.getChartIds(e.sheetId))this.history.update("charts",t,void 0)}}getContextCreationChart(e){return this.charts[e]?.getContextCreation()}getChart(e){return this.charts[e]}getChartType(e){const t=this.charts[e]?.type;if(!t)throw new Error("Chart not defined.");return t}isChartDefined(e){return e in this.charts&&void 0!==this.charts}getChartIds(e){return Object.entries(this.charts).filter((([,t])=>t?.sheetId===e)).map((([e])=>e))}getChartDefinition(e){const t=this.charts[e]?.getDefinition();if(!t)throw new Error(`There is no chart with the given figureId: ${e}`);return t}import(e){for(const t of e.sheets)if(t.figures)for(const e of t.figures)"chart"===e.tag&&(this.charts[e.id]=this.createChart(e.id,e.data,t.id))}export(e){if(e.sheets)for(const t of e.sheets){const e=this.getters.getFigures(t.id),o=[];for(const t of e){const e=t;if(e&&"chart"===e.tag){const t=this.charts[e.id]?.getDefinition();t&&(e.data=t,o.push(e))}else o.push(e)}t.figures=o}}addFigure(e,t,o,s,i,n={width:536,height:335}){this.dispatch("CREATE_FIGURE",{sheetId:t,figureId:e,col:o,row:s,offset:i,size:n,tag:"chart"})}addChart(e,t){const o=this.getters.getFigureSheetId(e);o&&this.history.update("charts",e,this.createChart(e,t,o))}checkChartDuplicate(e){return this.getters.getFigureSheetId(e.figureId)?"DuplicatedChartId":"Success"}checkChartExists(e){return this.isChartDefined(e.figureId)?"Success":"ChartDoesNotExist"}checkChartChanged(e){return mt(this.getChartDefinition(e.figureId),e.definition)?"NoChanges":"Success"}}).add("image",class extends Nk{static getters=["getImage","getImagePath","getImageSize"];fileStore;images={};syncedImages=new Set;constructor(e){super(e),this.fileStore=e.external.fileStore}allowDispatch(e){return"CREATE_IMAGE"===e.type&&this.getters.getFigure(e.sheetId,e.figureId)?"InvalidFigureId":"Success"}handle(e){switch(e.type){case"CREATE_IMAGE":this.addFigure(e.figureId,e.sheetId,e.col,e.row,e.offset,e.size),this.history.update("images",e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case"DUPLICATE_SHEET":{const t=this.getters.getFigures(e.sheetId);for(const o of t)if("image"===o.tag){const t=o.id.split(we).pop(),s=`${e.sheetIdTo}${we}${t}`,i=this.getImage(o.id);if(i){const t={width:o.width,height:o.height};this.dispatch("CREATE_IMAGE",{sheetId:e.sheetIdTo,figureId:s,offset:o.offset,col:o.col,row:o.row,size:t,definition:ze(i)})}}break}case"DELETE_FIGURE":this.history.update("images",e.sheetId,e.figureId,void 0);break;case"DELETE_SHEET":this.history.update("images",e.sheetId,void 0)}}garbageCollectExternalResources(){const e=new Set(this.getAllImages().map((e=>e.path)));for(const t of this.syncedImages)e.has(t)||this.fileStore?.delete(t)}getImage(e){for(const t of Object.values(this.images))if(t&&t[e])return t[e];throw new Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addFigure(e,t,o,s,i,n){this.dispatch("CREATE_FIGURE",{sheetId:t,figureId:e,col:o,row:s,offset:i,size:n,tag:"image"})}import(e){for(const t of e.sheets){const e=(t.figures||[]).filter((e=>"image"===e.tag));for(const o of e)this.history.update("images",t.id,o.id,o.data),this.syncedImages.add(o.data.path)}}export(e){for(const t of e.sheets){const e=t.figures.filter((e=>"image"===e.tag));for(const o of e)o.data=this.images[t.id]?.[o.id]}}exportForExcel(e){for(const t of e.sheets){t.images||(t.images=[]);const e=this.getters.getFigures(t.id),o=[];for(const t of e)if("image"===t?.tag){const e=this.getImage(t.id);e&&o.push({...t,data:ze(e)})}t.images=[...t.images,...o]}}getAllImages(){const e=[];for(const t in this.images)e.push(...Object.values(this.images[t]||{}).filter(lt));return e}}).add("pivot_core",class extends Nk{static getters=["getPivotCoreDefinition","getPivotDisplayName","getPivotId","getPivotFormulaId","getPivotIds","getMeasureCompiledFormula","getPivotName","isExistingPivot"];nextFormulaId=1;pivots={};formulaIds={};compiledMeasureFormulas={};allowDispatch(e){switch(e.type){case"ADD_PIVOT":return this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures);case"UPDATE_PIVOT":return e.pivotId in this.pivots?mt(e.pivot,this.pivots[e.pivotId]?.definition)?"NoChanges":""===e.pivot.name?"EmptyName":this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures):"PivotIdNotFound";case"RENAME_PIVOT":if(!(e.pivotId in this.pivots))return"PivotIdNotFound";if(""===e.name)return"EmptyName";break;case"REMOVE_PIVOT":case"DUPLICATE_PIVOT":case"INSERT_PIVOT":case"DUPLICATE_PIVOT":if(!(e.pivotId in this.pivots))return"PivotIdNotFound"}return"Success"}handle(e){switch(e.type){case"ADD_PIVOT":{const{pivotId:t,pivot:o}=e;this.addPivot(t,o);break}case"INSERT_PIVOT":{const{sheetId:t,col:o,row:s,pivotId:i,table:n}=e,r={sheetId:t,col:o,row:s},{cols:a,rows:l,measures:c,fieldsType:h}=n,d=new qN(a,l,c,h||{}),u=this.getPivotFormulaId(i);this.insertPivot(r,u,d);break}case"RENAME_PIVOT":this.history.update("pivots",e.pivotId,"definition","name",e.name);break;case"REMOVE_PIVOT":{const t={...this.pivots};delete t[e.pivotId];const o=this.getPivotFormulaId(e.pivotId);this.history.update("formulaIds",o,void 0),this.history.update("pivots",t);break}case"DUPLICATE_PIVOT":{const{pivotId:t,newPivotId:o}=e,s=ze(this.getPivotCore(t).definition);s.name=e.duplicatedPivotName??s.name+" (copy)",this.addPivot(o,s);break}case"UPDATE_PIVOT":this.history.update("pivots",e.pivotId,"definition",ze(e.pivot)),this.compileCalculatedMeasures(e.pivot.measures)}}adaptRanges(e){for(const t in this.compiledMeasureFormulas)for(const o in this.compiledMeasureFormulas[t]){const s=this.compiledMeasureFormulas[t][o],i=[];for(const t of s.dependencies){const o=e(t);"NONE"===o.changeType?i.push(t):i.push(o.range)}const n=this.getters.getFormulaString(t,s.tokens,i);n!==o&&this.replaceMeasureFormula(t,o,n)}}getPivotDisplayName(e){return`(#${this.getPivotFormulaId(e)}) ${this.getPivotName(e)}`}getPivotName(e){return this.getPivotCore(e).definition.name}getPivotCoreDefinition(e){return this.getPivotCore(e).definition}getPivotId(e){return this.formulaIds[e]}getPivotFormulaId(e){return this.getPivotCore(e).formulaId}getPivotIds(){return Object.keys(this.pivots)}isExistingPivot(e){return e in this.pivots}getMeasureCompiledFormula(e){if(!e.computedBy)throw new Error(`Measure ${e.fieldName} is not computed by formula`);const t=e.computedBy.sheetId;return this.compiledMeasureFormulas[t][e.computedBy.formula]}addPivot(e,t,o=this.nextFormulaId.toString()){this.history.update("pivots",e,{definition:ze(t),formulaId:o}),this.compileCalculatedMeasures(t.measures),this.history.update("formulaIds",o,e),this.history.update("nextFormulaId",this.nextFormulaId+1)}compileCalculatedMeasures(e){for(const t of e)if(t.computedBy){const e=t.computedBy.sheetId,o=this.compileMeasureFormula(t.computedBy.sheetId,t.computedBy.formula);this.history.update("compiledMeasureFormulas",e,t.computedBy.formula,o)}}insertPivot(e,t,o){this.resizeSheet(e.sheetId,e,o);const s=o.getPivotCells();for(let o=0;o<s.length;o++)for(let i=0;i<s[o].length;i++){const n=s[o][i];this.dispatch("UPDATE_CELL",{sheetId:e.sheetId,col:e.col+o,row:e.row+i,content:$c(t,n)})}}resizeSheet(e,{col:t,row:o},s){const i=s.getNumberOfDataColumns()+1,n=this.getters.getNumberCols(e),r=n-t;r<i&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:n-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-r,position:"after"});const a=s.columns.length+s.rows.length,l=this.getters.getNumberRows(e),c=l-o;c<a&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:l-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:a-c,position:"after"})}getPivotCore(e){const t=this.pivots[e];if(!t)throw new Error(`Pivot with id ${e} not found`);return t}compileMeasureFormula(e,t){const o=HS(t),s=o.dependencies.map((t=>this.getters.getRangeFromSheetXC(e,t)));return{...o,dependencies:s}}replaceMeasureFormula(e,t,o){this.history.update("compiledMeasureFormulas",e,t,void 0),this.history.update("compiledMeasureFormulas",e,o,this.compileMeasureFormula(e,o));for(const s in this.pivots){const i=this.pivots[s];if(i)for(const n of i.definition.measures)if(n.computedBy?.formula===t){const t=i.definition.measures.indexOf(n);this.history.update("pivots",s,"definition","measures",t,"computedBy",{formula:o,sheetId:e})}}}checkSortedColumnInMeasures(e){const t=e.measures.map((e=>e.id));return e.sortedColumn&&!t.includes(e.sortedColumn.measure)?"InvalidDefinition":"Success"}checkDuplicatedMeasureIds(e){const t=new Set(e.measures.map((e=>e.id)));return e.measures.length!==t.size?"InvalidDefinition":"Success"}import(e){if(e.pivots)for(const[t,o]of Object.entries(e.pivots))this.addPivot(t,o,o.formulaId);this.history.update("nextFormulaId",e.pivotNextId||kc(this.pivots)+1)}export(e){e.pivots={};for(const t in this.pivots)e.pivots[t]={...this.getPivotCoreDefinition(t),formulaId:this.getPivotFormulaId(t)};e.pivotNextId=this.nextFormulaId}}).add("spreadsheet_pivot_core",class extends Nk{allowDispatch(e){switch(e.type){case"ADD_PIVOT":case"UPDATE_PIVOT":const t=e.pivot;return this.checkDataSetValidity(t)}return"Success"}adaptRanges(e){for(const t of this.getters.getPivotIds()){const o=this.getters.getPivotCoreDefinition(t);if("SPREADSHEET"===o.type&&o.dataSet){const{sheetId:s,zone:i}=o.dataSet,n=zk(this.getters.getRangeFromZone(s,i),e),r=n&&{sheetId:n.sheetId,zone:n.zone};this.dispatch("UPDATE_PIVOT",{pivotId:t,pivot:{...o,dataSet:r}})}}}checkDataSetValidity(e){if("SPREADSHEET"===e.type&&e.dataSet){const{zone:t,sheetId:o}=e.dataSet;return o&&this.getters.tryGetSheet(o)&&t&&pr(t)?this.getters.checkZonesExistInSheet(o,[t]):"InvalidDataSet"}return"Success"}}).add("tableStyle",class extends Nk{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(!HR[e.templateName])return"InvalidTableStyle";try{Gt(e.primaryColor)}catch(e){return"InvalidTableStyle"}}return"Success"}handle(e){switch(e.type){case"CREATE_TABLE_STYLE":const t=UR(e.tableStyleName,e.templateName,e.primaryColor);this.history.update("styles",e.tableStyleId,t);break;case"REMOVE_TABLE_STYLE":const o={...this.styles};delete o[e.tableStyleId],this.history.update("styles",o);for(const t of this.getters.getSheetIds())for(const o of this.getters.getCoreTables(t))o.config.styleId===e.tableStyleId&&this.dispatch("UPDATE_TABLE",{sheetId:t,zone:o.range.zone,config:{styleId:wR.styleId}})}}getTableStyle(e){if(!this.styles[e])throw new Error(`Table style ${e} does not exist`);return this.styles[e]}getTableStyles(){return this.styles}getNewCustomTableStyleName(){return Vt(Ho("Custom Table Style"),Object.values(this.styles).map((e=>e.displayName)),{compute:(e,t)=>`${e} ${t}`,start:2})}isTableStyleEditable(e){return!LR[e]}import(e){for(const e in LR)this.styles[e]=LR[e];for(const t in e.customTableStyles){const o=e.customTableStyles[t];this.styles[t]=UR(o.displayName,o.templateName,o.primaryColor)}}export(e){const t={};for(const e in this.styles)LR[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}}),EL=(new n).add("ui_sheet",class extends BV{static getters=["getCellWidth","getTextWidth","getCellText","getCellMultiLineText","getContiguousZone","computeTextYCoordinate"];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(const t of e.cols){const o=this.getColMaxWidth(e.sheetId,t);0!==o&&this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"COL",size:o,sheetId:e.sheetId})}break;case"AUTORESIZE_ROWS":this.autoResizeRows(e.sheetId,e.rows);break;case"DELETE_UNFILTERED_CONTENT":const t=[];for(const o of e.target){const s=Ye(je(o.top,o.bottom+1).filter((t=>!this.getters.isRowFiltered(e.sheetId,t))));for(const e of s)t.push({...o,top:e[0],bottom:e[e.length-1]})}this.dispatch("DELETE_CONTENT",{sheetId:e.sheetId,target:t})}}getCellWidth(e){const t=this.getters.getCellComputedStyle(e);let o=0;const s=this.getters.getEvaluatedCell(e).formattedValue;if(s){const e=Wa(this.ctx,s,t,void 0);o+=Math.max(...e.map((e=>Va(this.ctx,e,t))))}for(const t of this.getters.getCellIcons(e))o+=t.margin+t.size;if(this.getters.getDataValidationChipStyle(e)&&(o+=10),0===o)return 0;if(o+=2*le,"wrap"===t.wrapping){const t=this.getters.getColSize(this.getters.getActiveSheetId(),e.col);return Math.min(t,o)}return o}getTextWidth(e,t){return Va(this.ctx,e,t)}getCellText(e,t){const o=this.getters.getCell(e),s=this.getters.getLocale();if(t?.showFormula&&o?.isFormula)return Ol(o.content,s);if(t?.showFormula&&!o?.content)return"";{const i=this.getters.getEvaluatedCell(e),n=t?.availableWidth?{availableWidth:t.availableWidth,measureText:e=>Va(this.ctx,e,o?.style||{})}:void 0;return In(i.value,{format:i.format,locale:s,formatWidth:n})}}getCellMultiLineText(e,t){const o=this.getters.getCellStyle(e),s=this.getters.getCellText(e,{showFormula:this.getters.shouldShowFormulas(),availableWidth:t.maxWidth});return Wa(this.ctx,s,o,t.wrapText?t.maxWidth:void 0)}computeTextYCoordinate(e,t,o=ue,s=1){const i=e.y+1,n=Pa(t,s);if(e.height>n+2*re){if("middle"===o)return Math.ceil(i+(e.height-n)/2);if("bottom"===o)return i+e.height-n-re}return i+re}getContiguousZone(e,t){const o=t=>{for(const o of je(t.left,t.right+1)){if(!this.isCellEmpty({sheetId:e,col:o,row:t.top-1}))return{...t,top:t.top-1};if(!this.isCellEmpty({sheetId:e,col:o,row:t.bottom+1}))return{...t,bottom:t.bottom+1}}for(const o of je(t.top,t.bottom+1)){if(!this.isCellEmpty({sheetId:e,col:t.left-1,row:o}))return{...t,left:t.left-1};if(!this.isCellEmpty({sheetId:e,col:t.right+1,row:o}))return{...t,right:t.right+1}}return t};let s=!1,i=t;do{s=!1;const e=o(i);Ir(i,e)||(s=!0,i=e)}while(s);return i}isCellEmpty(e){const t=this.getters.getMainCellPosition(e);return this.getters.getEvaluatedCell(t).type===_s.empty}getColMaxWidth(e,t){const o=_r(this.getters.getColsZone(e,t,t)).map((t=>this.getCellWidth({sheetId:e,...t})));return Math.max(0,Ft(o))}checkSheetExists(e){return"sheetId"in e&&void 0===this.getters.tryGetSheet(e.sheetId)?"InvalidSheetId":"Success"}checkZonesAreInSheet(e){const t="sheetId"in e?e.sheetId:this.getters.tryGetActiveSheetId();if("ranges"in e&&e.ranges.some((e=>!this.getters.tryGetSheet(e._sheetId))))return"InvalidSheetId";const o=this.getters.getCommandZones(e);return!t&&o.length>0?"NoActiveSheet":t&&o.length>0?this.getters.checkZonesExistInSheet(t,o):"Success"}autoResizeRows(e,t){const o=[];for(const s of t){let t=0;for(const o of this.getters.getRowCells(e,s)){const s=this.getters.getCellById(o);if(!s)continue;const i=this.getters.getCellPosition(s.id),n=this.getters.getColSize(e,i.col);if(s.isFormula||this.getters.getArrayFormulaSpreadingOn(i)){const e=this.getters.getEvaluatedCell(i).formattedValue,o=Ma(this.ctx,e,s?.style,n);o>t&&o>ie&&(t=o)}else{const e=s.content,o=Ma(this.ctx,e,s?.style,n);o>=t&&o>ie&&(t=0)}}o.push(t||null)}const s=new Map(o.map((e=>[e,[]])));for(let e=0;e<o.length;e++)s.get(o[e])?.push(t[e]);for(const[t,o]of s)this.dispatch("RESIZE_COLUMNS_ROWS",{elements:o,dimension:"ROW",size:t,sheetId:e})}}).add("ui_options",class extends BV{static getters=["shouldShowFormulas"];showFormulas=!1;handle(e){if("SET_FORMULA_VISIBILITY"===e.type)this.showFormulas=e.show}shouldShowFormulas(){return this.showFormulas}}).add("autofill",class extends BV{static layers=["Autofill"];static getters=["getAutofillTooltip"];autofillZone;steps;lastCellSelected={};direction;tooltip;allowDispatch(e){if("AUTOFILL_SELECT"===e.type){const t=this.getters.getActiveSheetId();return this.lastCellSelected.col=-1===e.col?this.lastCellSelected.col:Ze(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=-1===e.row?this.lastCellSelected.row:Ze(e.row,0,this.getters.getNumberRows(t)),void 0!==this.lastCellSelected.col&&void 0!==this.lastCellSelected.row?"Success":"InvalidAutofillSelection"}return"Success"}handle(e){switch(e.type){case"AUTOFILL":this.autofill(!0);break;case"AUTOFILL_SELECT":this.select(e.col,e.row);break;case"AUTOFILL_AUTO":this.autofillAuto()}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||void 0===this.direction)return void(this.tooltip=void 0);const t=this.getters.getSelectedZone(),o=this.autofillZone,s=[];switch(this.direction){case"down":for(let e=t.left;e<=t.right;e++){const i=[];for(let o=t.top;o<=t.bottom;o++)i.push(Po(e,o));const n=this.createGenerator(i);for(let t=o.top;t<=o.bottom;t++)s.push(this.computeNewCell(n,e,t))}break;case"up":for(let e=t.left;e<=t.right;e++){const i=[];for(let o=t.bottom;o>=t.top;o--)i.push(Po(e,o));const n=this.createGenerator(i);for(let t=o.bottom;t>=o.top;t--)s.push(this.computeNewCell(n,e,t))}break;case"left":for(let e=t.top;e<=t.bottom;e++){const i=[];for(let o=t.right;o>=t.left;o--)i.push(Po(o,e));const n=this.createGenerator(i);for(let t=o.right;t>=o.left;t--)s.push(this.computeNewCell(n,t,e))}break;case"right":for(let e=t.top;e<=t.bottom;e++){const i=[];for(let o=t.left;o<=t.right;o++)i.push(Po(o,e));const n=this.createGenerator(i);for(let t=o.left;t<=o.right;t++)s.push(this.computeNewCell(n,t,e))}}if(e){const e={},t={},o={},i=this.getters.getActiveSheetId();for(const n of s)this.collectBordersData(n,e),this.autofillMerge(i,n),this.autofillCell(i,n),this.collectConditionalFormatsData(i,n,t),this.collectDataValidationsData(i,n,o);this.autofillBorders(i,e),this.autofillConditionalFormats(i,t),this.autofillDataValidations(i,o),this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0}}collectBordersData(e,t){const o=JSON.stringify(e.border);o in t||(t[o]=[]),t[o].push(Mr({col:e.col,row:e.row}))}collectConditionalFormatsData(e,t,o){const{originCol:s,originRow:i,col:n,row:r}=t,a=this.getters.getRulesByCell(e,s,i),l=Po(n,r);for(const e of a)e.id in o||(o[e.id]=[]),o[e.id].push(l)}collectDataValidationsData(e,t,o){const{originCol:s,originRow:i,col:n,row:r}=t,a={sheetId:e,col:s,row:i},l=this.getters.getValidationRuleForCell(a);l&&(l.id in o||(o[l.id]=[]),o[l.id].push(Mr({col:n,row:r})))}autofillCell(e,t){this.dispatch("UPDATE_CELL",{sheetId:e,col:t.col,row:t.row,content:t.content||"",style:t.style||null,format:t.format||""}),this.dispatch("AUTOFILL_CELL",t)}autofillBorders(e,t){for(const o in t){const s="undefined"===o?void 0:JSON.parse(o);this.dispatch("SET_BORDERS_ON_TARGET",{sheetId:e,border:s,target:nr(t[o])})}}autofillConditionalFormats(e,t){for(const o in t){const s=t[o],i=this.getters.getConditionalFormats(e).find((e=>e.id===o));if(!i)continue;const n=this.getters.getAdaptedCfRanges(e,i,s.map(ur),[]);n&&this.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{id:i.id,rule:i.rule,stopIfTrue:i.stopIfTrue},ranges:n,sheetId:e})}}autofillDataValidations(e,t){for(const o in t){const s=t[o],i=this.getters.getDataValidationRule(e,o);if(!i)continue;const n=i.ranges.map((e=>e.zone)),r=nr(n.concat(s),[]);this.dispatch("ADD_DATA_VALIDATION_RULE",{rule:i,ranges:r.map((t=>this.getters.getRangeDataFromZone(e,t))),sheetId:e})}}select(e,t){const o=this.getters.getSelectedZone();if(Er(e,t,o))this.autofillZone=void 0;else{switch(this.direction=this.getDirection(e,t),this.direction){case"up":this.saveZone(t,o.top-1,o.left,o.right),this.steps=o.top-t;break;case"down":this.saveZone(o.bottom+1,t,o.left,o.right),this.steps=t-o.bottom;break;case"left":this.saveZone(o.top,o.bottom,e,o.left-1),this.steps=o.left-e;break;case"right":this.saveZone(o.top,o.bottom,o.right+1,e),this.steps=e-o.right}this.autofill(!1)}}autofillAuto(){const e=this.getters.getActivePosition(),t=this.getters.getTable(e);let o=t?t.range.zone.bottom:this.getAutofillAutoLastRow();const s=this.getters.getSelectedZone();for(let t=s.bottom+1;t<=o;t++)if(this.getters.getEvaluatedCell({...e,row:t}).type!==_s.empty){o=t-1;break}o>s.bottom&&(this.select(e.col,o),this.autofill(!0))}getAutofillAutoLastRow(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();let o=e.left,s=e.bottom;if(o>0){let e={sheetId:t,col:o-1,row:s};for(;this.getters.getEvaluatedCell(e).type!==_s.empty;)s+=1,e={sheetId:t,col:o-1,row:s}}if(s===e.bottom&&(o=e.right,o<=this.getters.getNumberCols(t))){let e={sheetId:t,col:o+1,row:s};for(;this.getters.getEvaluatedCell(e).type!==_s.empty;)s+=1,e={sheetId:t,col:o+1,row:s}}return s-1}computeNewCell(e,t,o){const{cellData:s,tooltip:i,origin:n}=e.next(),{content:r,style:a,border:l,format:c}=s;return this.tooltip=i,{originCol:n.col,originRow:n.row,col:t,row:o,content:r,style:a,border:l,format:c}}getRule(e,t){const o=MV.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((o=>o.condition(e,t)));return o&&this.direction&&o.generateRule(e,t,this.direction)}createGenerator(e){const t=[],o=[],s=this.getters.getActiveSheetId();for(const t of e){const{col:e,row:i}=Fo(t),n=this.getters.getCell({sheetId:s,col:e,row:i});o.push({col:e,row:i,cell:n,sheetId:s})}const i=o.map((e=>e.cell));for(const e of o){let o={type:"COPY_MODIFIER"};if(e&&e.cell){o=this.getRule(e.cell,i)||o}const s=this.getters.getCellBorder(e)||void 0;t.push({data:{...e,border:s},rule:o})}return new zV(t,this.getters,this.direction)}saveZone(e,t,o,s){this.autofillZone={top:e,bottom:t,left:o,right:s}}getDirection(e,t){const o=this.getters.getSelectedZone(),s={up:{number:o.top-t,value:"up"},down:{number:t-o.bottom,value:"down"},left:{number:o.left-e,value:"left"},right:{number:e-o.right,value:"right"}};if(1===Object.values(s).map((e=>e.number>0?1:0)).reduce(((e,t)=>e+t)))return Object.values(s).find((e=>e.number>0?1:0)).value;const i=s.up.number>0?"up":"down",n=s.left.number>0?"left":"right";return Math.abs(s[i].number)>=Math.abs(s[n].number)?s[i].value:s[n].value}autofillMerge(e,t){const{originCol:o,originRow:s,col:i,row:n}=t,r={sheetId:e,col:i,row:n},a={sheetId:e,col:o,row:s};if(this.getters.isInMerge(r)&&!this.getters.isInMerge(a)){const t=this.getters.getMerge(r);t&&this.dispatch("REMOVE_MERGE",{sheetId:e,target:[t]})}const l=this.getters.getMerge(a);l?.left===o&&l?.top===s&&this.dispatch("ADD_MERGE",{sheetId:e,target:[{top:n,bottom:n+l.bottom-l.top,left:i,right:i+l.right-l.left}]})}drawLayer(e){if(!this.autofillZone)return;const{ctx:t,thinLineWidth:o}=e,{x:s,y:i,width:n,height:r}=this.getters.getVisibleRect(this.autofillZone);n>0&&r>0&&(t.strokeStyle="black",t.lineWidth=o,t.setLineDash([3]),t.strokeRect(s,i,n,r),t.setLineDash([]))}}).add("sort",class extends BV{allowDispatch(e){return"SORT_CELLS"===e.type?Er(e.col,e.row,e.zone)?this.checkValidations(e,this.checkMerge,this.checkMergeSizes,this.checkArrayFormulaInSortZone):"InvalidSortAnchor":"Success"}handle(e){if("SORT_CELLS"===e.type)this.sortZone(e.sheetId,e,e.zone,e.sortDirection,e.sortOptions||{})}checkMerge({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return"Success";return _r(t).some((({col:t,row:o})=>!this.getters.isInMerge({sheetId:e,col:t,row:o})))?"InvalidSortZone":"Success"}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return"Success";const o=this.getters.getMerges(e).filter((e=>xr(e,t))),s=Tr(o[0]),[i,n]=[s.numberOfCols,s.numberOfRows];return o.every((e=>{const[t,o]=[e.right-e.left+1,e.bottom-e.top+1];return t===i&&o===n}))?"Success":"InvalidSortZone"}checkArrayFormulaInSortZone({sheetId:e,zone:t}){return _r(t).some((({col:t,row:o})=>this.getters.getArrayFormulaSpreadingOn({sheetId:e,col:t,row:o})))?"SortZoneWithArrayFormulas":"Success"}hasHeader(e,t){if(1===t[0].length)return!1;let o=t.map((t=>t.map((({col:t,row:o})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:o}).type))));return o[0][0]===_s.empty&&(o=o.slice(1)),!o.some((e=>e[0]===_s.empty))&&!!o.some((e=>e[1]!==_s.empty&&e[0]!==e[1]))}sortZone(e,t,o,s,i){const[n,r]=this.mainCellsSteps(e,o),a=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,l=Object.assign({},o);let c=this.mainCells(e,o);!i.sortHeaders&&this.hasHeader(e,c)&&(l.top+=r),c=this.mainCells(e,l);const h=function(e,t,o){const s=e.map(((e,t)=>({index:t,type:e.type,value:e.value})));return(o?s.map((e=>e.type===_s.empty?{...e,type:_s.number,value:0}:e)):s).sort(jp(t))}(c[a-l.left].map((e=>this.getters.getEvaluatedCell(e))),s,Boolean(i.emptyCellAsZero)),d=h.map((e=>e.index)),[u,g]=[c.length,c[0].length],p=[];for(let e=0;e<u;e++)for(let t=0;t<g;t++){const{col:o,row:s,sheetId:i}=c[e][d[t]],a=this.getters.getCell({sheetId:i,col:o,row:s}),h=l.left+e*n,u=l.top+t*r,g={sheetId:i,col:h,row:u,content:""};if(a){let e=a.content;if(a.isFormula){const t=this.getters.getCellPosition(a.id);e=this.getters.getTranslatedCellFormula(i,0,u-t.row,a.compiledFormula.tokens)}g.style=a.style,g.content=e,g.format=a.format}p.push(g)}p.forEach((e=>this.dispatch("UPDATE_CELL",e)))}mainCellsSteps(e,t){const o=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[o?o.right-o.left+1:1,o?o.bottom-o.top+1:1]}mainCells(e,t){const[o,s]=this.mainCellsSteps(e,t),i=[],n=je(t.left,t.right+1,o),r=je(t.top,t.bottom+1,s);for(const t of n){const o=[];i.push(o);for(const s of r)o.push({sheetId:e,col:t,row:s})}return i}}).add("automatic_sum",class extends BV{static getters=["getAutomaticSums"];handle(e){if("SUM_SELECTION"===e.type){const e=this.getters.getActiveSheetId(),{zones:t,anchor:o}=this.getters.getSelection();for(const s of t){const t=this.getAutomaticSums(e,s,o.cell);this.dispatchCellUpdates(e,t)}}}getAutomaticSums(e,t,o){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,o):this.sumData(e,t)}sumData(e,t){const o=this.dimensionsToSum(e,t),s=this.sumDimensions(e,t,o).filter((({zone:t})=>!this.getters.isEmpty(e,t)));return o.has("ROW")&&o.has("COL")&&s.push(this.sumTotal(t)),s}sumAdjacentData(e,t,o){const{col:s,row:i}=Er(o.col,o.row,t)?o:{col:t.left,row:t.top},n=this.findAdjacentData(e,s,i);return n?this.getters.isSingleCellOrMerge(e,t)||Ar(yr(n,t))?[{position:{col:s,row:i},zone:n}]:this.sumDimensions(e,yr(n,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,o){const s=this.getters.getSheet(e),i=this.getters.getMainCellPosition({sheetId:e,col:t,row:o}),n=this.findSuitableZoneToSum(s,i.col,i.row);if(n)return this.getters.expandZone(e,n)}findSuitableZoneToSum(e,t,o){const s=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:o-1}),i=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:o});if(this.isNumber(i)&&!this.isNumber(s))return this.findHorizontalZone(e,t,o);const n=this.findVerticalZone(e,t,o);if(this.isZoneValid(n))return n;const r=this.findHorizontalZone(e,t,o);return this.isZoneValid(r)?r:void 0}findVerticalZone(e,t,o){const s={top:0,bottom:o-1,left:t,right:t},i=this.reduceZoneStart(e,s,s.bottom);return{...s,top:i}}findHorizontalZone(e,t,o){const s={top:o,bottom:o,left:0,right:t-1},i=this.reduceZoneStart(e,s,s.right);return{...s,left:i}}reduceZoneStart(e,t,o){const s=this.getters.getEvaluatedCellsInZone(e.id,t),i=je(o,-1,-1),n=Ft(i.filter((e=>s[e]&&!s[e].isAutoSummable))),r=Ye(i.filter((e=>this.isNumber(s[e]))))[0]||[];return Ft(r)<n?1/0:Pt(r)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===_s.number&&!(e.format&&On(e.format))}isZoneValid(e){return e.bottom>=e.top&&e.right>=e.left}lastColIsEmpty(e,t){return this.getters.isEmpty(e,{...t,left:t.right})}lastRowIsEmpty(e,t){return this.getters.isEmpty(e,{...t,top:t.bottom})}dimensionsToSum(e,t){const o=new Set;return Ar(t)?(o.add(1===Tr(t).numberOfCols?"COL":"ROW"),o):(this.lastColIsEmpty(e,t)&&o.add("ROW"),this.lastRowIsEmpty(e,t)&&o.add("COL"),0===o.size&&o.add("COL"),o)}sumDimensions(e,t,o){return[...o.has("COL")?this.sumColumns(t,e):[],...o.has("ROW")?this.sumRows(t,e):[]]}sumTotal(e){const{bottom:t,right:o}=e;return{position:{col:o,row:t},zone:{...e,top:t,right:o-1}}}sumColumns(e,t){const o=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,o.bottom-1)},_r(o).map((t=>({position:t,zone:{...e,right:t.col,left:t.col}})))}sumRows(e,t){const o=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,o.right-1)},_r(o).map((t=>({position:t,zone:{...e,top:t.row,bottom:t.row}})))}dispatchCellUpdates(e,t){for(const o of t){const{col:t,row:s}=o.position;this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:s,content:`=SUM(${this.getters.zoneToXC(e,o.zone)})`})}}nextEmptyRow(e,t){let o=t.bottom+1;const{left:s,right:i}=t;for(;!this.getters.isEmpty(e,{bottom:o,top:o,left:s,right:i});)o++;return{...t,top:o,bottom:o}}nextEmptyCol(e,t){let o=t.right+1;const{top:s,bottom:i}=t;for(;!this.getters.isEmpty(e,{left:o,right:o,top:s,bottom:i});)o++;return{...t,left:o,right:o}}transpose(e){return new Set([...e.values()].map((e=>"COL"===e?"ROW":"COL")))}}).add("format",class extends BV{handle(e){switch(e.type){case"SET_DECIMAL":this.setDecimal(e.sheetId,e.target,e.step);break;case"SET_FORMATTING_WITH_PIVOT":this.setContextualFormat(e.sheetId,e.target,e.format)}}setContextualFormat(e,t,o){const s=[],i={};for(const o of nr(t))for(let t=o.left;t<=o.right;t++)for(let n=o.top;n<=o.bottom;n++){const o={sheetId:e,col:t,row:n},r=this.getters.getPivotCellFromPosition(o);if(this.isSpilledPivotValueFormula(o,r)){s.push(o);const e=this.getters.getPivotIdFromPosition(o)||"";i[e]??=new Set,i[e].add(r.measure)}}const n=nr(s.map(Mr));for(const e in i){const t=i[e],s=this.getters.getPivotCoreDefinition(e);this.dispatch("UPDATE_PIVOT",{pivotId:e,pivot:{...s,measures:s.measures.map((e=>t.has(e.id)?{...e,format:o}:e))}})}this.dispatch("SET_FORMATTING",{sheetId:e,target:n,format:""}),this.dispatch("SET_FORMATTING",{sheetId:e,target:nr(t,n),format:o})}isSpilledPivotValueFormula(e,t){const o=this.getters.getCell(e);return"VALUE"===t.type&&!o?.isFormula}setDecimal(e,t,o){const s={};for(const i of nr(t))for(const t of _r(i)){const i=this.getCellNumberFormat({sheetId:e,...t});if(void 0!==i){const e=qn(i,o);s[e]=s[e]||[],s[e].push(t)}}for(const t in s){const o=nr(s[t].map((e=>Mr(e))));this.setContextualFormat(e,o,t)}}getCellNumberFormat(e){for(const t of[e]){const e=this.getters.getEvaluatedCell(t);if(!(e.type!==_s.number||e.format&&On(e.format)))return e.format||Mn(e.value)}}}).add("insert_pivot",class extends BV{static getters=[];allowDispatch(e){if("DUPLICATE_PIVOT_IN_NEW_SHEET"===e.type){if(!this.getters.isExistingPivot(e.pivotId))return"PivotIdNotFound";if(!this.getters.getPivot(e.pivotId).isValid())return"PivotInError"}return"Success"}handle(e){switch(e.type){case"INSERT_NEW_PIVOT":this.insertNewPivot(e.pivotId,e.newSheetId);break;case"DUPLICATE_PIVOT_IN_NEW_SHEET":this.duplicatePivotInNewSheet(e.pivotId,e.newPivotId,e.newSheetId);break;case"INSERT_PIVOT_WITH_TABLE":this.insertPivotWithTable(e.sheetId,e.col,e.row,e.pivotId,e.table,e.pivotMode);break;case"SPLIT_PIVOT_FORMULA":this.splitPivotFormula(e.sheetId,e.col,e.row,e.pivotId)}}insertNewPivot(e,t){1===Lr(this.getters.getSelectedZone())&&this.selection.selectTableAroundSelection();const o=this.getters.getActiveSheetId();this.dispatch("ADD_PIVOT",{pivotId:e,pivot:{dataSet:{zone:this.getters.getSelectedZone(),sheetId:o},columns:[],rows:[],measures:[],name:Ho("New pivot"),type:"SPREADSHEET"}});const s=this.getters.getSheetIds().findIndex((e=>e===o))+1,i=this.getters.getPivotFormulaId(e);this.dispatch("CREATE_SHEET",{sheetId:t,name:Ho("Pivot #%(formulaId)s",{formulaId:i}),position:s}),this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:o,sheetIdTo:t});const n=this.getters.getPivot(e);this.insertPivotWithTable(t,0,0,e,n.getCollapsedTableStructure().export(),"dynamic")}duplicatePivotInNewSheet(e,t,o){this.dispatch("DUPLICATE_PIVOT",{pivotId:e,newPivotId:t,duplicatedPivotName:Ho("%s (copy)",this.getters.getPivotCoreDefinition(e).name)});const s=this.getters.getActiveSheetId(),i=this.getters.getSheetIds().indexOf(s)+1,n=this.getters.getPivotFormulaId(t),r=this.getters.getPivotName(t);if(this.dispatch("CREATE_SHEET",{sheetId:o,name:this.getPivotDuplicateSheetName(Ho("%(newPivotName)s (Pivot #%(formulaId)s)",{newPivotName:r,formulaId:n})),position:i}).isSuccessful){this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:s,sheetIdTo:o});const i=this.getters.getPivot(e);this.insertPivotWithTable(o,0,0,t,i.getCollapsedTableStructure().export(),"dynamic")}}getPivotDuplicateSheetName(e){const t=this.getters.getSheetIds().map((e=>this.getters.getSheetName(e)));return Vt(qe(e),t)}insertPivotWithTable(e,t,o,s,i,n){const{cols:r,rows:a,measures:l,fieldsType:c}=i,h=new qN(r,a,l,c||{}),d=h.columns.length-1;this.resizeSheet(e,t,o,h);const u=this.getters.getPivotFormulaId(s);let g;"dynamic"===n?(this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,content:`=PIVOT(${u})`}),g={left:t,right:t,top:o,bottom:o}):(this.dispatch("INSERT_PIVOT",{sheetId:e,col:t,row:o,pivotId:s,table:h.export()}),g={left:t,right:t+h.getNumberOfDataColumns(),top:o,bottom:o+d+h.rows.length}),this.dispatch("CREATE_TABLE",{tableType:n,sheetId:e,ranges:[this.getters.getRangeDataFromZone(e,g)],config:{...Ve,numberOfHeaders:d}})}resizeSheet(e,t,o,s){const i=s.getNumberOfDataColumns()+1,n=this.getters.getNumberCols(e),r=n-t;r<i&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:n-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-r,position:"after"});const a=s.columns.length+s.rows.length,l=this.getters.getNumberRows(e),c=l-o;c<a&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:l-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:a-c,position:"after"})}splitPivotFormula(e,t,o,s){const i=this.getters.getSpreadZone({sheetId:e,col:t,row:o});if(!i)return;const n=this.getters.getPivotFormulaId(s),r=new Map;for(let t=i.left;t<=i.right;t++)for(let o=i.top;o<=i.bottom;o++){const s={sheetId:e,col:t,row:o};r.set(s,this.getters.getPivotCellFromPosition(s))}for(const[e,t]of r)this.dispatch("UPDATE_CELL",{...e,content:$c(n,t)});const a=this.getters.getCoreTable({sheetId:e,col:t,row:o});if("dynamic"===a?.type){const s=Mr({col:t,row:o}),n=this.getters.getRangeDataFromZone(e,i);this.dispatch("UPDATE_TABLE",{sheetId:e,zone:s,newTableRange:n,tableType:"static"})}}}).add("pivot_presence",class extends BV{static getters=["getPivotPresenceTracker"];trackPresencePivotId;tracker;handle(e){switch(e.type){case"PIVOT_START_PRESENCE_TRACKING":this.tracker=new CL,this.trackPresencePivotId=e.pivotId;break;case"PIVOT_STOP_PRESENCE_TRACKING":this.trackPresencePivotId=void 0}}getPivotPresenceTracker(e){if(this.trackPresencePivotId===e){if(!this.tracker)throw new Error("Tracker not initialized");return this.tracker}}}).add("split_to_columns",class extends BV{static getters=["getAutomaticSeparator"];allowDispatch(e){return"SPLIT_TEXT_INTO_COLUMNS"===e.type?this.chainValidations(this.batchValidations(this.checkSingleColSelected,this.checkNonEmptySelector),this.batchValidations(this.checkNotOverwritingContent,this.checkSeparatorInSelection))(e):"Success"}handle(e){if("SPLIT_TEXT_INTO_COLUMNS"===e.type)this.splitIntoColumns(e)}getAutomaticSeparator(){const e=this.getters.getSelectedCells();for(const t of e)if(t.value&&t.type===_s.text){const e=this.getAutoSeparatorForString(t.value);if(e)return e}return" "}getAutoSeparatorForString(e){const t=[Ne,";",","," ","."];for(const o of t)if(e.includes(o))return o}splitIntoColumns({separator:e,addNewColumns:t}){const o=this.getters.getSelectedZone(),s=this.getters.getActiveSheetId(),i=this.getSplittedCols(o,e);t&&this.addColsToAvoidCollisions(o,i),this.removeMergesInSplitZone(o,i),this.addColumnsToNotOverflowSheet(o,i);for(let e=0;e<i.length;e++){const t=o.top+e,n=i[e],r=o.left,a=this.getters.getCell({sheetId:s,col:r,row:t});if(1!==n.length||n[0]!==a?.content)for(const[e,o]of n.entries())this.dispatch("UPDATE_CELL",{sheetId:s,col:r+e,row:t,content:Rl(o,this.getters.getLocale()),format:"",style:a?.style||null})}}getSplittedCols(e,t){if(!t)throw new Error("Separator cannot be empty");const o=this.getters.getActiveSheetId(),s=[];for(const i of je(e.top,e.bottom+1)){const n=this.getters.getEvaluatedCell({sheetId:o,col:e.left,row:i}).formattedValue;s.push(this.splitAndRemoveTrailingEmpty(n,t))}return s}splitAndRemoveTrailingEmpty(e,t){const o=e.split(t);for(;o.length>1&&""===o[o.length-1];)o.pop();return o}willSplittedColsOverwriteContent(e,t){const o=this.getters.getActiveSheetId();for(const s of je(e.top,e.bottom+1)){const i=t[s-e.top];for(let t=1;t<i.length;t++){const i=this.getters.getCell({sheetId:o,col:e.left+t,row:s});if(i&&i.content)return!0}}return!1}removeMergesInSplitZone(e,t){const o=this.getters.getActiveSheetId(),s=Math.max(...t.map((e=>e.length))),i={...e,right:e.left+s-1},n=this.getters.getMergesInZone(o,i);this.dispatch("REMOVE_MERGE",{sheetId:o,target:n})}addColsToAvoidCollisions(e,t){const o=this.getters.getActiveSheetId();let s=0;for(const i of je(e.top,e.bottom+1)){const n={sheetId:o,col:e.left,row:i},r=t[i-e.top],a=this.getColsToAddToAvoidCollision(n,r);s=Math.max(s,a)}s&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:e.left,sheetId:o,sheetName:this.getters.getSheetName(o),quantity:s,position:"after"})}getColsToAddToAvoidCollision(e,t){const o=t.length;for(let t=1;t<o;t++){const s=e.col+t,i=this.getters.getCell({...e,col:s});if(i&&i.content)return o-t}return 0}addColumnsToNotOverflowSheet(e,t){const o=this.getters.getActiveSheetId(),s=Math.max(...t.map((e=>e.length-1))),i=this.getters.getNumberCols(o)-1;e.left+s>i&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:i,sheetId:o,sheetName:this.getters.getSheetName(o),quantity:e.left+s-i,position:"after"})}checkSingleColSelected(){return this.getters.isSingleColSelected()?"Success":"MoreThanOneColumnSelected"}checkNonEmptySelector(e){return""===e.separator?"EmptySplitSeparator":"Success"}checkNotOverwritingContent(e){if(e.addNewColumns||e.force)return"Success";const t=this.getters.getSelectedZones()[0],o=this.getSplittedCols(t,e.separator);return this.willSplittedColsOverwriteContent(t,o)?"SplitWillOverwriteContent":"Success"}checkSeparatorInSelection({separator:e}){const t=this.getters.getSelectedCells();for(const o of t)if(o.formattedValue.includes(e))return"Success";return"NoSplitSeparatorInSelection"}}).add("collaborative",class extends BV{static getters=["getClientsToDisplay","getClient","getCurrentClient","getConnectedClients","isFullySynchronized"];static layers=["Selection"];colors=new bo(12);session;constructor(e){super(e),this.session=e.session}isPositionValid(e){return e.row<this.getters.getNumberRows(e.sheetId)&&e.col<this.getters.getNumberCols(e.sheetId)}getClient(e){return this.session.getClient(e)}getCurrentClient(){return this.session.getCurrentClient()}getConnectedClients(){return[...this.session.getConnectedClients()].map((e=>({...e,color:this.colors.get(e.id)})))}isFullySynchronized(){return this.session.isFullySynchronized()}getClientsToDisplay(){try{this.getters.getCurrentClient()}catch(e){if(e instanceof sL)return[];throw e}const e=this.getters.getActiveSheetId(),t=[];for(const o of this.getters.getConnectedClients())o.id!==this.getters.getCurrentClient().id&&o.position&&o.position.sheetId===e&&this.isPositionValid(o.position)&&t.push({...o,position:o.position});return t}drawLayer(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:o}=e,s=this.getters.getActiveSheetId();for(const e of this.getClientsToDisplay()){const{row:i,col:n}=e.position,r=this.getters.expandZone(s,{top:i,bottom:i,left:n,right:n}),{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(r);if(c<=0||h<=0)continue;const d=e.color;t.fillStyle=`${d}10`,t.lineWidth=4*o,t.strokeStyle=d,t.globalCompositeOperation="multiply",t.fillRect(a,l,c,h),t.globalCompositeOperation="source-over",t.strokeRect(a,l,c,h),t.font=`bold ${me+1}px ${fe}`}}}).add("history",class extends BV{static getters=["canUndo","canRedo"];undoStack=[];redoStack=[];session;constructor(e){super(e),this.session=e.session,this.session.on("new-local-state-update",this,this.onNewLocalStateUpdate),this.session.on("snapshot",this,(()=>{this.undoStack=[],this.redoStack=[]}))}allowDispatch(e){switch(e.type){case"REQUEST_UNDO":if(!this.canUndo())return"EmptyUndoStack";break;case"REQUEST_REDO":if(!this.canRedo())return"EmptyRedoStack"}return"Success"}handle(e){switch(e.type){case"REQUEST_UNDO":case"REQUEST_REDO":this.requestHistoryChange("REQUEST_UNDO"===e.type?"UNDO":"REDO")}}finalize(){}requestHistoryChange(e){const t="UNDO"===e?this.undoStack.pop():this.redoStack.pop();if(t)"UNDO"===e?(this.session.undo(t),this.redoStack.push(t)):(this.session.redo(t),this.undoStack.push(t));else{const e=this.getPossibleRevisionToRepeat();if(!e)return;const t=SL(e,this.getters);if(!t)return;if(!Array.isArray(t))return void this.dispatch(t.type,t);for(const e of t)this.dispatch(e.type,e)}}canUndo(){return this.undoStack.length>0}canRedo(){if(this.redoStack.length>0)return!0;const e=this.getPossibleRevisionToRepeat();return!(!(t=e)||!t.rootCommand||"object"!=typeof t.rootCommand)&&(Hs(t.rootCommand)?fL.contains(t.rootCommand.type):vL.contains(t.rootCommand.type));var t}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}getPossibleRevisionToRepeat(){return this.session.getLastLocalNonEmptyRevision()}}).add("data_cleanup",class extends BV{allowDispatch(e){return"REMOVE_DUPLICATES"===e.type?this.checkValidations(e,this.chainValidations(this.checkSingleRangeSelected,this.checkNoMergeInZone,this.checkRangeContainsValues,this.checkColumnsIncludedInZone),this.chainValidations(this.checkNoColumnProvided,this.checkColumnsAreUnique)):"Success"}handle(e){switch(e.type){case"REMOVE_DUPLICATES":this.removeDuplicates(e.columns,e.hasHeader);break;case"TRIM_WHITESPACE":this.trimWhitespace()}}removeDuplicates(e,t){const o=this.getters.getActiveSheetId(),s=this.getters.getSelectedZone();t&&(s.top+=1);const i=this.getUniqueRowsIndexes(o,s.top,s.bottom,e),n=i.length;if(n===Tr(s).numberOfRows)return void this.notifyRowsRemovedAndRemaining(0,n);const r=i.map((e=>({left:s.left,top:e,right:s.right,bottom:e}))),a=new Jc(this.getters,this.dispatch),l=a.copy(Qa(o,r),!1);if(!l)return;this.dispatch("CLEAR_CELLS",{target:[s],sheetId:o});const c={left:s.left,top:s.top,right:s.left,bottom:s.top};a.paste({zones:[c],sheetId:o},l,{isCutOperation:!1});const h={left:s.left,top:s.top-(t?1:0),right:s.right,bottom:s.top+n-1};this.selection.selectZone({cell:{col:h.left,row:h.top},zone:h});const d=s.bottom-s.top+1-n;this.notifyRowsRemovedAndRemaining(d,n)}getUniqueRowsIndexes(e,t,o,s){const i=new Map;for(const n of je(t,o+1)){const t=s.map((t=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).value));!Object.values(i).some((e=>mt(e,t)))&&(i[n]=t)}return Object.keys(i).map((e=>parseInt(e)))}notifyRowsRemovedAndRemaining(e,t){this.ui.notifyUI({type:"info",text:Ho("%s duplicate rows found and removed.\n%s unique rows remain.",e.toString(),t.toString()),sticky:!1})}checkSingleRangeSelected(){return 1!==this.getters.getSelectedZones().length?"MoreThanOneRangeSelected":"Success"}checkNoMergeInZone(){const e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZone();return this.getters.getMergesInZone(e,t).length>0?"WillRemoveExistingMerge":"Success"}checkRangeContainsValues(e){const t=this.getters.getActiveSheetId(),o=this.getters.getSelectedZone();e.hasHeader&&(o.top+=1);return this.getters.getEvaluatedCellsInZone(t,o).every((e=>"empty"===e.type))?"EmptyTarget":"Success"}checkNoColumnProvided(e){return 0===e.columns.length?"NoColumnsProvided":"Success"}checkColumnsIncludedInZone(e){const t=this.getters.getSelectedZone();return e.columns.some((e=>e<t.left||e>t.right))?"ColumnsNotIncludedInZone":"Success"}checkColumnsAreUnique(e){return e.columns.length!==new Set(e.columns).size?"DuplicatesColumnsSelected":"Success"}trimWhitespace(){const e=nr(this.getters.getSelectedZones()),t=this.getters.getActiveSheetId();let o=0;for(const{col:s,row:i}of e.map(_r).flat()){const e=this.getters.getCell({col:s,row:i,sheetId:t});if(!e)continue;const n=Dt(e.content);n!==e.content&&(o+=1,this.dispatch("UPDATE_CELL",{sheetId:t,col:s,row:i,content:n}))}const s=o?Ho("Trimmed whitespace from %s cells.",o):Ho("No selected cells had whitespace trimmed.");this.ui.notifyUI({type:"info",text:s,sticky:!1})}}).add("table_autofill",class extends BV{handle(e){if("AUTOFILL_TABLE_COLUMN"===e.type){const t=this.getters.getCoreTable(e),o=this.getters.getCell(e);if(!t?.config.automaticAutofill||"dynamic"===t.type||!o?.isFormula)return;const{col:s,row:i}=e,n=function(e,t){const o=t.numberOfHeaders,s={...e,top:e.top+o};return s.top<=s.bottom?s:void 0}(t.range.zone,t.config);if(n&&Er(s,i,n)){const t=e.autofillRowStart??n.top,o=e.autofillRowEnd??n.bottom,s={...n,top:t,bottom:o};this.autofillTableZone(e,s)}}}autofillTableZone(e,t){if(t.top===t.bottom)return;const{col:o,row:s,sheetId:i}=e;for(let e=t.top;e<=t.bottom;e++)if(e!==s&&this.getters.getEvaluatedCell({col:o,row:e,sheetId:i}).type!==_s.empty)return;const n={zone:this.getters.getSelectedZone(),cell:this.getters.getActivePosition()};this.selection.selectCell(o,s),this.dispatch("AUTOFILL_SELECT",{col:o,row:t.bottom}),this.dispatch("AUTOFILL"),this.selection.selectCell(o,s),this.dispatch("AUTOFILL_SELECT",{col:o,row:t.top}),this.dispatch("AUTOFILL"),this.selection.selectZone(n)}}).add("table_ui_resize",class extends BV{allowDispatch(e){if("RESIZE_TABLE"===e.type){const t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return"TableNotFound";const o=t.range.zone,s=this.getters.getRangeFromRangeData(e.newTableRange).zone;return s.top!==o.top||s.left!==o.left?"InvalidTableResize":this.canDispatch("UPDATE_TABLE",{...e}).reasons}return"Success"}handle(e){switch(e.type){case"RESIZE_TABLE":{const t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(this.dispatch("UPDATE_TABLE",{...e}),!t)return;const o=this.getters.getRangeFromRangeData(e.newTableRange).zone;if(this.selection.selectCell(o.right,o.bottom),!t.config.automaticAutofill)return;const s=t.range.zone;if(o.bottom>=s.bottom){for(let t=o.left;t<=o.right;t++){const i={col:t,row:s.bottom,sheetId:e.sheetId};this.getters.getCell(i)?.content.startsWith("=")&&this.dispatch("AUTOFILL_TABLE_COLUMN",{...i,autofillRowStart:s.bottom,autofillRowEnd:o.bottom})}break}}}}}).add("datavalidation_insert",class extends BV{handle(e){if("ADD_DATA_VALIDATION_RULE"===e.type)if("isBoolean"===e.rule.criterion.type){const t=e.ranges.map((e=>this.getters.getRangeFromRangeData(e)));for(const e of wa(t)){const t=this.getters.getCell(e),o=this.getters.getEvaluatedCell(e);if(t?.content)if(t?.content&&o.type===_s.empty){let o;if(t.content.startsWith("=")){const s=this.getters.evaluateFormula(e.sheetId,t.content);o=(js(s)?s[0][0]:s)?.toString()}else o=t.content;o&&Ke(o)||this.dispatch("UPDATE_CELL",{...e,content:"FALSE"})}else o.type!==_s.boolean&&this.dispatch("UPDATE_CELL",{...e,content:"FALSE"});else this.dispatch("UPDATE_CELL",{...e,content:"FALSE"})}}}}).add("checkbox_toggle",class extends BV{static getters=["hasBooleanValidationInZones"];handle(e){if("TOGGLE_CHECKBOX"===e.type)this.toggleCheckbox(e.sheetId,e.target)}hasBooleanValidationInZones(e){const t=this.getters.getActiveSheetId();for(const o of e)for(let e=o.left;e<=o.right;e++)for(let s=o.top;s<=o.bottom;s++)if(this.getters.isCellValidCheckbox({col:e,row:s,sheetId:t}))return!0;return!1}toggleCheckbox(e,t){for(const o of t)for(let t=o.left;t<=o.right;t++)for(let s=o.top;s<=o.bottom;s++){const o={col:t,row:s,sheetId:e};if(this.getters.isCellValidCheckbox(o)){const e=this.getters.getEvaluatedCell(o).value?"FALSE":"TRUE";this.dispatch("UPDATE_CELL",{...o,content:e})}}}}).add("geo_features",class extends BV{static getters=["getGeoJsonFeatures","geoFeatureNameToId","getGeoChartAvailableRegions"];geoJsonService;geoJsonCache={};constructor(e){super(e),this.geoJsonService=e.external.geoJsonService}getGeoChartAvailableRegions(){return this.geoJsonService?this.geoJsonService.getAvailableRegions()||[]:(console.error("No geoJsonService provided to the model"),[])}getGeoJsonFeatures(e){if(!this.geoJsonService)return void console.error("No geoJsonService provided to the model");const t=this.geoJsonCache[e];return t instanceof Promise?void 0:void 0!==t?t??void 0:void(this.geoJsonCache[e]=new Promise((async t=>{const o=await(this.geoJsonService?.getTopoJson(e));this.geoJsonCache[e]=this.convertToGeoJson(o),this.dispatch("EVALUATE_CHARTS"),t()})))}geoFeatureNameToId(e,t){if(this.geoJsonService)return this.geoJsonService.geoFeatureNameToId(e,t);console.error("No geoJsonService provided to the model")}convertToGeoJson(e){if(!e)return null;if("Topology"===e.type){const t=window.ChartGeo.topojson.feature(e,Object.values(e.objects)[0]);return"FeatureCollection"===t.type?t.features:[t]}if("FeatureCollection"===e.type)return e.features;throw new Error("Invalid TopoJSON")}}),RL=(new n).add("selection",class extends BV{static layers=["Selection"];static getters=["getActiveSheet","getActiveSheetId","getActiveSheetName","getActiveCell","getActiveCols","getActiveRows","getCurrentStyle","getSelectedZones","getSelectedZone","getSelectedCells","getSelectedFigureId","getSelection","getActivePosition","getSheetPosition","isSingleColSelected","getElementsFromSelection","tryGetActiveSheetId","isGridSelectionActive","getSelectecUnboundedZone"];gridSelection={anchor:{cell:{col:0,row:0},zone:{top:0,left:0,bottom:0,right:0}},zones:[{top:0,left:0,bottom:0,right:0}]};selectedFigureId=null;sheetsData={};moveClient;isUnbounded;activeSheet=null;constructor(e){super(e),this.moveClient=e.moveClient,this.isUnbounded=!1}allowDispatch(e){switch(e.type){case"ACTIVATE_SHEET":try{if(!this.getters.getSheet(e.sheetIdTo).isVisible)return"SheetIsHidden";break}catch(e){return"InvalidSheetId"}case"MOVE_COLUMNS_ROWS":return this.isMoveElementAllowed(e)}return"Success"}handleEvent(e){const t=e.anchor;let o=[];switch(this.isUnbounded=e.options?.unbounded||!1,e.mode){case"overrideSelection":o=[t.zone];break;case"updateAnchor":o=[...this.gridSelection.zones];const s=o.findIndex((t=>Ir(t,e.previousAnchor.zone)));s>=0&&(o[s]=t.zone);break;case"newAnchor":o=[...this.gridSelection.zones,t.zone]}this.setSelectionMixin(e.anchor,o),this.selection.resetDefaultAnchor(this,ze(this.gridSelection.anchor));const{col:s,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:s,row:i}),this.selectedFigureId=null}handle(e){switch(e.type){case"ACTIVATE_SHEET":this.selectedFigureId=null;break;case"DELETE_FIGURE":this.selectedFigureId===e.figureId&&(this.selectedFigureId=null);break;case"DELETE_SHEET":this.selectedFigureId&&this.getters.getFigure(e.sheetId,this.selectedFigureId)&&(this.selectedFigureId=null)}switch(e.type){case"START":const t=this.getters.getVisibleSheetIds()[0];this.activateSheet(t,t);const{col:o,row:s}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(o,s),this.selection.registerAsDefault(this,this.gridSelection.anchor,{handleEvent:this.handleEvent.bind(this)}),this.moveClient({sheetId:t,col:0,row:0});break;case"ACTIVATE_SHEET":this.activateSheet(e.sheetIdFrom,e.sheetIdTo);break;case"REMOVE_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);const{col:o,row:s}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:o,row:s})}break}case"ADD_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);const{col:o,row:s}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:o,row:s})}break}case"MOVE_COLUMNS_ROWS":e.sheetId===this.getActiveSheetId()&&this.onMoveElements(e);break;case"SELECT_FIGURE":this.selectedFigureId=e.figureId;break;case"ACTIVATE_NEXT_SHEET":this.activateNextSheet("right");break;case"ACTIVATE_PREVIOUS_SHEET":this.activateNextSheet("left");break;case"HIDE_SHEET":e.sheetId===this.getActiveSheetId()&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e.sheetId,sheetIdTo:this.getters.getVisibleSheetIds()[0]});break;case"UNDO":case"REDO":case"DELETE_SHEET":const i=Object.keys(this.sheetsData).filter((e=>!this.getters.tryGetSheet(e)));for(const e of i)delete this.sheetsData[e];for(const e in this.sheetsData){const t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:ze(t)}}this.fallbackToVisibleSheet();const n=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map((e=>this.getters.expandZone(n,e))),this.gridSelection.anchor.zone=this.getters.expandZone(n,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones),this.selectedFigureId=null}}finalize(){this.fallbackToVisibleSheet(),this.selection.resetDefaultAnchor(this,ze(this.gridSelection.anchor))}isGridSelectionActive(){return this.selection.isListening(this)}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}getActiveSheetName(){return this.activeSheet.name}tryGetActiveSheetId(){return this.activeSheet?.id}getActiveCell(){return this.getters.getEvaluatedCell(this.getActivePosition())}getActiveCols(){const e=new Set;for(const t of this.gridSelection.zones)if(0===t.top&&t.bottom===this.getters.getNumberRows(this.getters.getActiveSheetId())-1)for(let o=t.left;o<=t.right;o++)e.add(o);return e}getActiveRows(){const e=new Set,t=this.getters.getActiveSheetId();for(const o of this.gridSelection.zones)if(0===o.left&&o.right===this.getters.getNumberCols(t)-1)for(let t=o.top;t<=o.bottom;t++)e.add(t);return e}getCurrentStyle(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();return this.getters.getCellStyle({sheetId:t,col:e.left,row:e.top})}getSelectedZones(){return ze(this.gridSelection.zones)}getSelectedZone(){return ze(this.gridSelection.anchor.zone)}getSelectecUnboundedZone(){return ze(this.isUnbounded?this.getters.getUnboundedZone(this.activeSheet.id,this.gridSelection.anchor.zone):this.gridSelection.anchor.zone)}getSelection(){return ze(this.gridSelection)}getSelectedCells(){const e=this.getters.getActiveSheetId(),t=[];for(const o of this.gridSelection.zones)t.push(...this.getters.getEvaluatedCellsInZone(e,o));return t}getSelectedFigureId(){return this.selectedFigureId}getActivePosition(){return this.getters.getMainCellPosition({sheetId:this.getActiveSheetId(),col:this.gridSelection.anchor.cell.col,row:this.gridSelection.anchor.cell.row})}getSheetPosition(e){if(e===this.getters.getActiveSheetId())return this.getActivePosition();{const t=this.sheetsData[e];return t?{sheetId:e,col:t.gridSelection.anchor.cell.col,row:t.gridSelection.anchor.cell.row}:this.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0})}}isSingleColSelected(){const e=this.getters.getSelectedZones();return 1===e.length&&e[0].left===e[0].right}getElementsFromSelection(e){if("COL"===e&&0===this.getters.getActiveCols().size)return[];if("ROW"===e&&0===this.getters.getActiveRows().size)return[];const t=this.getters.getSelectedZones();let o=[];const s="COL"===e?"left":"top",i="COL"===e?"right":"bottom";for(const e of t){const t=Array.from({length:e[i]-e[s]+1},((t,o)=>e[s]+o));o=o.concat(t)}return[...new Set(o)].sort()}activateSheet(e,t){if(this.setActiveSheet(t),this.sheetsData[e]={gridSelection:ze(this.gridSelection)},t in this.sheetsData)Object.assign(this,this.sheetsData[t]),this.selection.resetDefaultAnchor(this,ze(this.gridSelection.anchor));else{const{col:e,row:o}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(e,o)}const{col:o,row:s}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.activeSheet.id,col:o,row:s})}setSelectionMixin(e,t){const{anchor:o,zones:s}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=o,this.gridSelection.zones=function(e){return e.reverse().filter(((e,t,o)=>t===o.findIndex((t=>t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right)))).reverse()}(s)}selectCell(e,t){const o=this.getters.getActiveSheetId(),s=this.getters.expandZone(o,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:s,cell:{col:e,row:t}},[s])}setActiveSheet(e){this.activeSheet=this.getters.getSheet(e)}activateNextSheet(e){const t=this.getters.getSheetIds(),o=(t.findIndex((e=>e===this.activeSheet.id))+("left"===e?t.length-1:1))%t.length;this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[o]})}onColumnsRemoved(e){const{cell:t,zone:o}=this.gridSelection.anchor,s=Sr(o,"left",[...e.elements]);let i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=Sr(i,"left",[...e.elements]);const n={cell:{col:i.left,row:i.top},zone:s},r=this.gridSelection.zones.map((t=>Sr(t,"left",[...e.elements])));this.setSelectionMixin(n,r)}onRowsRemoved(e){const{cell:t,zone:o}=this.gridSelection.anchor,s=Sr(o,"top",[...e.elements]);let i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=Sr(i,"top",[...e.elements]);const n={cell:{col:i.left,row:i.top},zone:s},r=this.gridSelection.zones.map((t=>Sr(t,"top",[...e.elements])));this.setSelectionMixin(n,r)}onAddElements(e){const t="COL"===e.dimension?"left":"top",o=br(this.gridSelection.anchor.zone,t,e.base,e.position,e.quantity),s=this.gridSelection.zones.map((o=>br(o,t,e.base,e.position,e.quantity))),i={cell:{col:o.left,row:o.top},zone:o};this.setSelectionMixin(i,s)}onMoveElements(e){const t=e.elements.length,o=this.getFiguresUpdates(e);this.dispatch("ADD_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,sheetName:e.sheetName,base:e.base,quantity:t,position:e.position});const s="COL"===e.dimension,i=e.elements[0],n=e.elements[t-1],r=e.base<i,a=r&&s?t:0,l=r&&!s?t:0,c=r?e.elements.map((e=>e+t)):e.elements,h={};for(const t of c)h[t]=this.getters.getHeaderSize(e.sheetId,e.dimension,t);const d=[{left:s?i+a:0,right:s?n+a:this.getters.getNumberCols(e.sheetId)-1,top:s?0:i+l,bottom:s?this.getters.getNumberRows(e.sheetId)-1:n+l}],u=this.getActiveSheetId(),g=r?e.base:e.base+1,p=[{left:s?g:0,right:s?g+t-1:this.getters.getNumberCols(e.sheetId)-1,top:s?0:g,bottom:s?this.getters.getNumberRows(e.sheetId)-1:g+t-1}];for(const e of eh.cellHandlers.getAll()){const t=new e(this.getters,this.dispatch),o=t.copy(Qa(u,d),!1,"shiftCells");o&&t.paste({zones:p,sheetId:u},o,{isCutOperation:!0})}const m=p[0],f=m.left,v=m.top;this.setSelectionMixin({zone:m,cell:{col:f,row:v}},[m]);let b=r?e.base:e.base+1;const S={};for(const t of c){const o=h[t];o!==this.getters.getHeaderSize(e.sheetId,e.dimension,b)&&(S[o]??=[],S[o].push(b)),b+=1}for(const t in S)this.dispatch("RESIZE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,size:parseInt(t,10),elements:S[t]});this.dispatch("REMOVE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,sheetName:e.sheetName,elements:c}),this.applyFigureUpdates(o)}getFiguresUpdates(e){const t=[],o={},s=e.elements[0]<e.base?e.base-e.elements.length+1:e.base;for(let t=0;t<e.elements.length;t++)o[e.elements[t]]=s+t;for(const s of this.getters.getFigures(e.sheetId))"COL"===e.dimension&&s.col in o&&t.push({type:"UPDATE_FIGURE",sheetId:e.sheetId,figureId:s.id,col:o[s.col],row:s.row}),"ROW"===e.dimension&&s.row in o&&t.push({type:"UPDATE_FIGURE",sheetId:e.sheetId,figureId:s.id,row:o[s.row],col:s.col});return t}applyFigureUpdates(e){for(const t of e)this.dispatch(t.type,{...t})}isMoveElementAllowed(e){const t="COL"===e.dimension,o=e.elements[0],s=e.elements[e.elements.length-1],i=e.sheetId,n=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;if(n(i,o-1,o)||n(i,s,s+1)||n(i,e.base-1,e.base))return"WillRemoveExistingMerge";const r=[e.base,...e.elements],a=t?this.getters.getNumberCols(i):this.getters.getNumberRows(i);return r.some((e=>e<0||e>=a))?"InvalidHeaderIndex":t||this.isTableRowMoveAllowed(i,e.elements)?"Success":"CannotMoveTableHeader"}isTableRowMoveAllowed(e,t){const o=this.getters.getCoreTables(e);if(0===o.length)return!0;const s=new Set(t);return o.every((({range:{zone:e},config:o})=>{const{top:i,bottom:n}=e;if(0===o.numberOfHeaders)return!0;const r=i+o.numberOfHeaders-1;if(!t.some((e=>e>=i&&e<=r)))return!0;return je(i,n+1).every((e=>s.has(e)))}))}fallbackToVisibleSheet(){if(!this.getters.tryGetSheet(this.getters.getActiveSheetId())){const e=this.getters.getVisibleSheetIds();if(this.activeSheet=this.getters.getSheet(e[0]),this.activeSheet.id in this.sheetsData){const{anchor:e}=this.clipSelection(this.activeSheet.id,this.sheetsData[this.activeSheet.id].gridSelection);this.selectCell(e.cell.col,e.cell.row)}else this.selectCell(0,0);const{col:t,row:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:o})}}clipSelection(e,t){const o=this.getters.getNumberCols(e)-1,s=this.getters.getNumberRows(e)-1;return{zones:t.zones.map((e=>({left:Ze(e.left,0,o),right:Ze(e.right,0,o),top:Ze(e.top,0,s),bottom:Ze(e.bottom,0,s)}))),anchor:{cell:{col:Ze(t.anchor.cell.col,0,o),row:Ze(t.anchor.cell.row,0,s)},zone:{left:Ze(t.anchor.zone.left,0,o),right:Ze(t.anchor.zone.right,0,o),top:Ze(t.anchor.zone.top,0,s),bottom:Ze(t.anchor.zone.bottom,0,s)}}}}drawLayer(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:o}=e,s=this.getSelectedZones();t.fillStyle="#f3f7fe";const i=1===s.length&&s[0].left===s[0].right&&s[0].top===s[0].bottom;t.fillStyle=i?"#f3f7fe":"#e9f0ff",t.strokeStyle=p,t.lineWidth=1.5*o;for(const e of s){const{x:o,y:s,width:i,height:n}=this.getters.getVisibleRect(e);t.globalCompositeOperation="multiply",t.fillRect(o,s,i,n),t.globalCompositeOperation="source-over",t.strokeRect(o,s,i,n)}t.globalCompositeOperation="source-over";const n=this.getActivePosition();let r;t.strokeStyle=p,t.lineWidth=3*o,r=this.getters.isInMerge(n)?this.getters.getMerge(n):Mr(n);const{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(r);c>0&&h>0&&t.strokeRect(a,l,c,h)}}).add("evaluation_filter",class extends BV{static getters=["getFilterValue","getFilterHiddenValues","getFilterCriterionValue","getFirstTableInSelection","isRowFiltered","isFilterActive"];filterValues={};hiddenRows={};isEvaluationDirty=!1;allowDispatch(e){if("UPDATE_FILTER"===e.type)if(!this.getters.getFilterId(e))return"FilterNotFound";return"Success"}handle(e){switch(e.type){case"UNDO":case"REDO":case"UPDATE_CELL":case"EVALUATE_CELLS":case"ACTIVATE_SHEET":case"REMOVE_TABLE":case"ADD_COLUMNS_ROWS":case"REMOVE_COLUMNS_ROWS":case"UPDATE_TABLE":this.isEvaluationDirty=!0;break;case"START":for(const e of this.getters.getSheetIds())this.filterValues[e]={};break;case"CREATE_SHEET":this.filterValues[e.sheetId]={};break;case"HIDE_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"GROUP_HEADERS":case"UNGROUP_HEADERS":case"FOLD_HEADER_GROUP":case"UNFOLD_HEADER_GROUP":case"FOLD_ALL_HEADER_GROUPS":case"UNFOLD_ALL_HEADER_GROUPS":case"FOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_HEADER_GROUPS_IN_ZONE":this.updateHiddenRows(e.sheetId);break;case"UPDATE_FILTER":this.updateFilter(e),this.updateHiddenRows(e.sheetId);break;case"DUPLICATE_SHEET":this.filterValues[e.sheetIdTo]=ze(this.filterValues[e.sheetId])}}finalize(){if(this.isEvaluationDirty){for(const e of this.getters.getSheetIds())this.updateHiddenRows(e);this.isEvaluationDirty=!1}}isRowFiltered(e,t){return!!this.hiddenRows[e]?.has(t)}getFilterValue(e){const t=this.getters.getFilterId(e),o=e.sheetId;return t?this.filterValues[o]?.[t]:void 0}getFilterHiddenValues(e){const t=this.getters.getFilterId(e),o=e.sheetId;if(!t||!this.filterValues[o])return[];const s=this.filterValues[o][t]||[];return"values"===s.filterType?s.hiddenValues:[]}getFilterCriterionValue(e){const t=this.getters.getFilterId(e),o=e.sheetId;if(!t||!this.filterValues[o])return wL;const s=this.filterValues[o][t];return s&&"criterion"===s.filterType?s:wL}isFilterActive(e){const t=this.getters.getFilterId(e);if(!t)return!1;const o=e.sheetId,s=this.filterValues[o]?.[t];return!!s&&("values"===s.filterType?s.hiddenValues.length>0:"none"!==s.type)}getFirstTableInSelection(){const e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZones();return this.getters.getTablesOverlappingZones(e,t)[0]}updateFilter({col:e,row:t,value:o,sheetId:s}){const i=this.getters.getFilterId({sheetId:s,col:e,row:t});i&&(this.filterValues[s]||(this.filterValues[s]={}),this.filterValues[s][i]=o)}updateHiddenRows(e){const t=this.getters.getFilters(e).sort(((e,t)=>e.rangeWithHeaders.zone.top-t.rangeWithHeaders.zone.top)),o=new Set;for(const s of t){const t=this.filterValues[e]?.[s.id],i=s.filteredRange?.zone;if(t&&i&&!o.has(s.rangeWithHeaders.zone.top)&&!this.getters.isRowHiddenByUser(e,s.rangeWithHeaders.zone.top))if("values"===t.filterType){const n=t.hiddenValues?.map(qa);if(!n)continue;const r=new Set(n);for(let t=i.top;t<=i.bottom;t++){const i=this.getCellValueAsString(e,s.col,t);r.has(i)&&o.add(t)}}else{if("none"===t.type)continue;const n=eE.get(t.type),r=t.values.map((t=>t.startsWith("=")?this.getters.evaluateFormula(e,t)??"":Kn(t,qs)));if(r.some(oc))continue;const a={type:t.type,values:r.map(ec),dateValue:t.dateValue};for(let t=i.top;t<=i.bottom;t++){const i={sheetId:e,col:s.col,row:t},r=this.getters.getEvaluatedCell(i).value??"";n.isValueValid(r,a,this.getters,e)||o.add(t)}}}this.hiddenRows[e]=o}getCellValueAsString(e,t,o){return this.getters.getEvaluatedCell({sheetId:e,col:t,row:o}).formattedValue.toLowerCase()}exportForExcel(e){for(const t of e.sheets){const e=t.id;for(const o of t.tables){const s=ur(o.range),i=[],n=[];for(const o of je(0,Tr(s).numberOfCols)){const r={sheetId:t.id,col:s.left+o,row:s.top},a=this.getFilterHiddenValues(r),l=this.getters.getFilter(r),c=l?.filteredRange?_r(l.filteredRange.zone).map((t=>this.getters.getEvaluatedCell({sheetId:e,...t}).formattedValue)):[];if(a.length){const e=c.filter((e=>e)).filter((e=>!a.includes(e)));i.push({colId:o,displayedValues:[...new Set(e)],displayBlanks:!a.includes("")&&c.some((e=>!e))})}const h=this.getters.getEvaluatedCell(r).formattedValue,d=this.getUniqueColNameForExcel(o,h,n);n.push(d);const u=Po(r.col,r.row);t.cells[u]=d,t.cellValues[u]=d}o.filters=i}}}getUniqueColNameForExcel(e,t,o){return t||(t=`Column${e}`),Vt(t,o,{compute:(e,o)=>t+String(o),start:2})}}).add("header_visibility_ui",class extends BV{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,o){return"COL"===t?this.isColHidden(e,o):this.isRowHidden(e,o)}getNextVisibleCellPosition({sheetId:e,col:t,row:o}){return{sheetId:e,col:this.findVisibleHeader(e,"COL",t,this.getters.getNumberCols(e)-1),row:this.findVisibleHeader(e,"ROW",o,this.getters.getNumberRows(e)-1)}}findVisibleHeader(e,t,o,s){if(o<=s)for(let i=o;i<=s;i++)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i;if(o>s)for(let i=o;i>=s;i--)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}findLastVisibleColRowIndex(e,t,{last:o,first:s}){return je(o,s,-1).find((o=>!this.isHeaderHidden(e,t,o)))||s}findFirstVisibleColRowIndex(e,t){const o=this.getters.getNumberHeaders(e,t);for(let s=0;s<o;s++){if("COL"===t&&!this.isColHidden(e,s))return s;if("ROW"===t&&!this.isRowHidden(e,s))return s}}exportForExcel(e){for(const t of e.sheets)for(const[e,o]of Object.entries(t.rows))o.isHidden=this.isRowHidden(t.id,Number(e))}}).add("cell_computed_style",class extends BV{static getters=["getCellComputedBorder","getCellComputedStyle"];styles={};borders={};handle(e){if(Fs.has(e.type)||"UPDATE_CELL"===e.type||"SET_FORMATTING"===e.type||"ADD_DATA_VALIDATION_RULE"===e.type||"REMOVE_DATA_VALIDATION_RULE"===e.type||"EVALUATE_CELLS"===e.type)return this.styles={},void(this.borders={});rL(e)?"sheetId"in e?(delete this.styles[e.sheetId],delete this.borders[e.sheetId]):(this.styles={},this.borders={}):Ns.has(e.type)?this.styles={}:ks.has(e.type)&&(this.borders={})}getCellComputedBorder(e){const{sheetId:t,row:o,col:s}=e;return void 0!==this.borders[t]?.[o]?.[s]||(this.borders[t]||(this.borders[t]={}),this.borders[t][o]||(this.borders[t][o]={}),this.borders[t][o][s]||(this.borders[t][o][s]=this.computeCellBorder(e))),this.borders[t][o][s]}getCellComputedStyle(e){const{sheetId:t,row:o,col:s}=e;return void 0!==this.styles[t]?.[o]?.[s]||(this.styles[t]||(this.styles[t]={}),this.styles[t][o]||(this.styles[t][o]={}),this.styles[t][o][s]||(this.styles[t][o][s]=this.computeCellStyle(e))),this.styles[t][o][s]}computeCellBorder(e){const t=this.getters.getCellBorder(e)||{},o={...bt(this.getters.getCellTableBorder(e)||{}),...bt(t)};return ct(o)?null:o}computeCellStyle(e){const t=this.getters.getCell(e),o=this.getters.getCellConditionalFormatStyle(e),s=this.getters.getCellTableStyle(e),i=this.getters.getDataValidationCellStyle(e),n={...bt(s),...bt(i),...bt(t?.style),...bt(o)};return this.getters.getEvaluatedCell(e).link&&!n.textColor&&(n.textColor=b),n}}).add("table_computed_style",class extends BV{static getters=["getCellTableStyle","getCellTableBorder"];tableStyles={};handle(e){Fs.has(e.type)||"UPDATE_CELL"===e.type&&("content"in e||"format"in e)||"EVALUATE_CELLS"===e.type?this.tableStyles={}:rL(e)&&("sheetId"in e?delete this.tableStyles[e.sheetId]:this.tableStyles={})}finalize(){for(const e of this.getters.getSheetIds()){this.tableStyles[e]||(this.tableStyles[e]={});for(const t of this.getters.getTables(e))this.tableStyles[e][t.id]||(this.tableStyles[e][t.id]=this.computeTableStyle(e,t))}}getCellTableStyle(e){const t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().styles[e.col]?.[e.row]}getCellTableBorder(e){const t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().borders[e.col]?.[e.row]}computeTableStyle(e,t){return ut((()=>{const{config:o,numberOfCols:s,numberOfRows:i}=this.getTableRuntimeConfig(e,t),n=w_(o,this.getters.getTableStyle(t.config.styleId),s,i),r=this.getTableMapping(e,t),a={borders:{},styles:{}};for(let e=0;e<s;e++){const t=r.colMapping[e];a.borders[t]={},a.styles[t]={};for(let o=0;o<i;o++){const s=r.rowMapping[o];a.borders[t][s]=n.borders[e][o],a.styles[t][s]=n.styles[e][o]}}return a}))}getTableRuntimeConfig(e,t){const o=t.range.zone,s={...t.config};let i=o.right-o.left+1,n=o.bottom-o.top+1;for(let i=o.top;i<=o.bottom;i++)this.getters.isRowHidden(e,i)&&(n--,i-o.top<t.config.numberOfHeaders&&(s.numberOfHeaders--,s.numberOfHeaders<0&&(s.numberOfHeaders=0)),i===o.bottom&&(s.totalRow=!1));for(let t=o.left;t<=o.right;t++)this.getters.isColHidden(e,t)&&(i--,t===o.left&&(s.firstColumn=!1),t===o.right&&(s.lastColumn=!1));return{config:s,numberOfCols:i,numberOfRows:n}}getTableMapping(e,t){const o={},s={};let i=0,n=0;const r=t.range.zone;for(let t=r.left;t<=r.right;t++)if(!this.getters.isColHidden(e,t)){o[i]=t,i++;for(let t=r.top;t<=r.bottom;t++)this.getters.isRowHidden(e,t)||(s[n]=t,n++)}return{colMapping:o,rowMapping:s}}}).add("header_positions",class extends BV{static getters=["getColDimensions","getRowDimensions","getColRowOffset"];headerPositions={};isDirty=!0;handle(e){switch(Fs.has(e.type)&&(this.headerPositions={},this.isDirty=!0),e.type){case"START":for(const e of this.getters.getSheetIds())this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e);break;case"UPDATE_CELL":case"UPDATE_FILTER":case"UPDATE_TABLE":case"REMOVE_TABLE":this.headerPositions={},this.isDirty=!0;break;case"REMOVE_COLUMNS_ROWS":case"RESIZE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"FOLD_HEADER_GROUP":case"UNFOLD_HEADER_GROUP":case"FOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_ALL_HEADER_GROUPS":case"FOLD_ALL_HEADER_GROUPS":case"UNGROUP_HEADERS":case"GROUP_HEADERS":case"CREATE_SHEET":this.getters.tryGetSheet(e.sheetId)&&(this.headerPositions[e.sheetId]=this.computeHeaderPositionsOfSheet(e.sheetId));break;case"DUPLICATE_SHEET":this.headerPositions[e.sheetIdTo]=ze(this.headerPositions[e.sheetId])}}finalize(){for(const e of this.getters.getSheetIds())!this.isDirty&&this.headerPositions[e]||(this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e));this.isDirty=!1}getColDimensions(e,t){const o=this.headerPositions[e].COL[t],s=this.getters.getColSize(e,t);return{start:o,size:s,end:o+(this.getters.isColHidden(e,t)?0:s)}}getRowDimensions(e,t){const o=this.headerPositions[e].ROW[t],s=this.getters.getRowSize(e,t);return{start:o,size:s,end:o+(this.getters.isRowHidden(e,t)?0:s)}}getColRowOffset(e,t,o,s=this.getters.getActiveSheetId()){const i=this.headerPositions[s][e][t];return this.headerPositions[s][e][o]-i}computeHeaderPositionsOfSheet(e){return{COL:this.computePositions(e,"COL"),ROW:this.computePositions(e,"ROW")}}computePositions(e,t){const o={};let s=0;for(let i=0;i<this.getters.getNumberHeaders(e,t)+1;i++)o[i]=s,this.getters.isHeaderHidden(e,t,i)||(s+=this.getters.getHeaderSize(e,t,i));return o}}).add("viewport",class extends BV{static getters=["getColIndex","getRowIndex","getActiveMainViewport","getSheetViewDimension","getSheetViewDimensionWithHeaders","getMainViewportRect","isVisibleInViewport","getEdgeScrollCol","getEdgeScrollRow","getVisibleFigures","getVisibleRect","getVisibleRectWithoutHeaders","getVisibleCellPositions","getColRowOffsetInViewport","getMainViewportCoordinates","getActiveSheetScrollInfo","getSheetViewVisibleCols","getSheetViewVisibleRows","getFrozenSheetViewRatio","isPixelPositionVisible","getColDimensionsInViewport","getRowDimensionsInViewport","getAllActiveViewportsZonesAndRect","getRect","getFigureUI","getPositionAnchorOffset","getGridOffset"];viewports={};sheetViewWidth=Me();sheetViewHeight=Me();gridOffsetX=0;gridOffsetY=0;sheetsWithDirtyViewports=new Set;shouldAdjustViewports=!1;allowDispatch(e){switch(e.type){case"SET_VIEWPORT_OFFSET":return this.chainValidations(this.checkScrollingDirection,this.checkIfViewportsWillChange)(e);case"RESIZE_SHEETVIEW":return this.chainValidations(this.checkValuesAreDifferent,this.checkPositiveDimension)(e);default:return"Success"}}handleEvent(e){const t=this.getters.getActiveSheetId();if(e.options.scrollIntoView){let{col:o,row:s}=Pr(e.previousAnchor.zone,e.anchor.zone);if("updateAnchor"===e.mode){const i=e.previousAnchor.zone,n=e.anchor.zone,{top:r,bottom:a,left:l,right:c}=this.getMainInternalViewport(t);i.left===n.left&&i.right===n.right&&(o=l>o||o>c?l:o),i.top===n.top&&i.bottom===n.bottom&&(s=r>s||s>a?r:s)}o=Math.min(o,this.getters.getNumberCols(t)-1),s=Math.min(s,this.getters.getNumberRows(t)-1),this.sheetsWithDirtyViewports.has(t)||this.refreshViewport(this.getters.getActiveSheetId(),{col:o,row:s})}}handle(e){if(Fs.has(e.type))for(const e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);switch(e.type){case"START":this.selection.observe(this,{handleEvent:this.handleEvent.bind(this)}),this.resetViewports(this.getters.getActiveSheetId());break;case"UNDO":case"REDO":this.cleanViewports();for(const e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);this.shouldAdjustViewports=!0;break;case"RESIZE_SHEETVIEW":this.resizeSheetView(e.height,e.width,e.gridOffsetX,e.gridOffsetY);break;case"SET_VIEWPORT_OFFSET":this.setSheetViewOffset(e.offsetX,e.offsetY);break;case"SHIFT_VIEWPORT_DOWN":const t=this.getters.getActiveSheetId(),{top:o,viewportHeight:s,offsetCorrectionY:i}=this.getMainInternalViewport(t),n=this.getters.getRowDimensions(t,o);this.shiftVertically(n.start+s-i);break;case"SHIFT_VIEWPORT_UP":{const e=this.getters.getActiveSheetId(),{top:t,viewportHeight:o,offsetCorrectionY:s}=this.getMainInternalViewport(e),i=this.getters.getRowDimensions(e,t);this.shiftVertically(i.end-s-o);break}case"REMOVE_TABLE":case"UPDATE_TABLE":case"UPDATE_FILTER":case"UNFREEZE_ROWS":case"UNFREEZE_COLUMNS":case"FREEZE_COLUMNS":case"FREEZE_ROWS":case"UNFREEZE_COLUMNS_ROWS":case"REMOVE_COLUMNS_ROWS":case"RESIZE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"UNGROUP_HEADERS":case"GROUP_HEADERS":case"FOLD_HEADER_GROUP":case"UNFOLD_HEADER_GROUP":case"FOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_ALL_HEADER_GROUPS":case"FOLD_ALL_HEADER_GROUPS":this.sheetsWithDirtyViewports.add(e.sheetId);break;case"UPDATE_CELL":if("content"in e||"format"in e||void 0!==e.style?.fontSize)for(const e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);break;case"DELETE_SHEET":this.cleanViewports(),this.sheetsWithDirtyViewports.delete(e.sheetId);break;case"ACTIVATE_SHEET":this.sheetsWithDirtyViewports.add(e.sheetIdTo);break;case"SCROLL_TO_CELL":this.refreshViewport(this.getters.getActiveSheetId(),{col:e.col,row:e.row})}}finalize(){for(const e of this.sheetsWithDirtyViewports)if(this.resetViewports(e),this.shouldAdjustViewports){const t=this.getters.getSheetPosition(e);this.getSubViewports(e).forEach((e=>{e.adjustPosition(t)}))}this.sheetsWithDirtyViewports=new Set,this.shouldAdjustViewports=!1,this.setViewports()}setViewports(){const e=this.getters.getSheetIds();for(const t of e)this.viewports[t]?.bottomRight||this.resetViewports(t)}getColIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map((t=>t.getColIndex(e))))}getRowIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map((t=>t.getRowIndex(e))))}getSheetViewDimensionWithHeaders(){return{width:this.sheetViewWidth+this.gridOffsetX,height:this.sheetViewHeight+this.gridOffsetY}}getSheetViewDimension(){return{width:this.sheetViewWidth,height:this.sheetViewHeight}}getGridOffset(){return{x:this.gridOffsetX,y:this.gridOffsetY}}getActiveMainViewport(){const e=this.getters.getActiveSheetId();return this.getMainViewport(e)}getActiveSheetScrollInfo(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetX,scrollY:t.offsetY}}getSheetViewVisibleCols(){const e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map((e=>je(e.left,e.right+1))).flat())].filter((t=>t>=0&&!this.getters.isHeaderHidden(e,"COL",t)))}getSheetViewVisibleRows(){const e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map((e=>je(e.top,e.bottom+1))).flat())].filter((t=>t>=0&&!this.getters.isHeaderHidden(e,"ROW",t)))}getVisibleCellPositions(){const e=this.getSheetViewVisibleCols(),t=this.getSheetViewVisibleRows(),o=this.getters.getActiveSheetId(),s=[];for(const i of e)for(const e of t){const t={sheetId:o,col:i,row:e},n=this.getters.getMainCellPosition(t);n.row===e&&n.col===i&&s.push(t)}return s}getMainViewportRect(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e),{xSplit:o,ySplit:s}=this.getters.getPaneDivisions(e),{width:i,height:n}=t.getMaxSize();return{x:this.getters.getColDimensions(e,o).start,y:this.getters.getRowDimensions(e,s).start,width:i,height:n}}getMaximumSheetOffset(){const e=this.getters.getActiveSheetId(),{width:t,height:o}=this.getMainViewportRect(),s=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-s.viewportWidth),maxOffsetY:Math.max(0,o-s.viewportHeight)}}getColRowOffsetInViewport(e,t,o){if(o<t)return-this.getColRowOffsetInViewport(e,o,t);const s=this.getters.getActiveSheetId(),i="COL"===e?this.getters.getSheetViewVisibleCols():this.getters.getSheetViewVisibleRows(),n=i.findIndex((e=>t>=e));let r=i.findIndex((e=>o<=e));r=-1===r?i.length:r;const a=i.slice(n,r);let l=0;for(const t of a)l+=this.getters.getHeaderSize(s,e,t);return l}isVisibleInViewport({sheetId:e,col:t,row:o}){return this.getSubViewports(e).some((e=>e.isVisible(t,o)))}getEdgeScrollCol(e,t,o){let s=!1,i=0,n=0;const{xSplit:r}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{width:a}=this.getSheetViewDimension(),{x:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollX;return e>a?(s=!0,n=jr(e-a),i=1):e<l&&o>=l&&c>0?(s=!0,n=jr(l-e),i=-1):r&&t<l&&e>l&&(s=!0,n=jr(e),i="reset"),{canEdgeScroll:s,direction:i,delay:n}}getEdgeScrollRow(e,t,o){let s=!1,i=0,n=0;const{ySplit:r}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{height:a}=this.getSheetViewDimension(),{y:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollY;return e>a?(s=!0,n=jr(e-a),i=1):e<l&&o>=l&&c>0?(s=!0,n=jr(l-e),i=-1):r&&t<l&&e>l&&(s=!0,n=jr(e),i="reset"),{canEdgeScroll:s,direction:i,delay:n}}getVisibleRect(e){const t=this.getVisibleRectWithoutHeaders(e);return{...t,x:t.x+this.gridOffsetX,y:t.y+this.gridOffsetY}}getVisibleRectWithoutHeaders(e){const t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,(t=>t.getVisibleRect(e)))}getRect(e){const t=this.getters.getActiveSheetId(),o=this.mapViewportsToRect(t,(t=>t.getFullRect(e)));return{...o,x:o.x+this.gridOffsetX,y:o.y+this.gridOffsetY}}getRectWithoutHeaders(e){const t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,(t=>t.getFullRect(e)))}getMainViewportCoordinates(){const e=this.getters.getActiveSheetId(),{xSplit:t,ySplit:o}=this.getters.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,o).start}}getColDimensionsInViewport(e,t){const{top:o}=this.getMainInternalViewport(e),s={left:t,right:t,top:o,bottom:o},{x:i,width:n}=this.getVisibleRect(s),r=i-this.gridOffsetX;return{start:r,size:n,end:r+n}}getRowDimensionsInViewport(e,t){const{left:o}=this.getMainInternalViewport(e),s={left:0,right:o,top:t,bottom:t},{y:i,height:n}=this.getVisibleRect(s),r=i-this.gridOffsetY;return{start:r,size:n,end:r+n}}getAllActiveViewportsZonesAndRect(){const e=this.getters.getActiveSheetId();return this.getSubViewports(e).map((e=>({zone:e,rect:{x:e.offsetCorrectionX+this.gridOffsetX,y:e.offsetCorrectionY+this.gridOffsetY,...e.getMaxSize()}})))}ensureMainViewportExist(e){this.viewports[e]||this.resetViewports(e)}getSubViewports(e){return this.ensureMainViewportExist(e),Object.values(this.viewports[e]).filter(lt)}checkPositiveDimension(e){return e.width<0||e.height<0?"InvalidViewportSize":"Success"}checkValuesAreDifferent(e){const{height:t,width:o}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===o&&e.height===t?"ValuesNotChanged":"Success"}checkScrollingDirection({offsetX:e,offsetY:t}){const o=this.getMainInternalViewport(this.getters.getActiveSheetId());return!o.canScrollHorizontally&&e>0||!o.canScrollVertically&&t>0?"InvalidScrollingDirection":"Success"}checkIfViewportsWillChange({offsetX:e,offsetY:t}){const o=this.getters.getActiveSheetId(),{maxOffsetX:s,maxOffsetY:i}=this.getMaximumSheetOffset();return this.getSubViewports(o).some((o=>o.willNewOffsetScrollViewport(Ze(e,0,s),Ze(t,0,i))))?"Success":"ViewportScrollLimitsReached"}getMainViewport(e){const t=this.getMainInternalViewport(e);return{top:t.top,left:t.left,bottom:t.bottom,right:t.right}}getMainInternalViewport(e){return this.ensureMainViewportExist(e),this.viewports[e].bottomRight}cleanViewports(){const e={};for(const t of this.getters.getSheetIds())e[t]=this.viewports[t];this.viewports=e}resizeSheetView(e,t,o=0,s=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=o,this.gridOffsetY=s,this.recomputeViewports()}recomputeViewports(){for(const e of this.getters.getSheetIds())this.resetViewports(e)}setSheetViewOffset(e,t){const o=this.getters.getActiveSheetId(),{maxOffsetX:s,maxOffsetY:i}=this.getMaximumSheetOffset();this.getSubViewports(o).forEach((o=>o.setViewportOffset(Ze(e,0,s),Ze(t,0,i))))}getViewportOffset(e){return{x:this.viewports[e]?.bottomRight.offsetX||0,y:this.viewports[e]?.bottomRight.offsetY||0}}resetViewports(e){if(!this.getters.tryGetSheet(e))return;const{xSplit:t,ySplit:o}=this.getters.getPaneDivisions(e),s=this.getters.getNumberCols(e),i=this.getters.getNumberRows(e),n=Math.min(this.getters.getColRowOffset("COL",0,t,e),this.sheetViewWidth),r=Math.min(this.getters.getColRowOffset("ROW",0,o,e),this.sheetViewHeight),a=Math.max(this.sheetViewWidth-n,0),l=Math.max(this.sheetViewHeight-r,0),{xRatio:c,yRatio:h}=this.getFrozenSheetViewRatio(e),d=c<1,u=h<1,g=this.getViewportOffset(e),p={topLeft:o&&t&&new IL(this.getters,e,{left:0,right:t-1,top:0,bottom:o-1},{width:n,height:r},{canScrollHorizontally:!1,canScrollVertically:!1},{x:0,y:0})||void 0,topRight:o&&new IL(this.getters,e,{left:t,right:s-1,top:0,bottom:o-1},{width:a,height:r},{canScrollHorizontally:d,canScrollVertically:!1},{x:d?g.x:0,y:0})||void 0,bottomLeft:t&&new IL(this.getters,e,{left:0,right:t-1,top:o,bottom:i-1},{width:n,height:l},{canScrollHorizontally:!1,canScrollVertically:u},{x:0,y:u?g.y:0})||void 0,bottomRight:new IL(this.getters,e,{left:t,right:s-1,top:o,bottom:i-1},{width:a,height:l},{canScrollHorizontally:d,canScrollVertically:u},{x:d?g.x:0,y:u?g.y:0})};this.viewports[e]=p}refreshViewport(e,t){this.getSubViewports(e).forEach((e=>{e.adjustViewportZone(),e.adjustPosition(t)}))}shiftVertically(e){const t=this.getters.getActiveSheetId(),{top:o}=this.getMainInternalViewport(t),{scrollX:s}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(s,e);const{anchor:i}=this.getters.getSelection();if(i.cell.row>=this.getters.getPaneDivisions(t).ySplit){const e=this.getMainInternalViewport(t).top-o;this.selection.selectCell(i.cell.col,i.cell.row+e)}}getColIndexLeftOfMainViewport(e){if(e>=0)return-1;const t=this.getters.getActiveSheetId();let o=this.getActiveMainViewport().left,s=-this.getActiveSheetScrollInfo().scrollX-this.getters.getColRowOffset("COL",o,0);for(;e<s;o--)s-=this.getters.getColSize(t,o-1);return Math.max(o,0)}getRowIndexTopOfMainViewport(e){if(e>=0)return-1;const t=this.getters.getActiveSheetId();let o=this.getActiveMainViewport().top,s=-this.getActiveSheetScrollInfo().scrollY-this.getters.getColRowOffset("ROW",o,0);for(;e<s;o--)s-=this.getters.getRowSize(t,o-1);return Math.max(o,0)}getVisibleFigures(){const e=this.getters.getActiveSheetId(),t=[],o=this.getters.getFigures(e),{scrollX:s,scrollY:i}=this.getters.getActiveSheetScrollInfo(),{x:n,y:r}=this.getMainViewportCoordinates(),{width:a,height:l}=this.getters.getSheetViewDimensionWithHeaders();for(const c of o){const o=this.getFigureUI(e,c),{x:h,y:d}=o;h>=n&&(h+c.width<s+n||h>a+s+n)||(d>=r&&(d+c.height<i+r||d>l+i+r)||t.push(o))}return t}getFigureUI(e,t){const o=t.offset.x+this.getters.getColDimensions(e,t.col).start,s=t.offset.y+this.getters.getRowDimensions(e,t.row).start;return{...t,x:o,y:s}}getPositionAnchorOffset(e){const{scrollX:t,scrollY:o}=this.getters.getActiveSheetScrollInfo(),s=e.x-t,i=e.y-o,n=s>=0?this.getColIndex(s):this.getColIndexLeftOfMainViewport(s),r=i>=0?this.getRowIndex(i):this.getRowIndexTopOfMainViewport(i),{x:a,y:l}=this.getRect(Mr({col:n,row:r}));return{col:n,row:r,offset:{x:Math.max(s-a+this.gridOffsetX,0),y:Math.max(i-l+this.gridOffsetY,0)}}}isPixelPositionVisible(e){const{scrollX:t,scrollY:o}=this.getters.getActiveSheetScrollInfo(),{x:s,y:i}=this.getters.getMainViewportCoordinates(),{width:n,height:r}=this.getters.getSheetViewDimension();return!(e.x>=s&&(e.x<s+t||e.x>n+t+s))&&!(e.y>=i&&(e.y<i+o||e.y>r+o+i))}getFrozenSheetViewRatio(e){const{xSplit:t,ySplit:o}=this.getters.getPaneDivisions(e),s=this.getters.getColDimensions(e,t).start,i=this.getters.getRowDimensions(e,o).start;return{xRatio:s/(this.sheetViewWidth+this.gridOffsetX),yRatio:i/(this.sheetViewHeight+this.gridOffsetY)}}mapViewportsToRect(e,t){let o=1/0,s=1/0,i=0,n=0,r=!1;for(const a of this.getSubViewports(e)){const e=t(a);e&&(r=!0,o=Math.min(o,e.x),s=Math.min(s,e.y),i=Math.max(i,e.x+e.width),n=Math.max(n,e.y+e.height))}return r?{x:o,y:s,width:i-o,height:n-s}:{x:0,y:0,width:0,height:0}}}).add("clipboard",class extends BV{static layers=["Clipboard"];static getters=["getClipboardTextAndImageContent","getClipboardId","getClipboardTextContent","isCutOperation"];status="invisible";originSheetId;copiedData;_isCutOperation=!1;clipboardId=(new Ka).uuidv4();fileStore;uuidGenerator;constructor(e){super(e),this.fileStore=e.external.fileStore,this.uuidGenerator=new Ka}allowDispatch(e){switch(e.type){case"CUT":const t=this.getters.getSelectedZones();return this.isCutAllowedOn(t);case"PASTE_FROM_OS_CLIPBOARD":{const t=this.convertTextToClipboardData(e.clipboardContent.text??""),o=e.pasteOption;return this.isPasteAllowed(e.target,t,{pasteOption:o,isCutOperation:!1})}case"PASTE":{if(!this.copiedData)return"EmptyClipboard";const t=e.pasteOption;return this.isPasteAllowed(e.target,this.copiedData,{pasteOption:t,isCutOperation:this._isCutOperation})}case"COPY_PASTE_CELLS_ABOVE":{const e=this.getters.getSelectedZones();if(e.length>1||0===e[0].top&&0===e[0].bottom)return"InvalidCopyPasteSelection";break}case"COPY_PASTE_CELLS_ON_LEFT":{const e=this.getters.getSelectedZones();if(e.length>1||0===e[0].left&&0===e[0].right)return"InvalidCopyPasteSelection";break}case"INSERT_CELL":{const{cut:t,paste:o}=this.getInsertCellsTargets(e.zone,e.shiftDimension),s=this.copy(t,"shiftCells");return this.isPasteAllowed(o,s,{isCutOperation:!0})}case"DELETE_CELL":{const{cut:t,paste:o}=this.getDeleteCellsTargets(e.zone,e.shiftDimension),s=this.copy(t,"shiftCells");return this.isPasteAllowed(o,s,{isCutOperation:!0})}}return"Success"}handle(e){switch(e.type){case"COPY":case"CUT":const t=this.getters.getSelectedZones();this.status="visible",this.originSheetId=this.getters.getActiveSheetId(),this._isCutOperation="CUT"===e.type,this.copiedData=this.copy(t);break;case"PASTE_FROM_OS_CLIPBOARD":{this._isCutOperation=!1;const t=e.clipboardContent.data;if(e.clipboardContent.imageData){const t=this.getters.getActiveSheetId(),o=this.uuidGenerator.uuidv4(),s=e.clipboardContent.imageData,i=px(this.getters,s.size);this.dispatch("CREATE_IMAGE",{definition:s,size:i,col:e.target[0].left,row:e.target[0].top,offset:{x:0,y:0},sheetId:t,figureId:o})}this.copiedData=t||this.convertTextToClipboardData(e.clipboardContent.text??"");const o=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:o,selectTarget:!0,isCutOperation:!1}),this.status="invisible",this.copiedData=void 0;break}case"PASTE":{const t=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:t,selectTarget:!0,isCutOperation:this._isCutOperation}),this.status="invisible",this._isCutOperation&&(this.copiedData=void 0,this._isCutOperation=!1);break}case"COPY_PASTE_CELLS_ABOVE":{const e=this.getters.getSelectedZone(),t=e.top!==e.bottom,o={...e,bottom:t?e.top:e.top-1,top:t?e.top:e.top-1};this.originSheetId=this.getters.getActiveSheetId();const s=this.copy([o]);this.paste([e],s,{isCutOperation:!1,selectTarget:!0})}break;case"COPY_PASTE_CELLS_ON_LEFT":{const e=this.getters.getSelectedZone(),t=e.left!==e.right,o={...e,right:t?e.left:e.left-1,left:t?e.left:e.left-1};this.originSheetId=this.getters.getActiveSheetId();const s=this.copy([o]);this.paste([e],s,{isCutOperation:!1,selectTarget:!0})}break;case"CLEAN_CLIPBOARD_HIGHLIGHT":this.status="invisible";break;case"DELETE_CELL":{const{cut:t,paste:o}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!pr(t[0])){this.dispatch("CLEAR_CELLS",{target:[e.zone],sheetId:this.getters.getActiveSheetId()});break}const s=this.copy(t,"shiftCells");this.paste(o,s,{isCutOperation:!0});break}case"INSERT_CELL":{const{cut:t,paste:o}=this.getInsertCellsTargets(e.zone,e.shiftDimension),s=this.copy(t,"shiftCells");this.paste(o,s,{isCutOperation:!0});break}case"ADD_COLUMNS_ROWS":if(this.status="invisible",!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;this.isColRowDirtyingClipboard("before"===e.position?e.base:e.base+1,e.dimension)&&(this.copiedData=void 0);break;case"REMOVE_COLUMNS_ROWS":if(this.status="invisible",!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;for(const t of e.elements){if(this.isColRowDirtyingClipboard(t,e.dimension)){this.copiedData=void 0;break}}this.status="invisible";break;case"REPEAT_PASTE":this.paste(e.target,this.copiedData,{isCutOperation:!1,pasteOption:e.pasteOption,selectTarget:!0});break;case"DELETE_SHEET":if(!this._isCutOperation)return;this.originSheetId===e.sheetId&&(this.copiedData=void 0,this.status="invisible");break;default:Hs(e)&&(this.status="invisible")}}convertTextToClipboardData(e){const t=this.selectClipboardHandlers({figureId:!0}).concat(this.selectClipboardHandlers({})),o={};for(const{handlerName:s,handler:i}of t){const t=i.convertTextToClipboardData(e);o[s]=t;const n=["sheetId","cells","zones","figureId"];for(const e of n)t&&e in t&&(o[e]=t[e])}return o}selectClipboardHandlers(e){const t="figureId"in e?eh.figureHandlers:eh.cellHandlers;return t.getKeys().map((e=>({handlerName:e,handler:new(t.get(e))(this.getters,this.dispatch)})))}isCutAllowedOn(e){const t=this.getClipboardData(e);for(const{handler:e}of this.selectClipboardHandlers(t)){const o=e.isCutAllowed(t);if("Success"!==o)return o}return"Success"}isPasteAllowed(e,t,o){for(const{handler:s}of this.selectClipboardHandlers(t)){const i=s.isPasteAllowed(this.getters.getActiveSheetId(),e,t,{...o});if("Success"!==i)return i}return"Success"}isColRowDirtyingClipboard(e,t){if(!this.copiedData||!this.copiedData.zones)return!1;const{zones:o}=this.copiedData;for(const s of o){if("COL"===t&&e<=s.right)return!0;if("ROW"===t&&e<=s.bottom)return!0}return!1}copy(e,t="copyPaste"){const o={},s=this.getClipboardData(e);for(const{handlerName:e,handler:i}of this.selectClipboardHandlers(s)){const n=i.copy(s,this._isCutOperation,t);o[e]=n;const r=["sheetId","cells","zones","figureId"];for(const e of r)n&&e in n&&(o[e]=n[e])}return o}paste(e,t,o){if(!t)return;const s=this.getters.getActiveSheetId(),i=this.selectClipboardHandlers(t),{target:n,zone:r,selectedZones:a}=sl(s,e,t,i,o);void 0!==r&&this.addMissingDimensions(s,r.right-r.left+1,r.bottom-r.top+1,r.left,r.top),ol(i,t,n,o),o?.selectTarget&&il(this.selection,e,a)}addMissingDimensions(e,t,o,s,i){const n=o+i-this.getters.getNumberRows(e);n>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:this.getters.getNumberRows(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:n,position:"after"});const r=t+s-this.getters.getNumberCols(e);r>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:this.getters.getNumberCols(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:r,position:"after"})}getClipboardTextContent(){return this.getPlainTextContent()}getClipboardId(){return this.clipboardId}async getClipboardTextAndImageContent(){const e=await this.getImageContent(),t=e?.type,o={[Os.PlainText]:this.getPlainTextContent(),[Os.Html]:await this.getHTMLContent()};return t&&e&&(o[t]=e),o}getSheetData(){const e={version:hD(),clipboardId:this.clipboardId};return this.copiedData&&"figureId"in this.copiedData?e:{...e,...this.copiedData}}getPlainTextContent(){return this.copiedData?.cells&&this.copiedData.cells.map((e=>e.map((e=>this.getters.shouldShowFormulas()&&e?.tokens?.length?e?.content||"":e.evaluatedCell?.formattedValue||"")).join("\t"))).join("\n")||"\t"}async getHTMLContent(){let e="";const t=this.copiedData?.cells;if(t)if(1===t.length&&1===t[0].length)e=`${this.getters.getCellText(t[0][0].position)}`;else{if(!t[0][0])return"";{let o='<table border="1" style="border-collapse:collapse">';for(const e of t){o+="<tr>";for(const t of e){if(!t)continue;o+=`<td style="${xh(Ih(this.getters.getCellComputedStyle(t.position)))}">`+bx(this.getters.getCellText(t.position))+"</td>"}o+="</tr>"}o+="</table>",e=o}}else if(this.copiedData?.figureId){const t=this.copiedData.figureId,o=this.getters.getFigureSheetId(t);e="image"===this.getters.getFigure(o,t).tag?await this.craftImageHTML(t):"\t"}else e="\t";return`<div data-osheet-clipboard='${bx(JSON.stringify(this.getSheetData()))}'>${e}</div>`}readFileAsDataURL(e){return new Promise((t=>{const o=new FileReader;o.onload=()=>t(o.result),o.readAsDataURL(e)}))}async craftImageHTML(e){if(!this.fileStore)return"\t";const t=this.getters.getImage(e).path,o=await(this.fileStore?.getFile(t))||null;if(o){return`<img src="${bx(await this.readFileAsDataURL(o))}" />`}return"\t"}async getImageContent(){const e=this.copiedData?.figureId;if(!e)return;const t=this.getters.getFigureSheetId(e);let o;if("image"===this.getters.getFigure(t,e).tag){if(!this.fileStore)return;const t=this.getters.getImage(e).path;if(o=await(this.fileStore?.getFile(t)),"image/png"!==o.type){if(o.size>yL)return void this.ui.notifyUI({text:Ho("The file you are trying to copy is too large (>%sMB).\nIt will not be added to your OS clipboard.\nYou can download it directly instead.",Math.round(5)),sticky:!1,type:"warning"});o=await async function(e){return new Promise(((t,o)=>{const s=new Image;s.addEventListener("load",(()=>{const e=document.createElement("canvas");e.width=s.width,e.height=s.height;const o=e.getContext("2d");o?.drawImage(s,0,0),e.toBlob(t,"image/png")})),s.addEventListener("error",o),s.src=e}))}(t)}}return o?o instanceof File?o:new File([o],"image.png",{type:"image/png"}):void 0}isCutOperation(){return this._isCutOperation??!1}getDeleteCellsTargets(e,t){const o=this.getters.getActiveSheetId();let s;return s="COL"===t?{...e,left:e.right+1,right:this.getters.getNumberCols(o)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(o)-1},{cut:[s],paste:[e]}}getInsertCellsTargets(e,t){const o=this.getters.getActiveSheetId();let s,i;return"COL"===t?(s={...e,right:this.getters.getNumberCols(o)-1},i={...e,left:e.right+1,right:e.right+1}):(s={...e,bottom:this.getters.getNumberRows(o)-1},i={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(o)-1}),{cut:[s],paste:[i]}}getClipboardData(e){const t=this.getters.getActiveSheetId(),o=this.getters.getSelectedFigureId();if(o)return{figureId:o,sheetId:t};const s=Qa(t,e);return this._isCutOperation||(s.rowsIndexes=s.rowsIndexes.filter((e=>!this.getters.isRowFiltered(t,e)))),s}drawLayer(e){if("visible"!==this.status||!this.copiedData)return;const{sheetId:t,zones:o}=this.copiedData;if(t!==this.getters.getActiveSheetId()||!o||!o.length)return;const{ctx:s,thinLineWidth:i}=e;s.setLineDash([8,5]),s.strokeStyle=p,s.lineWidth=3.3*i;for(const e of o){const{x:t,y:o,width:i,height:n}=this.getters.getVisibleRect(e);i>0&&n>0&&s.strokeRect(t,o,i,n)}}}),TL=(new n).add("evaluation",class extends $k{static getters=["evaluateFormula","evaluateFormulaResult","evaluateCompiledFormula","getCorrespondingFormulaCell","getRangeFormattedValues","getRangeValues","getRangeFormats","getEvaluatedCell","getEvaluatedCells","getEvaluatedCellsInZone","getEvaluatedCellsPositions","getSpreadZone","getArrayFormulaSpreadingOn","isEmpty"];shouldRebuildDependenciesGraph=!0;evaluator;positionsToUpdate=[];constructor(e){super(e),this.evaluator=new yV(e.custom,this.getters)}beforeHandle(e){(Fs.has(e.type)||Ms.has(e.type))&&(this.shouldRebuildDependenciesGraph=!0)}handle(e){switch(e.type){case"UPDATE_CELL":if(!("content"in e)&&!("format"in e)||this.shouldRebuildDependenciesGraph)return;const t={sheetId:e.sheetId,row:e.row,col:e.col};this.positionsToUpdate.push(t),"content"in e&&this.evaluator.updateDependencies(t);break;case"EVALUATE_CELLS":this.evaluator.evaluateAllCells()}}finalize(){this.shouldRebuildDependenciesGraph?(this.evaluator.buildDependencyGraph(),this.evaluator.evaluateAllCells(),this.shouldRebuildDependenciesGraph=!1):this.positionsToUpdate.length&&this.evaluator.evaluateCells(this.positionsToUpdate),this.positionsToUpdate=[]}evaluateFormula(e,t){const o=this.evaluateFormulaResult(e,t);return js(o)?ki(o,(e=>e.value)):o.value}evaluateFormulaResult(e,t){return this.evaluator.evaluateFormulaResult(e,t)}evaluateCompiledFormula(e,t,o){return this.evaluator.evaluateCompiledFormula(e,t,o)}getRangeFormattedValues(e){return void 0===this.getters.tryGetSheet(e.sheetId)?[]:this.mapVisiblePositions(e,(e=>this.getters.getEvaluatedCell(e).formattedValue))}getRangeValues(e){return void 0===this.getters.tryGetSheet(e.sheetId)?[]:this.mapVisiblePositions(e,(e=>this.getters.getEvaluatedCell(e).value))}getRangeFormats(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map((e=>e.format))}getEvaluatedCell(e){return this.evaluator.getEvaluatedCell(e)}getEvaluatedCells(e){return this.evaluator.getEvaluatedPositionsInSheet(e).map((e=>this.getEvaluatedCell(e)))}getEvaluatedCellsPositions(e){return this.evaluator.getEvaluatedPositionsInSheet(e)}getEvaluatedCellsInZone(e,t){return _r(t).map((({col:t,row:o})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:o})))}getSpreadZone(e,t={ignoreSpillError:!1}){return this.evaluator.getSpreadZone(e,t)}getArrayFormulaSpreadingOn(e){return this.evaluator.getArrayFormulaSpreadingOn(e)}isEmpty(e,t){return _r(t).map((({col:t,row:o})=>this.getEvaluatedCell({sheetId:e,col:t,row:o}))).every((e=>e.type===_s.empty))}mapVisiblePositions(e,t){const{sheetId:o,zone:s}=e;return _r(s).reduce(((e,s)=>{const{col:i,row:n}=s;return this.getters.isColHidden(o,i)||this.getters.isRowHidden(o,n)||e.push(t({sheetId:o,...s})),e}),[])}exportForExcel(e){for(const t of e.sheets)t.cellValues={},t.formulaSpillRanges={};for(const t of this.evaluator.getEvaluatedPositions()){const o=this.evaluator.getEvaluatedCell(t),s=Po(t.col,t.row),i=o.value;let n,r=!1,a=!0;const l=e.sheets.find((e=>e.id===t.sheetId)),c=this.getCorrespondingFormulaCell(t);if(c){const h=this.getters.getCell(t);if(a=$S(c.compiledFormula.tokens),r=a&&h?.content===c.content,!a&&""!==i){n=(i??"").toString();const t=o.format;if(t){const o=Gr(t,e.formats);l.formats[s]=o}}}const h=l.cells[s];let d;d=a&&r&&c instanceof kk?c.contentWithFixedReferences:a?h:n,l.cells[s]=d,l.cellValues[s]="error"!==o.type?i:void 0;const u=this.getSpreadZone(t);u&&(l.formulaSpillRanges[s]=this.getters.getRangeString(this.getters.getRangeFromZone(t.sheetId,u),t.sheetId))}}getCorrespondingFormulaCell(e){const t=this.getters.getCell(e);if(t&&t.isFormula)return t.compiledFormula.isBadExpression?void 0:t;if(t&&t.content)return;const o=this.getArrayFormulaSpreadingOn(e);if(void 0===o)return;const s=this.getters.getCell(o);return s?.isFormula?s:void 0}}).add("evaluation_chart",class extends $k{static getters=["getChartRuntime","getStyleOfSingleCellChart"];charts={};createRuntimeChart=lx(this.getters);handle(e){if(Fs.has(e.type)||Ns.has(e.type)||Ps.has(e.type))for(const e in this.charts)this.charts[e]=void 0;switch(e.type){case"UPDATE_CHART":case"CREATE_CHART":case"DELETE_FIGURE":this.charts[e.figureId]=void 0;break;case"DELETE_SHEET":for(const e in this.charts)this.getters.isChartDefined(e)||(this.charts[e]=void 0)}}getChartRuntime(e){if(!this.charts[e]){const t=this.getters.getChart(e);if(!t)throw new Error(`No chart for the given id: ${e}`);this.charts[e]=this.createRuntimeChart(t)}return this.charts[e]}getStyleOfSingleCellChart(e,t){if(e)return{background:e,fontColor:rC(e)};if(!t)return{background:m,fontColor:rC(m)};const o=t.zone.left,s=t.zone.top,i=t.sheetId,n=this.getters.getCellComputedStyle({sheetId:i,col:o,row:s}),r=n.fillColor||m;return{background:r,fontColor:n.textColor||rC(r)}}exportForExcel(e){for(const t of e.sheets){t.images||(t.images=[]);const e=this.getters.getFigures(t.id),o=[];for(const s of e){if(!s||"chart"!==s.tag)continue;const e=s.id,i=this.getters.getChart(e)?.getDefinitionForExcel();if(i)o.push({...s,data:i});else{if(!this.getters.getChart(e))continue;const o=this.getters.getChartType(e),i=Wy(this.getters.getChartRuntime(e),s,o);i&&t.images.push({...s,tag:"image",data:{mimetype:"image/png",path:i,size:{width:s.width,height:s.height}}})}}t.charts=o}}}).add("evaluation_cf",class extends $k{static getters=["getConditionalIcon","getCellConditionalFormatStyle","getConditionalDataBar"];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(Fs.has(e.type)||Ns.has(e.type)||"UPDATE_CELL"===e.type&&("content"in e||"format"in e))&&(this.isStale=!0)}finalize(){if(this.isStale){for(const e of this.getters.getSheetIds())this.computedStyles[e]=ut((()=>this.getComputedStyles(e))),this.computedIcons[e]=ut((()=>this.getComputedIcons(e))),this.computedDataBars[e]=ut((()=>this.getComputedDataBars(e)));this.isStale=!1}}getCellConditionalFormatStyle(e){const{sheetId:t,col:o,row:s}=e,i=this.computedStyles[t]();return i&&i[o]?.[s]}getConditionalIcon({sheetId:e,col:t,row:o}){const s=this.computedIcons[e]();return s&&s[t]?.[o]}getConditionalDataBar({sheetId:e,col:t,row:o}){const s=this.computedDataBars[e]();return s&&s[t]?.[o]}getComputedStyles(e){const t={};for(const o of this.getters.getConditionalFormats(e).reverse())switch(o.rule.type){case"ColorScaleRule":for(const s of o.ranges)this.applyColorScale(e,s,o.rule,t);break;case"CellIsRule":const s=o.rule.values.map((e=>e.startsWith("=")?HS(e):void 0));for(const i of o.ranges){const n=this.getters.getRangeFromSheetXC(e,i).zone;for(let i=n.top;i<=n.bottom;i++)for(let r=n.left;r<=n.right;r++){const a={sheetId:e,col:r,row:i},l=o.rule.values.map(((t,o)=>{const a=s[o];return a?this.getters.getTranslatedCellFormula(e,r-n.left,i-n.top,a.tokens):t}));this.getRuleResultForTarget(a,{...o.rule,values:l})&&(t[r]||(t[r]=[]),t[r][i]=Object.assign(t[r]?.[i]||{},o.rule.style))}}}return t}getComputedIcons(e){const t={};for(const o of this.getters.getConditionalFormats(e).reverse())if("IconSetRule"===o.rule.type)for(const s of o.ranges)this.applyIcon(e,s,o.rule,t);return t}getComputedDataBars(e){const t={};for(const o of this.getters.getConditionalFormats(e).reverse())if("DataBarRule"===o.rule.type)for(const s of o.ranges)this.applyDataBar(e,s,o.rule,t);return t}parsePoint(e,t,o,s){const i=this.getters.getEvaluatedCellsInZone(e,this.getters.getRangeFromSheetXC(e,t).zone).filter((e=>e.type===_s.number)).map((e=>e.value));switch(o.type){case"value":return"max"===s?Ft(i):Pt(i);case"number":return Number(o.value);case"percentage":const t=Pt(i);return t+(Ft(i)-t)*Number(o.value)/100;case"percentile":return Ds(i,Number(o.value)/100,!0);case"formula":const n=o.value&&this.getters.evaluateFormula(e,o.value);return"number"==typeof n?n:null;default:return null}}applyIcon(e,t,o,s){const i=this.parsePoint(e,t,o.lowerInflectionPoint),n=this.parsePoint(e,t,o.upperInflectionPoint);if(null===i||null===n||i>n)return;const r=this.getters.getRangeFromSheetXC(e,t).zone,a=[o.icons.upper,o.icons.middle,o.icons.lower];for(let t=r.top;t<=r.bottom;t++)for(let l=r.left;l<=r.right;l++){const r=this.getters.getEvaluatedCell({sheetId:e,col:l,row:t});if(r.type!==_s.number)continue;const c=this.computeIcon(r.value,n,o.upperInflectionPoint.operator,i,o.lowerInflectionPoint.operator,a);s[l]||(s[l]=[]),s[l][t]=c}}computeIcon(e,t,o,s,i,n){return"ge"===o&&e>=t||"gt"===o&&e>t?n[0]:"ge"===i&&e>=s||"gt"===i&&e>s?n[1]:n[2]}applyDataBar(e,t,o,s){const i=this.getters.getRangeFromSheetXC(e,o.rangeValues||t),n=Ft(this.getters.getEvaluatedCellsInZone(e,i.zone).filter((e=>e.type===_s.number)).map((e=>e.value)));if(n<=0)return;const r=o.color,a=this.getters.getRangeFromSheetXC(e,t).zone,l=i.zone;for(let t=a.top;t<=a.bottom;t++)for(let o=a.left;o<=a.right;o++){const i=o-a.left+l.left,c=t-a.top+l.top,h=this.getters.getEvaluatedCell({sheetId:e,col:i,row:c});!Er(i,c,l)||h.type!==_s.number||h.value<=0||(s[o]||(s[o]=[]),s[o][t]={color:zt(r),percentage:100*h.value/n})}}applyColorScale(e,t,o,s){const i=this.parsePoint(e,t,o.minimum,"min"),n=o.midpoint?this.parsePoint(e,t,o.midpoint):null,r=this.parsePoint(e,t,o.maximum,"max");if(null===i||null===r||i>=r||n&&(i>=n||n>=r))return;const a=this.getters.getRangeFromSheetXC(e,t).zone,l=[{value:i,color:o.minimum.color}];o.midpoint&&n&&l.push({value:n,color:o.midpoint.color}),l.push({value:r,color:o.maximum.color});const c=So(l);for(let t=a.top;t<=a.bottom;t++)for(let o=a.left;o<=a.right;o++){const n=this.getters.getEvaluatedCell({sheetId:e,col:o,row:t});if(n.type===_s.number){const e=Ze(n.value,i,r);s[o]||(s[o]=[]),s[o][t]=s[o]?.[t]||{},s[o][t].fillColor=c(e)}}}getRuleResultForTarget(e,t){const o=this.getters.getEvaluatedCell(e);if(o.type===_s.error)return!1;const{sheetId:s}=e,i=eE.get(t.operator),n=t.values.map((e=>e.startsWith("=")?this.getters.evaluateFormula(s,e)??"":Kn(e,qs)));if(n.some(oc))return!1;const r={type:t.operator,values:n.map(ec)};return i.isValueValid(o.value??"",r,this.getters,s)}}).add("row_size",class extends $k{static getters=["getRowSize","getHeaderSize","getMaxAnchorOffset"];tallestCellInRow={};ctx=document.createElement("canvas").getContext("2d");beforeHandle(e){if("ADD_COLUMNS_ROWS"===e.type){if("COL"===e.dimension)return;const t=pt(e.position,e.base),o=Array(e.quantity).fill(void 0),s=Tt(this.tallestCellInRow[e.sheetId],o,t);this.history.update("tallestCellInRow",e.sheetId,s)}}handle(e){switch(e.type){case"START":for(const e of this.getters.getSheetIds())this.initializeSheet(e);break;case"CREATE_SHEET":this.initializeSheet(e.sheetId);break;case"DUPLICATE_SHEET":{const t=ze(this.tallestCellInRow[e.sheetId]);this.history.update("tallestCellInRow",e.sheetIdTo,t);break}case"DELETE_SHEET":const t={...this.tallestCellInRow};delete t[e.sheetId],this.history.update("tallestCellInRow",t);break;case"REMOVE_COLUMNS_ROWS":{if("COL"===e.dimension)return;const t=Rt(this.tallestCellInRow[e.sheetId],e.elements);this.history.update("tallestCellInRow",e.sheetId,t);break}case"RESIZE_COLUMNS_ROWS":{const t=e.sheetId;if("ROW"===e.dimension)for(const o of e.elements){const e=this.getRowTallestCell(t,o);this.history.update("tallestCellInRow",t,o,e)}else for(const o of je(0,this.getters.getNumberRows(t)))for(const s of e.elements)this.updateRowSizeForCellChange(t,o,s)}break;case"UPDATE_CELL":this.updateRowSizeForCellChange(e.sheetId,e.row,e.col);break;case"ADD_MERGE":case"REMOVE_MERGE":for(const t of e.target)for(const o of _r(t))this.updateRowSizeForCellChange(e.sheetId,o.row,o.col)}}getRowSize(e,t){return Math.round(this.getters.getUserRowSize(e,t)??this.tallestCellInRow[e][t]?.size??ie)}getMaxAnchorOffset(e,t,o){let{numberOfRows:s,numberOfCols:i}=this.getters.getSheetSize(e),n=0;for(;n<t&&s>0;s--)n+=this.getRowSize(e,s-1);let r=0;for(;r<o&&i>0;i--)r+=this.getters.getColSize(e,i-1);return{col:i,row:s,offset:{x:r-o,y:n-t}}}getHeaderSize(e,t,o){return this.getters.isHeaderHidden(e,t,o)?0:"ROW"===t?this.getRowSize(e,o):this.getters.getColSize(e,o)}updateRowSizeForCellChange(e,t,o){const s=this.tallestCellInRow[e]?.[t];if(s?.cell.col===o){const o=this.getRowTallestCell(e,t);this.history.update("tallestCellInRow",e,t,o)}const i=this.getCellHeight({sheetId:e,col:o,row:t});if(!(i<=ie)&&(!s&&i>ie||s&&i>s.size)){const s={cell:{sheetId:e,col:o,row:t},size:i};this.history.update("tallestCellInRow",e,t,s)}}initializeSheet(e){const t=[];for(let o=0;o<this.getters.getNumberRows(e);o++){const s=this.getRowTallestCell(e,o);t.push(s)}this.history.update("tallestCellInRow",e,t)}getCellHeight(e){if(this.isInMultiRowMerge(e))return ie;const t=this.getters.getCell(e),o=this.getters.getColSize(e.sheetId,e.col);return function(e,t,o){return t&&(t.isFormula||t.content)?Ma(e,t.isFormula?"":t.content,t.style,o):ie}(this.ctx,t,o)}isInMultiRowMerge(e){const t=this.getters.getMerge(e);return!!t&&t.bottom!==t.top}getRowTallestCell(e,t){if(void 0!==this.getters.getUserRowSize(e,t))return;const o=this.getters.getRowCells(e,t);let s,i=0;for(let e=0;e<o.length;e++){const t=this.getters.getCellById(o[e]);if(!t)continue;const n=this.getters.getCellPosition(t.id),r=this.getCellHeight(n);r>i&&r>ie&&(i=r,s={cell:n,size:r})}return s&&s.size>ie?s:void 0}}).add("data_validation_ui",class extends $k{static getters=["getDataValidationInvalidCriterionValueMessage","getInvalidDataValidationMessage","getValidationResultForCellValue","getDataValidationRangeValues","isCellValidCheckbox","getDataValidationCellStyle","getDataValidationChipStyle","isDataValidationInvalid"];validationResults={};handle(e){if(Fs.has(e.type)||"EVALUATE_CELLS"===e.type||"UPDATE_CELL"===e.type&&("content"in e||"format"in e))this.validationResults={};else switch(e.type){case"ADD_DATA_VALIDATION_RULE":case"REMOVE_DATA_VALIDATION_RULE":delete this.validationResults[e.sheetId]}}isDataValidationInvalid(e){return!this.getValidationResultForCell(e).isValid}getDataValidationCellStyle(e){if(!this.hasChip(e))return this.getDataValidationStyle(e)}getDataValidationChipStyle(e){if(this.hasChip(e))return this.getDataValidationStyle(e)??{fillColor:F}}getInvalidDataValidationMessage(e){const t=this.getValidationResultForCell(e);return t.isValid?void 0:t.error}getDataValidationInvalidCriterionValueMessage(e,t){const o=eE.get(e);return t.startsWith("=")?"onlyLiterals"===o.allowedValues?Ho("The value must not be a formula"):this.isValidFormula(t)?void 0:tw.CriterionError.validFormula:"onlyFormulas"===o.allowedValues?Ho("The value must be a formula"):o.isCriterionValueValid(t)?void 0:o.criterionValueErrorString}getDataValidationRangeValues(e,t){const o=this.getters.getRangeFromSheetXC(e,String(t.values[0])),s=[],i=new Set;for(const e of _r(o.zone)){const t=this.getters.getEvaluatedCell({...e,sheetId:o.sheetId});t.formattedValue&&!i.has(t.formattedValue)&&(i.add(t.formattedValue),s.push({label:t.formattedValue,value:t.value?.toString()||""}))}return s}isCellValidCheckbox(e){if(!this.getters.isMainCellPosition(e))return!1;const t=this.getters.getValidationRuleForCell(e);return!(!t||"isBoolean"!==t.criterion.type)&&this.getValidationResultForCell(e).isValid}getValidationResultForCellValue(e,t){const o=this.getters.getValidationRuleForCell(t);if(!o)return RV;const s=this.getRuleErrorForCellValue(e,t,o);return s?{error:s,rule:o,isValid:!1}:RV}hasChip(e){const t=this.getters.getValidationRuleForCell(e);return("isValueInList"===t?.criterion.type||"isValueInRange"===t?.criterion.type)&&"chip"===t.criterion.displayStyle}getDataValidationStyle(e){const t=this.getters.getValidationRuleForCell(e);if(!t||this.isDataValidationInvalid(e))return;const o=this.getters.getEvaluatedCell(e),s=this.getValueColor(t,o.value);if(!s)return;return{fillColor:s,textColor:no(s)}}getValueColor(e,t){if("isValueInList"===e.criterion.type||"isValueInRange"===e.criterion.type)for(const o in e.criterion.colors)if(o.toLowerCase()===String(t).toLowerCase())return e.criterion.colors[o]}isValidFormula(e){return!HS(e).isBadExpression}getValidationResultForCell(e){const{col:t,row:o,sheetId:s}=e;return this.validationResults[s]||(this.validationResults[s]=this.computeSheetValidationResults(s)),this.validationResults[s][t]?.[o]?.()||RV}computeSheetValidationResults(e){const t={},o=this.getters.getDataValidationRules(e).map((e=>e.ranges));for(const e of wa(o.flat())){const{col:o,row:s}=e;t[o]||(t[o]=[]),t[o][s]=ut((()=>{const t=this.getters.getEvaluatedCell(e);return t.type===_s.empty?RV:this.getValidationResultForCellValue(t.value,e)}))}return t}getRuleErrorForCellValue(e,t,o){const{sheetId:s}=t,i=o.criterion,n=eE.get(i.type),r=this.getCellOffsetInRule(t,o),a=this.getEvaluatedCriterionValues(s,r,i);if(a.some(oc))return;const l={...i,values:a.map(ec)};return n.isValueValid(e,l,this.getters,s)?void 0:n.getErrorString(l,this.getters,s)}getCellOffsetInRule(e,t){const o=t.ranges.find((t=>Er(e.col,e.row,t.zone)));if(!o)throw new Error("The cell is not in any range of the rule");return{col:e.col-o.zone.left,row:e.row-o.zone.top}}getEvaluatedCriterionValues(e,t,o){return o.values.map((o=>{if(!o.startsWith("="))return Kn(o,qs);const s=HS(o),i=this.getters.getTranslatedCellFormula(e,t.col,t.row,s.tokens);return this.getters.evaluateFormula(e,i)}))}}).add("dynamic_tables",class extends $k{static getters=["canCreateDynamicTableOnZones","doesZonesContainFilter","getFilter","getFilters","getTable","getTables","getTablesOverlappingZones","getFilterId","getFilterHeaders","isFilterHeader"];tables={};handle(e){if(Fs.has(e.type)||"UPDATE_CELL"===e.type&&("content"in e||"format"in e)||"EVALUATE_CELLS"===e.type)this.tables={};else switch(e.type){case"CREATE_TABLE":case"REMOVE_TABLE":case"UPDATE_TABLE":case"DELETE_CONTENT":this.tables={}}}finalize(){for(const e of this.getters.getSheetIds())this.tables[e]||(this.tables[e]=this.computeTables(e))}computeTables(e){const t=[],o=this.getters.getCoreTables(e);for(const e of o)"dynamic"!==e.type&&t.push(e);const s=[...t];for(const i of o){if("dynamic"!==i.type)continue;const o=this.coreTableToTable(e,i);let n=o.range.zone;for(const e of s)xr(n,e.range.zone)&&(n={...n,right:e.range.zone.left-1});t.push({...o,range:this.getters.getRangeFromZone(e,n)})}return t}getFilters(e){return this.getTables(e).filter((e=>e.config.hasFilters)).map((e=>e.filters)).flat()}getTables(e){return this.tables[e]||[]}getFilter(e){const t=this.getTable(e);if(t&&t.config.hasFilters)return t.filters.find((t=>t.col===e.col))}getFilterId(e){return this.getFilter(e)?.id}getTable({sheetId:e,col:t,row:o}){return this.getTables(e).find((e=>Er(t,o,e.range.zone)))}getTablesOverlappingZones(e,t){return this.getTables(e).filter((e=>t.some((t=>xr(e.range.zone,t)))))}doesZonesContainFilter(e,t){return this.getTablesOverlappingZones(e,t).some((e=>e.config.hasFilters))}getFilterHeaders(e){const t=[];for(const o of this.getTables(e)){if(!o.config.hasFilters)continue;const s=o.range.zone,i=s.top;for(let o=s.left;o<=s.right;o++)t.push({sheetId:e,col:o,row:i})}return t}isFilterHeader({sheetId:e,col:t,row:o}){return this.getFilterHeaders(e).some((e=>e.col===t&&e.row===o))}canCreateDynamicTableOnZones(e,t){if(!Ur(t))return!1;const o=yr(...t),s={col:o.left,row:o.top,sheetId:e},i=this.getters.getArrayFormulaSpreadingOn(s);if(!i)return!1;if(mt(i,s)&&1===Lr(o))return!0;return mt(o,this.getters.getSpreadZone(i))}coreTableToTable(e,t){if("dynamic"!==t.type)return t;const o=t.range.zone,s={sheetId:e,col:o.left,row:o.top},i=this.getters.getSpreadZone(s)??t.range.zone,n=this.getters.getRangeFromZone(e,i),r=this.getDynamicTableFilters(e,t,i);return{id:t.id,range:n,filters:r,config:t.config}}getDynamicTableFilters(e,t,o){const s=[],{top:i,bottom:n,left:r,right:a}=o;for(let o=r;o<=a;o++){const a=o-r,l={left:o,right:o,top:i,bottom:n},c=C_(this.getDynamicTableFilterId(t.id,a),this.getters.getRangeFromZone(e,l),t.config,this.getters.getRangeFromZone);s.push(c)}return s}getDynamicTableFilterId(e,t){return e+"_"+t}exportForExcel(e){for(const t of e.sheets)for(const e of t.tables){const o=ur(e.range),s={sheetId:t.id,col:o.left,row:o.top},i=this.getters.getCoreTable(s),n=this.getTable(s);"dynamic"===i?.type&&n&&(e.range=fr(n.range.zone))}}}).add("custom_colors",class extends $k{customColors={};shouldUpdateColors=!0;static getters=["getCustomColors"];constructor(e){super(e),this.tryToAddColors(e.customColors??[])}handle(e){switch(e.type){case"START":for(const e of this.getters.getSheetIds())for(const t of this.getters.getChartIds(e))this.tryToAddColors(this.getChartColors(t));break;case"UPDATE_CHART":case"CREATE_CHART":this.tryToAddColors(this.getChartColors(e.figureId));break;case"UPDATE_CELL":case"ADD_CONDITIONAL_FORMAT":case"SET_BORDER":case"SET_ZONE_BORDERS":case"SET_FORMATTING":case"CREATE_TABLE":case"UPDATE_TABLE":this.history.update("shouldUpdateColors",!0)}}finalize(){this.shouldUpdateColors&&(this.history.update("shouldUpdateColors",!1),this.tryToAddColors(this.computeCustomColors()))}getCustomColors(){return function(e){const t=[{leadColor:Zt(255,0,0),colors:[]},{leadColor:Zt(255,128,0),colors:[]},{leadColor:Zt(128,128,0),colors:[]},{leadColor:Zt(128,255,0),colors:[]},{leadColor:Zt(0,255,0),colors:[]},{leadColor:Zt(0,255,128),colors:[]},{leadColor:Zt(0,255,255),colors:[]},{leadColor:Zt(0,127,255),colors:[]},{leadColor:Zt(0,0,255),colors:[]},{leadColor:Zt(127,0,255),colors:[]},{leadColor:Zt(128,0,128),colors:[]},{leadColor:Zt(255,0,128),colors:[]}];for(const o of e.map(Xt)){let e=500,s=0;t.forEach(((t,i)=>{const n=(r=o,a=t.leadColor,Math.sqrt(Math.pow(r.r-a.r,2)+Math.pow(r.g-a.g,2)+Math.pow(r.b-a.b,2)));var r,a;e>n&&(e=n,s=i)})),t[s].colors.push(o)}return t.map((e=>e.colors.sort(((e,t)=>Jt(e).s-Jt(t).s)))).flat().map(Yt)}(Object.keys(this.customColors))}computeCustomColors(){let e=[];for(const t of this.getters.getSheetIds())e=e.concat(this.getColorsFromCells(t),this.getFormattingColors(t),this.getTableColors(t));return[...new Set([...e])]}getColorsFromCells(e){const t=Object.values(this.getters.getCells(e)),o=new Set;for(const e of t)e.style?.textColor&&o.add(e.style.textColor),e.style?.fillColor&&o.add(e.style.fillColor);for(const t of this.getters.getBordersColors(e))o.add(t);return[...o]}getFormattingColors(e){const t=this.getters.getConditionalFormats(e),o=[];for(const e of t){const t=e.rule;"CellIsRule"===t.type?(o.push(t.style.textColor),o.push(t.style.fillColor)):"ColorScaleRule"===t.type&&(o.push(zt(t.minimum.color)),o.push(t.midpoint?zt(t.midpoint.color):void 0),o.push(zt(t.maximum.color)))}return o.filter(lt)}getChartColors(e){const t=this.getters.getChart(e);if(void 0===t)return[];return[...JSON.stringify(t.getDefinition()).matchAll(EV)].map((e=>e[1]))}getTableColors(e){return this.getters.getTables(e).flatMap((e=>{const t=e.config,o=this.getters.getTableStyle(t.styleId);return[this.getTableStyleElementColors(o.wholeTable),t.numberOfHeaders>0?this.getTableStyleElementColors(o.headerRow):[],t.totalRow?this.getTableStyleElementColors(o.totalRow):[],t.bandedColumns?this.getTableStyleElementColors(o.firstColumnStripe):[],t.bandedColumns?this.getTableStyleElementColors(o.secondColumnStripe):[],t.bandedRows?this.getTableStyleElementColors(o.firstRowStripe):[],t.bandedRows?this.getTableStyleElementColors(o.secondRowStripe):[],t.firstColumn?this.getTableStyleElementColors(o.firstColumn):[],t.lastColumn?this.getTableStyleElementColors(o.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(lt):[]}tryToAddColors(e){for(const t of e){if(!Wt(t))continue;const e=Gt(t);t&&!ee.includes(e)&&this.history.update("customColors",e,!0)}}}).add("pivot_ui",class extends $k{static getters=["getPivot","getFirstPivotFunction","getPivotIdFromPosition","getPivotCellFromPosition","generateNewCalculatedMeasureName","isPivotUnused","isSpillPivotFormula"];pivots={};unusedPivots;custom;constructor(e){super(e),this.custom=e.custom}beforeHandle(e){if("START"===e.type)for(const e of this.getters.getPivotIds())this.setupPivot(e)}handle(e){if(Fs.has(e.type))for(const e of this.getters.getPivotIds())ik.get(this.getters.getPivotCoreDefinition(e).type).externalData||this.setupPivot(e,{recreate:!0});switch(e.type){case"REFRESH_PIVOT":this.refreshPivot(e.id);break;case"ADD_PIVOT":this.setupPivot(e.pivotId);break;case"DUPLICATE_PIVOT":this.setupPivot(e.newPivotId);break;case"UPDATE_PIVOT":this.setupPivot(e.pivotId,{recreate:!0});break;case"DELETE_SHEET":case"UPDATE_CELL":this.unusedPivots=void 0;break;case"UNDO":case"REDO":{this.unusedPivots=void 0;const t=e.commands.filter(FV);for(const e of t){const t=e.pivotId;this.getters.isExistingPivot(t)&&this.setupPivot(t,{recreate:!0})}break}case"UPDATE_LOCALE":!function(){for(const e in ok)ok[e].set.clear(),ok[e].values={}}()}}getPivotIdFromPosition(e){const t=this.getters.getCorrespondingFormulaCell(e);if(t&&t.isFormula){const o=this.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(o){const e=o.args[0]?.toString();return e&&this.getters.getPivotId(e)}}}isSpillPivotFormula(e){const t=this.getters.getCorrespondingFormulaCell(e);if(t&&t.isFormula){const o=this.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);return"PIVOT"===o?.functionName}return!1}getFirstPivotFunction(e,t){const o=BN(t);if(!o)return;const{functionName:s,args:i}=o;return{functionName:s,args:i.map((t=>{if("EMPTY"===t.type)return;if("STRING"===t.type||"BOOLEAN"===t.type||"NUMBER"===t.type)return t.value;const o=gv(t);return this.getters.evaluateFormula(e,o)}))}}getPivotCellFromPosition(e){const t=this.getters.getCorrespondingFormulaCell(e);if(!t||!t.isFormula||0===zN(t.compiledFormula.tokens))return ZN;const o=this.getters.getCellPosition(t.id),s=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(!s)return ZN;let{functionName:i,args:n}=s;const r=n[0];if(!r)return ZN;const a=this.getters.getPivotId(r.toString());if(!a)return ZN;const l=this.getPivot(a);if(!l.isValid())return ZN;if("PIVOT"===i&&!t.content.replaceAll(" ","").toUpperCase().startsWith("=PIVOT"))return ZN;if("PIVOT"===i){const t=ec(n[2]),s=void 0===t||Ei(t),i=ec(n[3]),r=ec(n[5]),a=void 0===r||Ei(r),c={displayColumnHeaders:void 0===i||Ei(i),displayTotals:s,displayMeasuresRow:a},h=l.getCollapsedTableStructure().getPivotCells(c),d=e.col-o.col,u=e.row-o.row;return h[d][u]}try{const t=e.row-o.row,s=e.col-o.col;if(n=n.map((e=>js(e)?e[s][t]:e)),"PIVOT.HEADER"===i&&"measure"===n.at(-2)){return{type:"MEASURE_HEADER",domain:l.parseArgsToPivotDomain(n.slice(1,-2).map((e=>({value:e})))),measure:n.at(-1)?.toString()||""}}if("PIVOT.HEADER"===i){const e=l.parseArgsToPivotDomain(n.slice(1).map((e=>({value:e}))));return{type:"HEADER",domain:e,dimension:NO(l,e).colDomain.length?"COL":"ROW"}}const[r,...a]=n.slice(1);return{type:"VALUE",domain:l.parseArgsToPivotDomain(a.map((e=>({value:e})))),measure:r?.toString()||""}}catch(e){return ZN}}generateNewCalculatedMeasureName(e){const t=e.map((e=>e.fieldName));return Vt(Ho("Calculated measure 1"),t,{compute:(e,t)=>Ho("Calculated measure %s",t)})}getPivot(e){if(!this.getters.isExistingPivot(e))throw new Error(`pivot ${e} not found`);return this.pivots[e]}isPivotUnused(e){return this._getUnusedPivots().includes(e)}refreshPivot(e){this.getters.getPivot(e).init({reload:!0})}setupPivot(e,{recreate:t}={recreate:!1}){const o=this.getters.getPivotCoreDefinition(e);if(e in this.pivots)t&&this.pivots[e].onDefinitionChange(o);else{const t=_V(ik.get(o.type).ui);this.pivots[e]=new t(this.custom,{definition:o,getters:this.getters})}}_getUnusedPivots(){if(void 0!==this.unusedPivots)return this.unusedPivots;const e=new Set(this.getters.getPivotIds());for(const t of this.getters.getSheetIds())for(const o in this.getters.getCells(t)){const t=this.getters.getCellPosition(o),s=this.getPivotIdFromPosition(t);if(s&&(e.delete(s),!e.size))return this.unusedPivots=[],[]}return this.unusedPivots=[...e],this.unusedPivots}}).add("cell_icon",class extends $k{static getters=["doesCellHaveGridIcon","getCellIcons","getCellIconRect"];cellIconsCache={};handle(e){"SET_VIEWPORT_OFFSET"!==e.type&&(this.cellIconsCache={})}getCellIcons(e){return this.cellIconsCache[e.sheetId]||(this.cellIconsCache[e.sheetId]={}),this.cellIconsCache[e.sheetId][e.col]||(this.cellIconsCache[e.sheetId][e.col]={}),this.cellIconsCache[e.sheetId][e.col][e.row]||(this.cellIconsCache[e.sheetId][e.col][e.row]=this.computeCellIcons(e)),this.cellIconsCache[e.sheetId][e.col][e.row]}getCellIconRect(e,t){const o=e.position,s=this.getters.getCell(o);return{x:this.getIconHorizontalPosition(t,e.horizontalAlign,e),y:this.getters.computeTextYCoordinate(t,e.size,s?.style?.verticalAlign),width:e.size,height:e.size}}getIconHorizontalPosition(e,t,o){const s=e.x,i=e.x+e.width;switch(t){case"right":return i-o.margin-o.size;case"left":return s+o.margin;default:const e=Math.floor((i-s-o.size)/2);return i-o.size-e}}computeCellIcons(e){const t={left:void 0,right:void 0,center:void 0},o=TV.getAll();for(const s of o){const o=s(this.getters,e);o&&(!t[o.horizontalAlign]||o.priority>t[o.horizontalAlign].priority)&&(t[o.horizontalAlign]=o)}if(t.center&&(t.left||t.right)){const e=Math.max(t.left?.priority||0,t.right?.priority||0);t.center.priority<e?t.center=void 0:(t.left=void 0,t.right=void 0)}return Object.values(t).filter(lt)}doesCellHaveGridIcon(e){return Boolean(this.getCellIcons(e).length)}});mE.add("dataValidation",{displayAllOnInitialContent:!0,canBeToggled:!1,getProposals(e,t){if(Lt(t))return[];if(!this.composer.currentEditedCell)return[];const o=this.composer.currentEditedCell,s=this.getters.getValidationRuleForCell(o);if(!s||"isValueInList"!==s.criterion.type&&"isValueInRange"!==s.criterion.type)return[];const i=this.composer.currentEditedCell.sheetId,n="isValueInRange"===s.criterion.type?this.getters.getDataValidationRangeValues(i,s.criterion):s.criterion.values.map((e=>({label:e,value:e})));if(!("chip"===s.criterion.displayStyle))return n.map((e=>({text:e.value,fuzzySearchKey:e.label,htmlContent:[{value:e.label}]})));const r=s.criterion.colors;return n.map((e=>{const t=r?.[e.value];return{text:e.value,htmlContent:[{value:e.label,color:t?no(t):void 0,backgroundColor:t||F,classes:["badge rounded-pill fs-6 fw-normal w-100 mt-1 text-start"]}],fuzzySearchKey:e.label}}))},selectProposal(e,t){this.composer.setCurrentContent(t),this.composer.stopEdition()}}),mE.add("functions",{sequence:100,autoSelectFirstProposal:!0,maxDisplayedProposals:10,getProposals(e){if("SYMBOL"!==e.type)return[];const t=e.value;if(!Lt(this.composer.currentContent))return[];const o=Object.entries(RS.content).filter((([e,{hidden:t}])=>!t)).map((([e,{description:o}])=>({text:e,description:o,htmlContent:EN(t,e,E,"o-semi-bold")}))).sort(((e,t)=>e.text.length-t.text.length||e.text.localeCompare(t.text)));return o},selectProposal(e,t){let o=e.end,s=e.end;["SYMBOL","FUNCTION"].includes(e.type)&&(o=e.start);const i=this.composer.currentTokens;t+="(";const n=i.map((e=>e.start)).indexOf(e.start);if(n+1<i.length){const e=i[n+1];"LEFT_PAREN"===e?.type&&s++}this.composer.changeComposerCursorSelection(o,s),this.composer.replaceComposerCursorSelection(t)}}),mE.add("pivot_ids",{sequence:50,autoSelectFirstProposal:!0,getProposals(e){const t=e.functionContext;if(!t||!["PIVOT.VALUE","PIVOT.HEADER","PIVOT"].includes(t.parent.toUpperCase())||0!==t.argPosition)return;const o=this.getters.getPivotIds();return o.includes(e.value)?void 0:o.map((e=>{const t=this.getters.getPivotCoreDefinition(e),o=`${this.getters.getPivotFormulaId(e)}`;return{text:o,description:t.name,htmlContent:[{value:o,color:wE.NUMBER}],fuzzySearchKey:o+t.name,alwaysExpanded:!0}})).filter(lt)},selectProposal:HN}),mE.add("pivot_measures",{sequence:50,autoSelectFirstProposal:!0,getProposals(e){const t=e.functionContext;if("PIVOT.VALUE"!==t?.parent.toUpperCase()||1!==t.argPosition)return[];const o=UN(e),s=this.getters.getPivotId(o);if(!s||!this.getters.isExistingPivot(s))return[];const i=this.getters.getPivot(s);return i.init(),i.isValid()?i.definition.measures.map((e=>{if("__count"===e.fieldName){const e='"__count"';return{text:e,description:Ho("Count"),htmlContent:[{value:e,color:wE.STRING}],fuzzySearchKey:Ho("Count")+e}}return function(e){const t=`"${e.id}"`,o=e.displayName+e.fieldName+t;return{text:t,description:e.displayName,htmlContent:[{value:t,color:wE.STRING}],fuzzySearchKey:o}}(e)})).filter(lt):[]},selectProposal:LN}),mE.add("pivot_group_fields",{sequence:50,autoSelectFirstProposal:!0,getProposals(e){const t=e.functionContext;if(!t||!function(e){const t=e.functionContext;return"PIVOT.VALUE"===t?.parent.toUpperCase()&&t.argPosition>=2&&t.argPosition%2==0}(e)&&!function(e){const t=e.functionContext;return"PIVOT.HEADER"===t?.parent.toUpperCase()&&t.argPosition>=1&&t.argPosition%2==1}(e))return;const o=UN(e),s=this.getters.getPivotId(o);if(!s||!this.getters.isExistingPivot(s))return;const i=this.getters.getPivot(s);i.init();const n=i.getFields(),{columns:r,rows:a}=i.definition;let l=t.args;"PIVOT.VALUE"===t?.parent.toUpperCase()?(l=l.filter(((e,t)=>t%2==0)),l=l.slice(1,t.argPosition)):l=l.filter(((e,t)=>t%2==1));const c=l.map((e=>e?.value)).filter(lt),h=r.map((e=>e.nameWithGranularity)),d=a.map((e=>e.nameWithGranularity)),u=[];let g=["ARG_SEPARATOR","SPACE"].includes(e.type)?c.at(-1):c.at(-2);const p=Ok.get(i.type);if(p&&g?.startsWith("#")&&(g=g.slice(1)),void 0===g&&(u.push(h[0]),u.push(d[0])),d.includes(g)){const e=d[d.indexOf(g)+1];u.push(e),u.push(h[0])}if(h.includes(g)){const e=h[h.indexOf(g)+1];u.push(e)}const m=u.filter(lt);return m.map((e=>{const[t,o]=e.split(":"),s=n[t];return s?VN(s,o):void 0})).concat(m.map((e=>{if(!p)return;const t=e.split(":")[0],o=n[t];if(!o)return;const s=`"#${e}"`;return{text:s,description:Ho("%s (positional)",o.string)+(o.help?` (${o.help})`:""),htmlContent:[{value:s,color:wE.STRING}],fuzzySearchKey:o.string+s}}))).filter(lt)},selectProposal:LN}),mE.add("pivot_group_values",{sequence:50,autoSelectFirstProposal:!0,getProposals(e){const t=e.functionContext;if(!t||!e||!function(e){const t=e.functionContext;return"PIVOT.VALUE"===t?.parent.toUpperCase()&&t.argPosition>=2&&t.argPosition%2==1}(e)&&!function(e){const t=e.functionContext;return"PIVOT.HEADER"===t?.parent.toUpperCase()&&t.argPosition>=1&&t.argPosition%2==0}(e))return;const o=UN(e),s=this.getters.getPivotId(o);if(!s||!this.getters.isExistingPivot(s))return;const i=this.getters.getPivot(s);if(!i.isValid())return;const n=t.argPosition,r=e.functionContext?.args[n-1]?.value;if(!r)return;let a;try{a=i.definition.getDimension(r)}catch(e){return}return"month_number"===a.granularity?Object.values(yn).map(((e,t)=>({text:`${t+1}`,fuzzySearchKey:e.toString(),description:e.toString(),htmlContent:[{value:`${t+1}`,color:wE.NUMBER}]}))):"quarter_number"===a.granularity?[1,2,3,4].map((e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:Ho("Quarter %s",e),htmlContent:[{value:`${e}`,color:wE.NUMBER}]}))):"day_of_month"===a.granularity?je(1,32).map((e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:wE.NUMBER}]}))):"iso_week_number"===a.granularity?je(0,54).map((e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:wE.NUMBER}]}))):"day_of_week"===a.granularity?je(1,8).map((e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:wE.NUMBER}]}))):"hour_number"===a.granularity?je(0,24).map((e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:wE.NUMBER}]}))):"minute_number"===a.granularity?je(0,60).map((e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:wE.NUMBER}]}))):"second_number"===a.granularity?je(0,60).map((e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:wE.NUMBER}]}))):i.getPossibleFieldValues(a).map((({value:e,label:t})=>{const o="string"==typeof e,s=o?`"${e}"`:e.toString(),i=t===e?"":t;return{text:s,description:i,htmlContent:[{value:s,color:o?wE.STRING:wE.NUMBER}],fuzzySearchKey:s+i}}))},selectProposal:LN}),mE.add("sheet_names",{sequence:150,autoSelectFirstProposal:!0,getProposals(e){return"SYMBOL"===e.type||"UNKNOWN"===e.type&&e.value.startsWith("'")?this.getters.getSheetIds().map((e=>{const t=We(this.getters.getSheetName(e));return{text:t,fuzzySearchKey:t.startsWith("'")?t:"'"+t}})):[]},selectProposal(e,t){const o=e.start,s=e.end;this.composer.changeComposerCursorSelection(o,s),this.composer.replaceComposerCursorSelection(t+"!")}});const AL=new n;AL.add("link",{condition:(e,t)=>!!t.getEvaluatedCell(e).link,execute:(e,t,o)=>Zo(t.model.getters.getEvaluatedCell(e).link,t,o),title:(e,t)=>{const o=t.getEvaluatedCell(e).link;return o?o.isExternal?Ho("Go to url: %(url)s",{url:o.url}):Ho("Go to %(label)s",{label:o.label}):""},sequence:5});const DL=(new n).add("ADD_COLUMNS_ROWS",(function(e){const t=[];let o=e.base;"after"===e.position&&o++;for(let s=0;s<e.quantity;s++)t.push(s+o);return[{type:"REMOVE_COLUMNS_ROWS",dimension:e.dimension,elements:t,sheetId:e.sheetId,sheetName:e.sheetName}]})).add("REMOVE_COLUMNS_ROWS",(function(e){const t=[],o=[...e.elements].sort(((e,t)=>e-t));for(const s of Ye(o)){const o=0===s[0]?0:s[0]-1,i=0===s[0]?"before":"after";t.push({type:"ADD_COLUMNS_ROWS",dimension:e.dimension,quantity:s.length,base:o,sheetId:e.sheetId,sheetName:e.sheetName,position:i})}return t})).add("ADD_MERGE",(function(e){return[{type:"REMOVE_MERGE",sheetId:e.sheetId,target:e.target}]})).add("REMOVE_MERGE",(function(e){return[{type:"ADD_MERGE",sheetId:e.sheetId,target:e.target}]})).add("CREATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetId,sheetName:e.name}]})).add("DELETE_SHEET",(function(e){return[{type:"CREATE_SHEET",sheetId:e.sheetId,position:1,name:e.sheetName}]})).add("DUPLICATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetIdTo,sheetName:""}]})).add("CREATE_FIGURE",(function(e){return[{type:"DELETE_FIGURE",figureId:e.figureId,sheetId:e.sheetId}]})).add("CREATE_CHART",(function(e){return[{type:"DELETE_FIGURE",figureId:e.figureId,sheetId:e.sheetId}]})).add("HIDE_COLUMNS_ROWS",(function(e){return[{type:"UNHIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]})).add("UNHIDE_COLUMNS_ROWS",(function(e){return[{type:"HIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]})).add("CREATE_TABLE_STYLE",(function(e){return[{type:"REMOVE_TABLE_STYLE",tableStyleId:e.tableStyleId}]})).add("ADD_PIVOT",(function(e){return[{type:"REMOVE_PIVOT",pivotId:e.pivotId}]})).add("RENAME_SHEET",(function(e){return[{type:"RENAME_SHEET",sheetId:e.sheetId,oldName:e.newName,newName:e.oldName}]}));for(const e of Ls.values())DL.contains(e)||DL.add(e,_L);function _L(e){return[e]}const OL=new n;OL.add("format_number_automatic",{...pF,id:"format_number_automatic",sequence:10}).add("format_number_plain_text",{...mF,id:"format_number_plain_text",sequence:15,separator:!0}).add("format_number_number",{...fF,id:"format_number_number",sequence:20}).add("format_number_percent",{...bF,id:"format_number_percent",sequence:30,separator:!0}).add("format_number_currency",{...SF,id:"format_number_currency",sequence:40}).add("format_number_accounting",{...yF,id:"format_number_accounting",sequence:45}).add("format_number_currency_rounded",{...CF,id:"format_number_currency_rounded",sequence:50}).add("format_custom_currency",{...IF,id:"format_custom_currency",sequence:60,separator:!0}).add("format_number_date",{...xF,id:"format_number_date",sequence:70}).add("format_number_time",{...EF,id:"format_number_time",sequence:80}).add("format_number_date_time",{...RF,id:"format_number_date_time",sequence:90}).add("format_number_duration",{...TF,id:"format_number_duration",sequence:100,separator:!0}).add("more_formats",{..._F,id:"more_formats",sequence:120});const FL=Et((e=>On(e)?"date":e.includes("[$")?"currency":"number")),PL={name:Ho("More formats"),icon:"o-spreadsheet-Icon.NUMBER_FORMATS",children:[e=>{const t=function(e){const t=new Set(OL.getAll().map((t=>"function"==typeof t.format?t.format(e):t.format))),o=new Map;for(const s of e.model.getters.getSheetIds()){const i=e.model.getters.getEvaluatedCells(s);for(const e in i){const s=i[e];if(s.format&&!o.has(s.format)&&!t.has(s.format)){const e=FL(s.format);"date"!==e&&"currency"!==e||o.set(s.format,gF({descriptionValue:"currency"===e?1e3:wF,format:s.format,name:s.format}))}}}return[...o.values()]}(e).map((e=>({...e,sequence:110})));return t.length>0&&(t[t.length-1].separator=!0),o([...OL.getAll(),...t])}]};const ML=new vR;ML.add("file",{name:Ho("File"),sequence:10}).addChild("settings",["file"],{name:Ho("Settings"),sequence:200,execute:e=>e.openSidePanel("Settings"),isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.COG"}).add("edit",{name:Ho("Edit"),sequence:20}).addChild("undo",["edit"],{...__,sequence:10}).addChild("redo",["edit"],{...O_,sequence:20,separator:!0}).addChild("copy",["edit"],{...F_,sequence:30}).addChild("cut",["edit"],{...P_,sequence:40}).addChild("paste",["edit"],{...M_,sequence:50}).addChild("paste_special",["edit"],{...N_,sequence:60,separator:!0}).addChild("paste_special_value",["edit","paste_special"],{...k_,sequence:10}).addChild("paste_special_format",["edit","paste_special"],{...V_,sequence:20}).addChild("edit_table",["edit"],{...X_,isVisible:VD,sequence:60}).addChild("find_and_replace",["edit"],{...L_,sequence:65,separator:!0}).addChild("delete",["edit"],{name:Ho("Delete"),icon:"o-spreadsheet-Icon.TRASH",sequence:70}).addChild("edit_delete_cell_values",["edit","delete"],{...H_,sequence:10}).addChild("edit_delete_row",["edit","delete"],{...U_,sequence:20}).addChild("edit_delete_column",["edit","delete"],{...$_,sequence:30}).addChild("edit_delete_cell_shift_up",["edit","delete"],{...Z_,sequence:40}).addChild("edit_delete_cell_shift_left",["edit","delete"],{...j_,sequence:50}).addChild("edit_unhide_columns",["edit"],{...jD,sequence:80}).addChild("edit_unhide_rows",["edit"],{...KD,sequence:80}).add("view",{name:Ho("View"),sequence:30}).addChild("unfreeze_panes",["view"],{...JD,sequence:4}).addChild("freeze_panes",["view"],{...QD,sequence:5}).addChild("unfreeze_rows",["view","freeze_panes"],{...e_,sequence:5}).addChild("freeze_first_row",["view","freeze_panes"],{...t_,sequence:10}).addChild("freeze_second_row",["view","freeze_panes"],{...o_,sequence:15}).addChild("freeze_current_row",["view","freeze_panes"],{...s_,sequence:20,separator:!0}).addChild("unfreeze_columns",["view","freeze_panes"],{...i_,sequence:25}).addChild("freeze_first_col",["view","freeze_panes"],{...n_,sequence:30}).addChild("freeze_second_col",["view","freeze_panes"],{...r_,sequence:35}).addChild("freeze_current_col",["view","freeze_panes"],{...a_,sequence:40}).addChild("group_headers",["view"],{name:Ho("Group"),sequence:15,separator:!0,icon:"o-spreadsheet-Icon.PLUS_IN_BOX",isVisible:HD}).addChild("group_columns",["view","group_headers"],{...d_,sequence:5}).addChild("ungroup_columns",["view","group_headers"],{...g_,isVisible:e=>v_(e,"COL"),sequence:10}).addChild("group_rows",["view","group_headers"],{...u_,sequence:15}).addChild("ungroup_rows",["view","group_headers"],{...p_,isVisible:e=>v_(e,"ROW"),sequence:20}).addChild("show",["view"],{name:Ho("Show"),sequence:1,icon:"o-spreadsheet-Icon.SHOW"}).addChild("view_gridlines",["view","show"],{...l_,sequence:5}).addChild("view_formulas",["view","show"],{...h_,sequence:10}).addChild("view_irregularity_map",["view"],{...c_,sequence:40,separator:!0}).add("insert",{name:Ho("Insert"),sequence:40}).addChild("insert_row",["insert"],{...eO,sequence:10}).addChild("insert_row_before",["insert","insert_row"],{...oO,sequence:10}).addChild("insert_row_after",["insert","insert_row"],{...nO,sequence:20}).addChild("insert_column",["insert"],{...rO,sequence:20}).addChild("insert_column_before",["insert","insert_column"],{...lO,sequence:10}).addChild("insert_column_after",["insert","insert_column"],{...dO,sequence:20}).addChild("insert_cell",["insert"],{...uO,sequence:30}).addChild("insert_cell_down",["insert","insert_cell"],{...gO,name:Ho("Shift down"),sequence:10}).addChild("insert_cell_right",["insert","insert_cell"],{...pO,name:Ho("Shift right"),sequence:20}).addChild("insert_sheet",["insert"],{...DO,sequence:40,separator:!0}).addChild("insert_chart",["insert"],{...mO,sequence:50}).addChild("insert_pivot",["insert"],{...fO,sequence:52}).addChild("insert_image",["insert"],{...vO,sequence:55}).addChild("insert_table",["insert"],{...bO,sequence:57}).addChild("insert_function",["insert"],{...SO,sequence:60}).addChild("insert_function_sum",["insert","insert_function"],{...CO,sequence:0}).addChild("insert_function_average",["insert","insert_function"],{...yO,sequence:10}).addChild("insert_function_count",["insert","insert_function"],{...wO,sequence:20}).addChild("insert_function_max",["insert","insert_function"],{...IO,sequence:30}).addChild("insert_function_min",["insert","insert_function"],{...xO,sequence:40,separator:!0}).addChild("categorie_function_all",["insert","insert_function"],{...EO,sequence:50}).addChild("categories_function_list",["insert","insert_function"],(()=>{const e=RS.content;return[...new Set(RS.getAll().filter((e=>!e.hidden)).map((e=>e.category)))].filter(lt).sort().map(((t,o)=>{const s=Object.keys(e).filter((o=>e[o].category===t&&!e[o].hidden));return{name:t,children:_O(s)}}))})).addChild("insert_link",["insert"],{...RO,separator:!0,sequence:70}).addChild("insert_checkbox",["insert"],{...TO,sequence:80}).addChild("insert_dropdown",["insert"],{...AO,separator:!0,sequence:90}).add("format",{name:Ho("Format"),sequence:50}).addChild("format_number",["format"],{...PL,name:Ho("Number"),sequence:10,separator:!0}).addChild("format_bold",["format"],{...zF,sequence:20}).addChild("format_italic",["format"],{...$F,sequence:30}).addChild("format_underline",["format"],{...GF,sequence:40}).addChild("format_strikethrough",["format"],{...WF,sequence:50,separator:!0}).addChild("format_font_size",["format"],{...qF,sequence:60,separator:!0}).addChild("format_alignment",["format"],{...ZF,sequence:70}).addChild("format_alignment_left",["format","format_alignment"],{...YF,sequence:10}).addChild("format_alignment_center",["format","format_alignment"],{...XF,sequence:20}).addChild("format_alignment_right",["format","format_alignment"],{...KF,sequence:30,separator:!0}).addChild("format_alignment_top",["format","format_alignment"],{...QF,sequence:40}).addChild("format_alignment_middle",["format","format_alignment"],{...eP,sequence:50}).addChild("format_alignment_bottom",["format","format_alignment"],{...tP,sequence:60,separator:!0}).addChild("format_wrapping",["format"],{...oP,sequence:80,separator:!0}).addChild("format_wrapping_overflow",["format","format_wrapping"],{...iP,sequence:10}).addChild("format_wrapping_wrap",["format","format_wrapping"],{...nP,sequence:20}).addChild("format_wrapping_clip",["format","format_wrapping"],{...rP,sequence:30}).addChild("format_cf",["format"],{...aP,sequence:90,separator:!0}).addChild("format_clearFormat",["format"],{...lP,sequence:100,separator:!0}).add("data",{name:Ho("Data"),sequence:60}).addChild("sort_range",["data"],{...oF,sequence:10,separator:!0}).addChild("sort_ascending",["data","sort_range"],{...sF,sequence:10}).addChild("sort_descending",["data","sort_range"],{...aF,sequence:20}).addChild("data_cleanup",["data"],{...iF,sequence:15}).addChild("remove_duplicates",["data","data_cleanup"],{...nF,sequence:10}).addChild("trim_whitespace",["data","data_cleanup"],{...rF,sequence:20}).addChild("split_to_columns",["data"],{...hF,sequence:20}).addChild("data_validation",["data"],{name:Ho("Data Validation"),execute:e=>{e.openSidePanel("DataValidation")},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.DATA_VALIDATION",sequence:30,separator:!0}).addChild("add_remove_data_filter",["data"],{...lF,sequence:40,separator:!0}).addChild("pivot_data_sources",["data"],(e=>{const t=e.model.getters.getPivotIds().length;return e.model.getters.getPivotIds().map(((o,s)=>{const i={get highlights(){return wN(e.model.getters,o)}};return{id:`item_pivot_${e.model.getters.getPivotFormulaId(o)}`,name:e.model.getters.getPivotDisplayName(o),sequence:50+s/t,isReadonlyAllowed:!0,execute:e=>e.openSidePanel("PivotSidePanel",{pivotId:o}),isEnabled:e=>!e.isSmall,onStartHover:e=>e.getStore(vE).register(i),onStopHover:e=>e.getStore(vE).unRegister(i),icon:"o-spreadsheet-Icon.PIVOT",separator:s===e.model.getters.getPivotIds().length-1,secondaryIcon:e=>e.model.getters.isPivotUnused(o)?"o-spreadsheet-Icon.UNUSED_PIVOT_WARNING":void 0}}))})).addChild("reinsert_dynamic_pivot",["data"],dF).addChild("reinsert_static_pivot",["data"],uF);const NL=new class extends n{mapping={};uuidGenerator=new Ka;replace(e,t){const o={...t,id:this.uuidGenerator.uuidv4()};return super.replace(e,o)}getAllOrdered(){return this.getAll().sort(((e,t)=>e.sequence-t.sequence))}};class kL{listeners=[];async sendMessage(e){for(const{callback:t}of this.listeners)t(e)}onNewMessage(e,t){this.listeners.push({id:e,callback:t})}leave(e){this.listeners=this.listeners.filter((t=>t.id!==e))}}class VL{fileStore;constructor(e){this.fileStore=e}async requestImage(){const e=await this.userImageUpload(),t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}async uploadFile(e){const t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}userImageUpload(){return new Promise(((e,t)=>{const o=document.createElement("input");o.setAttribute("type","file"),o.setAttribute("accept","image/*"),o.addEventListener("change",(async()=>{null===o.files||1!==o.files.length?t():e(o.files[0])})),o.click()}))}getImageOriginalSize(e){return new Promise(((t,o)=>{const s=new Image;s.addEventListener("load",(()=>{const e={width:s.width,height:s.height};t(e)})),s.addEventListener("error",o),s.src=e}))}}const LL=[{transform:"scale(0)"},{transform:"scale(0.8)",offset:.33},{opacity:"0",transform:"scale(1)",offset:1}];yh`
|
|
1874
|
+
`;class Pk extends t.Component{static template="o_spreadsheet.PivotHTMLRenderer";static components={Checkbox:oR};static props={pivotId:String,onCellClicked:Function};pivot=this.env.model.getters.getPivot(this.props.pivotId);data={columns:[],rows:[],values:[]};state=t.useState({showMissingValuesOnly:!1});setup(){const e=this.pivot.getExpandedTableStructure(),t=this.env.model.getters.getPivotFormulaId(this.props.pivotId);this.data={columns:this._buildColHeaders(t,e),rows:this._buildRowHeaders(t,e),values:this._buildValues(t,e)}}get tracker(){return this.env.model.getters.getPivotPresenceTracker(this.props.pivotId)}getTableData(){if(!this.state.showMissingValuesOnly)return this.data;const e=this.getColumnsIndexes(),t=this.getRowsIndexes();return{columns:this.buildColumnsMissing(e),rows:this.buildRowsMissing(t),values:this.buildValuesMissing(e,t)}}addRecursiveRow(e){const t=this.pivot.getExpandedTableStructure().rows,o=[...t[e].values];if(o.length<=1)return[e];o.pop();const s=t.findIndex((e=>JSON.stringify(e.values)===JSON.stringify(o)));return[e].concat(this.addRecursiveRow(s))}buildColumnsMissing(e){const t=[];for(const e of this.data.columns){const o=[];for(const t in e)for(let s=0;s<e[t].span;s++)o.push(parseInt(t,10));t.push(o)}for(let o=t[t.length-1].length;o>=0;o--)if(!e.includes(o))for(const e of t)e.splice(o,1);const o=[];for(const e in t){const s=[];let i,n=1;for(let o=0;o<t[e].length;o++)i!==t[e][o]?(void 0!==i&&s.push(Object.assign({},this.data.columns[e][i],{span:n})),i=t[e][o],n=1):n++;void 0!==i&&s.push(Object.assign({},this.data.columns[e][i],{span:n})),o.push(s)}return o}buildRowsMissing(e){return e.map((e=>this.data.rows[e]))}buildValuesMissing(e,t){const o=e.map((()=>[]));for(const s of t)for(const t in e)o[t].push(this.data.values[e[t]][s]);return o}getColumnsIndexes(){const e=new Set;for(let t=0;t<this.data.columns.length;t++){const o=[];for(let e=0;e<this.data.columns[t].length;e++)for(let s=0;s<this.data.columns[t][e].span;s++)o.push(this.data.columns[t][e]);for(let t=0;t<o.length;t++)o[t].isMissing&&e.add(t)}for(let t=0;t<this.data.columns[this.data.columns.length-1].length;t++){this.data.values[t].find((e=>e.isMissing))&&e.add(t)}return Array.from(e).sort(((e,t)=>e-t))}getRowsIndexes(){const e=new Set;for(let t=0;t<this.data.rows.length;t++){this.data.rows[t].isMissing&&e.add(t);for(const o of this.data.values)o[t].isMissing&&this.addRecursiveRow(t).forEach((t=>e.add(t)))}return Array.from(e).sort(((e,t)=>e-t))}_buildColHeaders(e,t){const o=[];for(const s of t.columns){const t=[];for(const o of s){const s=[];for(let e=0;e<o.fields.length;e++)s.push({value:o.fields[e]},{value:o.values[e]});const i=this.pivot.parseArgsToPivotDomain(s),n=this.env.model.getters.getLocale();if("measure"===i.at(-1)?.field){const{value:s,format:r}=this.pivot.getPivotMeasureValue(wi(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${Bc(e,i).join(",")})`,value:In(s,{format:r,locale:n}),span:o.width,isMissing:!this.tracker?.isHeaderPresent(i)})}else{const{value:s,format:r}=this.pivot.getPivotHeaderValueAndFormat(i);t.push({formula:`=PIVOT.HEADER(${Bc(e,i).join(",")})`,value:In(s,{format:r,locale:n}),span:o.width,isMissing:!this.tracker?.isHeaderPresent(i)})}}o.push(t)}const s=o[o.length-1];return o[o.length-1]=s.map((e=>(e.isMissing||(e.style="color: #756f6f;"),e))),o}_buildRowHeaders(e,t){const o=[];for(const s of t.rows){const t=[];for(let e=0;e<s.fields.length;e++)t.push({value:s.fields[e]},{value:s.values[e]});const i=this.pivot.parseArgsToPivotDomain(t),{value:n,format:r}=this.pivot.getPivotHeaderValueAndFormat(i),a=this.env.model.getters.getLocale(),l={formula:`=PIVOT.HEADER(${Bc(e,i).join(",")})`,value:In(n,{format:r,locale:a}),isMissing:!this.tracker?.isHeaderPresent(i)};s.indent>1&&(l.style=`padding-left: ${s.indent-10}px`),o.push(l)}return o}_buildValues(e,t){const o=[];for(const s of t.columns.at(-1)||[]){const i=[],n=wi(s.values[s.values.length-1]);for(const o of t.rows){const t=[];for(let e=0;e<o.fields.length;e++)t.push({value:o.fields[e]},{value:o.values[e]});for(let e=0;e<s.fields.length-1;e++)t.push({value:s.fields[e]},{value:s.values[e]});const r=this.pivot.parseArgsToPivotDomain(t),{value:a,format:l}=this.pivot.getPivotCellValueAndFormat(n,r),c=this.env.model.getters.getLocale();i.push({formula:`=PIVOT.VALUE(${Bc(e,r,n).join(",")})`,value:In(a,{format:l,locale:c}),isMissing:!this.tracker?.isValuePresent(n,r)})}o.push(i)}return o}}class Mk{static getters=[];history;constructor(e){this.history=Object.assign(Object.create(e),{update:e.addChange.bind(e,this),selectCell:()=>{}})}exportForExcel(e){}allowDispatch(e){return"Success"}beforeHandle(e){}handle(e){}finalize(){}batchValidations(...e){return t=>e.map((e=>e.call(this,t))).flat()}chainValidations(...e){return t=>{for(const o of e){let e=o.call(this,t);Array.isArray(e)||(e=[e]);const s=e.filter((e=>"Success"!==e));if(s.length)return s}return"Success"}}checkValidations(e,...t){return this.batchValidations(...t)(e)}}class Nk extends Mk{getters;dispatch;canDispatch;constructor({getters:e,stateObserver:t,range:o,dispatch:s,canDispatch:i}){super(t),o.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.dispatch=s,this.canDispatch=i}import(e){}export(e){}adaptRanges(e,t,o){}garbageCollectExternalResources(){}}class kk{id;format;style;sheetId;getRangeString;isFormula=!0;compiledFormula;constructor(e,t,o,s,i,n,r){this.id=e,this.format=o,this.style=s,this.sheetId=n,this.getRangeString=r;let a=0;const l=t.tokens.map((e=>{if("REFERENCE"===e.type){const e=a++;return new Vk(i,e,this.sheetId,this.getRangeString)}return e}));this.compiledFormula={...t,dependencies:i,tokens:l}}get content(){return dt(this.compiledFormula.tokens.map((e=>e.value)))}get contentWithFixedReferences(){let e=0;return dt(this.compiledFormula.tokens.map((t=>{if("REFERENCE"===t.type){const t=e++;return this.getRangeString(this.compiledFormula.dependencies[t],this.sheetId,{useBoundedReference:!0})}return t.value})))}}class Vk{ranges;rangeIndex;sheetId;getRangeString;type="REFERENCE";constructor(e,t,o,s){this.ranges=e,this.rangeIndex=t,this.sheetId=o,this.getRangeString=s}get value(){const e=this.ranges[this.rangeIndex];return this.getRangeString(e,this.sheetId)}}function Lk(e){return""===e?NaN:Number(e)}function Hk(e){return Object.entries(e).map((([e,t])=>t?Uk(parseInt(e,10),t):void 0)).filter(lt).map((e=>Po(e.left,e.top)+":"+Po(e.right,e.bottom)))}function Uk(e,t){return{...t.zone,id:e}}class Bk{getters;providers=[];constructor(e){this.getters=e}static getters=["adaptFormulaStringDependencies","copyFormulaStringForSheet","extendRange","getRangeString","getRangeFromSheetXC","createAdaptedRanges","getRangeData","getRangeDataFromXc","getRangeDataFromZone","getRangeFromRangeData","getRangeFromZone","getRangesUnion","recomputeRanges","isRangeValid","removeRangesSheetPrefix"];allowDispatch(e){return"MOVE_RANGES"===e.type?1===e.target.length?"Success":"InvalidZones":"Success"}beforeHandle(e){}handle(e){const t=Ia(e);t?.applyChange&&this.executeOnAllRanges(t.applyChange,t.sheetId,t.sheetName)}finalize(){}verifyRangeRemoved(e){return t=>{const o=e(t);return"NONE"===o.changeType||pr(o.range.zone)?o:{range:o.range,changeType:"REMOVE"}}}executeOnAllRanges(e,t,o){const s=this.verifyRangeRemoved(e);for(const e of this.providers)e(s,t,o)}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,o,s){return e.map((e=>{if(!pr(e.zone))return e;const i=e.prefixSheet?e.sheetId:s,n=ba(e),r=va(e),a={...e.unboundedZone,left:n&&!e.unboundedZone.hasHeader?e.unboundedZone.left:e.unboundedZone.left+(e.parts[0].colFixed?0:t),right:n?e.unboundedZone.right:e.unboundedZone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:r&&!e.unboundedZone.hasHeader?e.unboundedZone.top:e.unboundedZone.top+(e.parts[0].rowFixed?0:o),bottom:r?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:o)};return function(e){if(mr(e.zone))return e;const t={...e.unboundedZone},o={...e.zone};let s=e.parts;if(void 0!==t.right&&t.right<t.left){const e=t.right;t.right=t.left,t.left=e,o.right=o.left,o.left=e,s=[{colFixed:s[1]?.colFixed||!1,rowFixed:s[0]?.rowFixed||!1},{colFixed:s[0]?.colFixed||!1,rowFixed:s[1]?.rowFixed||!1}]}if(void 0!==t.bottom&&t.bottom<t.top){const e=t.bottom;t.bottom=t.top,t.top=e,o.bottom=o.top,o.top=e,s=[{colFixed:s[0]?.colFixed||!1,rowFixed:s[1]?.rowFixed||!1},{colFixed:s[1]?.colFixed||!1,rowFixed:s[0]?.rowFixed||!1}]}return{unboundedZone:t,zone:o,parts:s,invalidXc:e.invalidXc,prefixSheet:e.prefixSheet,invalidSheetName:e.invalidSheetName,sheetId:e.sheetId}}(pa({...e,sheetId:i,zone:a},this.getters.getSheetSize))}))}removeRangesSheetPrefix(e,t){return t.map((t=>t.prefixSheet&&t.sheetId===e?{...t,prefixSheet:!1}:t))}extendRange(e,t,o){const s="COL"===t?e.zone.right+o:e.zone.right,i="ROW"===t?e.zone.bottom+o:e.zone.bottom,n={left:e.zone.left,top:e.zone.top,right:ba(e)?void 0:s,bottom:va(e)?void 0:i};return pa({...e,zone:n},this.getters.getSheetSize)}getRangeFromSheetXC(e,t){if(!ta.test(t)||!this.getters.tryGetSheet(e))return fa(t);const{sheetName:o}=ra(t);return ma({xc:t,sheetId:this.getters.getSheetIdByName(o)||e,invalidSheetName:o&&!this.getters.getSheetIdByName(o)?o:void 0},this.getters.getSheetSize)}getRangeString(e,t,o={useBoundedReference:!1,useFixedReference:!1}){return e?e.invalidXc?e.invalidXc:this.getters.tryGetSheet(e.sheetId)?Sa(e,t,this.getters.getSheetName,o):ti.InvalidReference:ti.InvalidReference}getRangeDataFromXc(e,t){const o=this.getters.getRangeFromSheetXC(e,t);return this.getRangeDataFromZone(o.sheetId,o.unboundedZone)}getRangeDataFromZone(e,t){return{_sheetId:e,_zone:t=this.getters.getUnboundedZone(e,t)}}getRangeData(e){return this.getRangeDataFromZone(e.sheetId,e.unboundedZone)}getRangeFromZone(e,t){return pa({sheetId:e,zone:t,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}],prefixSheet:!1},this.getters.getSheetSize)}recomputeRanges(e,t){const o=e.map((e=>e.unboundedZone)),s=t.map((e=>e.unboundedZone));return nr(o,s).map((t=>this.getRangeFromZone(e[0].sheetId,t)))}getRangeFromRangeData(e){if(!this.getters.tryGetSheet(e._sheetId))return fa(ti.InvalidReference);return pa({prefixSheet:!1,zone:e._zone,sheetId:e._sheetId,invalidSheetName:void 0,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}]},this.getters.getSheetSize)}isRangeValid(e){if(!e)return!1;const{xc:t,sheetName:o}=ra(e);return null!==t.match(ta)&&(!o||void 0!==this.getters.getSheetIdByName(o))}getRangesUnion(e){const t=e.map((e=>e.unboundedZone)),o=function(...e){return{top:Math.min(...e.map((e=>e.top))),left:Math.min(...e.map((e=>e.left))),bottom:e.some((e=>void 0===e.bottom))?void 0:Math.max(...e.map((e=>e.bottom))),right:e.some((e=>void 0===e.right))?void 0:Math.max(...e.map((e=>e.right)))}}(...t);return this.getRangeFromZone(e[0].sheetId,o)}adaptFormulaStringDependencies(e,t,o){if(!t.startsWith("="))return t;const s=HS(t),i=s.dependencies.map((t=>{const s=this.getters.getRangeFromSheetXC(e,t),i=o(s);return"NONE"===i.changeType?s:i.range}));return this.getters.getFormulaString(e,s.tokens,i)}copyFormulaStringForSheet(e,t,o,s){if(!o.startsWith("="))return o;const i=HS(o),n=i.dependencies.map((o=>{const i=this.getters.getRangeFromSheetXC(e,o);return"keepSameReference"===s?i:Ca(e,t,i)}));return this.getters.getFormulaString(t,i.tokens,n)}}function zk(e,t){if(!e)return;const o=t(e);switch(o.changeType){case"NONE":return e;case"REMOVE":return;default:return o.range}}class $k extends Mk{getters;constructor({getters:e,stateObserver:t}){super(t),this.getters=e}}const Gk=new n;Gk.add("pivots",(e=>{for(const t of e.getPivotIds()){const o=e.getPivot(t);o.markAsDirtyForEvaluation?.()}}));const Wk=RS.mapping;function qk(e,t,o){return new Zk(e,t,o).getParameters()}class Zk{getters;computeCell;evalContext;rangeCache={};constructor(e,t,o){this.getters=t,this.computeCell=o,this.evalContext=Object.assign(Object.create(Wk),e,{getters:this.getters,locale:this.getters.getLocale()})}getParameters(){return{referenceDenormalizer:this.refFn.bind(this),ensureRange:this.range.bind(this),evalContext:this.evalContext}}refFn(e,t){const o=this.getRangeError(e);if(o)return o;if(t){return{value:aa(this.getters.getSheetName(e.sheetId),fr(e.zone))}}const s={sheetId:e.sheetId,col:e.zone.left,row:e.zone.top};return this.computeCell(s)}range(e){const t=this.getRangeError(e);if(t)return[[t]];const o=e.sheetId,s=e.zone,i=wr(s,this.getters.getSheetZone(o));if(!i)return[[]];const{top:n,left:r,bottom:a,right:l}=s,c=`${o}-${n}-${r}-${a}-${l}`;if(c in this.rangeCache)return this.rangeCache[c];const h=i.bottom-i.top+1,d=i.right-i.left+1,u=new Array(d);for(let e=i.left;e<=i.right;e++){const t=e-i.left;u[t]=new Array(h);for(let s=i.top;s<=i.bottom;s++){const n=s-i.top;u[t][n]=this.computeCell({sheetId:o,col:e,row:s})}}return this.rangeCache[c]=u,u}getRangeError(e){return pr(e.zone)?e.invalidSheetName?new si(Ho("Invalid sheet name: %s",e.invalidSheetName)):void 0:new ri}}function jk(e,t,o,s,i){Yk(e,t,o||0,s||e.length-1,i||Kk)}function Yk(e,t,o,s,i){for(;s>o;){if(s-o>600){var n=s-o+1,r=t-o+1,a=Math.log(n),l=.5*Math.exp(2*a/3),c=.5*Math.sqrt(a*l*(n-l)/n)*(r-n/2<0?-1:1);Yk(e,t,Math.max(o,Math.floor(t-r*l/n+c)),Math.min(s,Math.floor(t+(n-r)*l/n+c)),i)}var h=e[t],d=o,u=s;for(Xk(e,o,t),i(e[s],h)>0&&Xk(e,o,s);d<u;){for(Xk(e,d,u),d++,u--;i(e[d],h)<0;)d++;for(;i(e[u],h)>0;)u--}0===i(e[o],h)?Xk(e,o,u):Xk(e,++u,s),u<=t&&(o=u+1),t<=u&&(s=u-1)}}function Xk(e,t,o){var s=e[t];e[t]=e[o],e[o]=s}function Kk(e,t){return e<t?-1:e>t?1:0}class Jk{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(e){let t=this.data;const o=[];if(!cV(e,t))return o;const s=this.toBBox,i=[];for(;t;){for(let n=0;n<t.children.length;n++){const r=t.children[n],a=t.leaf?s(r):r;cV(e,a)&&(t.leaf?o.push(r):lV(e,a)?this._all(r,o):i.push(r))}t=i.pop()}return o}collides(e){let t=this.data;if(!cV(e,t))return!1;const o=[];for(;t;){for(let s=0;s<t.children.length;s++){const i=t.children[s],n=t.leaf?this.toBBox(i):i;if(cV(e,n)){if(t.leaf||lV(e,n))return!0;o.push(i)}}t=o.pop()}return!1}load(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(let t=0;t<e.length;t++)this.insert(e[t]);return this}let t=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===t.height)this._splitRoot(this.data,t);else{if(this.data.height<t.height){const e=this.data;this.data=t,t=e}this._insert(t,this.data.height-t.height-1,!0)}else this.data=t;return this}insert(e){return e&&this._insert(e,this.data.height-1),this}clear(){return this.data=hV([]),this}remove(e,t){if(!e)return this;let o=this.data;const s=this.toBBox(e),i=[],n=[];let r,a,l;for(;o||i.length;){if(o||(o=i.pop(),a=i[i.length-1],r=n.pop(),l=!0),o.leaf){const s=Qk(e,o.children,t);if(-1!==s)return o.children.splice(s,1),i.push(o),this._condense(i),this}l||o.leaf||!lV(o,s)?a?(r++,o=a.children[r],l=!1):o=null:(i.push(o),n.push(r),r=0,a=o,o=o.children[0])}return this}toBBox(e){return e}compareMinX(e,t){return e.minX-t.minX}compareMinY(e,t){return e.minY-t.minY}toJSON(){return this.data}fromJSON(e){return this.data=e,this}_all(e,t){const o=[];for(;e;)e.leaf?t.push(...e.children):o.push(...e.children),e=o.pop();return t}_build(e,t,o,s){const i=o-t+1;let n,r=this._maxEntries;if(i<=r)return n=hV(e.slice(t,o+1)),eV(n,this.toBBox),n;s||(s=Math.ceil(Math.log(i)/Math.log(r)),r=Math.ceil(i/Math.pow(r,s-1))),n=hV([]),n.leaf=!1,n.height=s;const a=Math.ceil(i/r),l=a*Math.ceil(Math.sqrt(r));dV(e,t,o,l,this.compareMinX);for(let i=t;i<=o;i+=l){const t=Math.min(i+l-1,o);dV(e,i,t,a,this.compareMinY);for(let o=i;o<=t;o+=a){const i=Math.min(o+a-1,t);n.children.push(this._build(e,o,i,s-1))}}return eV(n,this.toBBox),n}_chooseSubtree(e,t,o,s){for(;s.push(t),!t.leaf&&s.length-1!==o;){let o,s=1/0,r=1/0;for(let a=0;a<t.children.length;a++){const l=t.children[a],c=nV(l),h=(i=e,n=l,(Math.max(n.maxX,i.maxX)-Math.min(n.minX,i.minX))*(Math.max(n.maxY,i.maxY)-Math.min(n.minY,i.minY))-c);h<r?(r=h,s=c<s?c:s,o=l):h===r&&c<s&&(s=c,o=l)}t=o||t.children[0]}var i,n;return t}_insert(e,t,o){const s=o?e:this.toBBox(e),i=[],n=this._chooseSubtree(s,this.data,t,i);for(n.children.push(e),oV(n,s);t>=0&&i[t].children.length>this._maxEntries;)this._split(i,t),t--;this._adjustParentBBoxes(s,i,t)}_split(e,t){const o=e[t],s=o.children.length,i=this._minEntries;this._chooseSplitAxis(o,i,s);const n=this._chooseSplitIndex(o,i,s),r=hV(o.children.splice(n,o.children.length-n));r.height=o.height,r.leaf=o.leaf,eV(o,this.toBBox),eV(r,this.toBBox),t?e[t-1].children.push(r):this._splitRoot(o,r)}_splitRoot(e,t){this.data=hV([e,t]),this.data.height=e.height+1,this.data.leaf=!1,eV(this.data,this.toBBox)}_chooseSplitIndex(e,t,o){let s,i=1/0,n=1/0;for(let r=t;r<=o-t;r++){const t=tV(e,0,r,this.toBBox),a=tV(e,r,o,this.toBBox),l=aV(t,a),c=nV(t)+nV(a);l<i?(i=l,s=r,n=c<n?c:n):l===i&&c<n&&(n=c,s=r)}return s||o-t}_chooseSplitAxis(e,t,o){const s=e.leaf?this.compareMinX:sV,i=e.leaf?this.compareMinY:iV;this._allDistMargin(e,t,o,s)<this._allDistMargin(e,t,o,i)&&e.children.sort(s)}_allDistMargin(e,t,o,s){e.children.sort(s);const i=this.toBBox,n=tV(e,0,t,i),r=tV(e,o-t,o,i);let a=rV(n)+rV(r);for(let s=t;s<o-t;s++){const t=e.children[s];oV(n,e.leaf?i(t):t),a+=rV(n)}for(let s=o-t-1;s>=t;s--){const t=e.children[s];oV(r,e.leaf?i(t):t),a+=rV(r)}return a}_adjustParentBBoxes(e,t,o){for(let s=o;s>=0;s--)oV(t[s],e)}_condense(e){for(let t,o=e.length-1;o>=0;o--)0===e[o].children.length?o>0?(t=e[o-1].children,t.splice(t.indexOf(e[o]),1)):this.clear():eV(e[o],this.toBBox)}}function Qk(e,t,o){if(!o)return t.indexOf(e);for(let s=0;s<t.length;s++)if(o(e,t[s]))return s;return-1}function eV(e,t){tV(e,0,e.children.length,t,e)}function tV(e,t,o,s,i){i||(i=hV(null)),i.minX=1/0,i.minY=1/0,i.maxX=-1/0,i.maxY=-1/0;for(let n=t;n<o;n++){const t=e.children[n];oV(i,e.leaf?s(t):t)}return i}function oV(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 sV(e,t){return e.minX-t.minX}function iV(e,t){return e.minY-t.minY}function nV(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function rV(e){return e.maxX-e.minX+(e.maxY-e.minY)}function aV(e,t){const o=Math.max(e.minX,t.minX),s=Math.max(e.minY,t.minY),i=Math.min(e.maxX,t.maxX),n=Math.min(e.maxY,t.maxY);return Math.max(0,i-o)*Math.max(0,n-s)}function lV(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function cV(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function hV(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function dV(e,t,o,s,i){const n=[t,o];for(;n.length;){if((o=n.pop())-(t=n.pop())<=s)continue;const r=t+Math.ceil((o-t)/s/2)*s;jk(e,r,t,o,i),n.push(t,r,r,o)}}class uV{rTrees={};constructor(e=[]){const t={};for(const o of e){const e=o.boundingBox.sheetId;t[e]||(t[e]=[]),t[e].push(o)}for(const e in t)this.rTrees[e]=new gV,this.rTrees[e].load(t[e])}insert(e){const t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new gV),this.rTrees[t].insert(e)}search({zone:e,sheetId:t}){return this.rTrees[t]?this.rTrees[t].search({minX:e.left,minY:e.top,maxX:e.right,maxY:e.bottom}):[]}remove(e){const t=e.boundingBox.sheetId;this.rTrees[t]&&this.rTrees[t].remove(e,this.rtreeItemComparer)}rtreeItemComparer(e,t){return e.data===t.data&&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}}class gV extends Jk{toBBox({boundingBox:e}){const t=e.zone;return{minX:t.left,minY:t.top,maxX:t.right,maxY:t.bottom}}compareMinX(e,t){return e.boundingBox.zone.left-t.boundingBox.zone.left}compareMinY(e,t){return e.boundingBox.zone.top-t.boundingBox.zone.top}}class pV{createEmptyPositionSet;dependencies=new $D;rTree;constructor(e,t=[]){this.createEmptyPositionSet=e,this.rTree=new uV(t)}removeAllDependencies(e){const t=this.dependencies.get(e);if(t){for(const e of t)this.rTree.remove(e);this.dependencies.delete(e)}}addDependencies(e,t){const o=t.map((({sheetId:t,zone:o})=>({data:e,boundingBox:{zone:o,sheetId:t}})));for(const e of o)this.rTree.insert(e);const s=this.dependencies.get(e);s?s.push(...o):this.dependencies.set(e,o)}getCellsDependingOn(e){const t=this.createEmptyPositionSet(),o=Array.from(e).reverse();for(;o.length>0;){const e=o.pop(),s=e.zone,i=e.sheetId;for(let e=s.left;e<=s.right;e++)for(let o=s.top;o<=s.bottom;o++)t.add({sheetId:i,col:e,row:o});const n=this.rTree.search(e).map((e=>e.data)),r={};for(const e of n)t.has(e)||(r[e.sheetId]||(r[e.sheetId]=[]),r[e.sheetId].push(Mr(e)));for(const e in r){const t=nr(r[e],[]);o.push(...t.map((t=>({sheetId:e,zone:t}))))}}for(const o of e){const e=o.zone,s=o.sheetId;for(let o=e.left;o<=e.right;o++)for(let i=e.top;i<=e.bottom;i++)t.delete({sheetId:s,col:o,row:i})}return t}}class mV extends Uint32Array{columnOffset=0;cols=0;rows=0;static create(e,t){const o=function(e){if(0===e)return-1/0;if(e<0)return NaN;return 32-Math.clz32(--e)}(t),s=new this((e<<o>>5)+1);return s.columnOffset=o,s.cols=t,s.rows=e,s}getValue(e){const[t,o]=this.getCoordinates(e);return this[t]>>o&1}setValue(e,t){const[o,s]=this.getCoordinates(e),i=0===(this[o]>>s&1)&&1===t;return this[o]=this[o]&~(1<<s)|t<<s,i}isEmpty(){return!this.some((e=>0!==e))}fillAllPositions(){this.fill(-1>>>0)}clear(){this.fill(0)}getCoordinates(e){const{row:t,col:o}=e,s=(t<<this.columnOffset)+o,i=s>>5;return[i,s-(i<<5)]}}class fV{sheets={};insertions=[];maxSize=0;constructor(e){for(const t in e){const o=e[t].cols,s=e[t].rows;this.maxSize+=o*s,this.sheets[t]=mV.create(s,o)}}add(e){this.sheets[e.sheetId].setValue(e,1)&&this.insertions.push(e)}addMany(e){for(const t of e)this.add(t)}delete(e){this.sheets[e.sheetId].setValue(e,0)}deleteMany(e){for(const t of e)this.delete(t)}has(e){return 1===this.sheets[e.sheetId].getValue(e)}clear(){const e=[...this];this.insertions=[];for(const e in this.sheets)this.sheets[e].clear();return e}isEmpty(){if(0===this.insertions.length)return!0;for(const e in this.sheets)if(!this.sheets[e].isEmpty())return!1;return!0}fillAllPositions(){this.insertions=new Array(this.maxSize);let e=0;for(const t in this.sheets){const o=this.sheets[t];o.fillAllPositions();for(let s=0;s<o.rows;s++)for(let i=0;i<o.cols;i++)this.insertions[e++]={sheetId:t,row:s,col:i}}}*[Symbol.iterator](){for(const e of this.insertions)1===this.sheets[e.sheetId].getValue(e)&&(yield e)}}class vV{resultsToArrayFormulas=new uV;arrayFormulasToResults=new $D;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map((e=>e.data))||bV}getArrayResultZone(e){return this.arrayFormulasToResults.get(e)}removeNode(e){this.resultsToArrayFormulas.remove({boundingBox:{sheetId:e.sheetId,zone:Mr(e)},data:e}),this.arrayFormulasToResults.delete(e)}addRelation({arrayFormulaPosition:e,resultZone:t}){this.resultsToArrayFormulas.insert({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.set(e,t)}isArrayFormula(e){return this.arrayFormulasToResults.has(e)}}const bV=[],SV=Object.freeze(Jn(new ni)),CV=Object.freeze(Jn({value:null}));class yV{context;getters;compilationParams;evaluatedCells=new $D;formulaDependencies=ut(new pV(this.createEmptyPositionSet.bind(this)));blockedArrayFormulas=new fV({});spreadingRelations=new vV;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=qk(this.context,this.getters,this.computeAndSave.bind(this))}getEvaluatedCell(e){return this.evaluatedCells.get(e)||CV}getSpreadZone(e,t={ignoreSpillError:!1}){const o=this.spreadingRelations.getArrayResultZone(e);if(!o)return;const s=this.evaluatedCells.get(e);return s?.type!==_s.error||t.ignoreSpillError&&s?.value===ti.SpilledBlocked?yr(Mr(e),o):Mr(e)}getEvaluatedPositions(){return this.evaluatedCells.keys()}getEvaluatedPositionsInSheet(e){return this.evaluatedCells.keysForSheet(e)}getArrayFormulaSpreadingOn(e){if(this.getEvaluatedCell(e).type===_s.empty)return;const t=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e.sheetId,Mr(e));return Array.from(t).find((e=>!this.blockedArrayFormulas.has(e)))}updateDependencies(e){this.formulaDependencies().removeAllDependencies(e);const t=this.getDirectDependencies(e);this.formulaDependencies().addDependencies(e,t)}addDependencies(e,t){this.formulaDependencies().addDependencies(e,t);for(const e of t){const t=e.sheetId,{left:o,bottom:s,right:i,top:n}=e.zone;for(let e=o;e<=i;e++)for(let o=n;o<=s;o++)this.computeAndSave({sheetId:t,col:e,row:o})}}updateCompilationParameters(){this.compilationParams=qk(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.updateDependencies=this.updateDependencies.bind(this),this.compilationParams.evalContext.addDependencies=this.addDependencies.bind(this),this.compilationParams.evalContext.lookupCaches={forwardSearch:new Map,reverseSearch:new Map}}createEmptyPositionSet(){const e={};for(const t of this.getters.getSheetIds())e[t]={rows:this.getters.getNumberRows(t),cols:this.getters.getNumberCols(t)};return new fV(e)}evaluateCells(e){const t=performance.now(),o=this.createEmptyPositionSet();o.addMany(e);const s=this.getArrayFormulasImpactedByChangesOf(e);o.addMany(this.getCellsDependingOn(e)),o.addMany(s),o.addMany(this.getCellsDependingOn(s)),this.evaluate(o),console.debug("evaluate Cells",performance.now()-t,"ms")}getArrayFormulasImpactedByChangesOf(e){const t=this.createEmptyPositionSet();for(const o of e){const e=this.getters.getCell(o)?.content,s=this.getArrayFormulaSpreadingOn(o);void 0!==s&&t.add(s),e||t.add(o)}const o=Dr(t);for(const e in o)for(const s of o[e])t.addMany(this.getArrayFormulasBlockedBy(e,s));return t}buildDependencyGraph(){this.blockedArrayFormulas=this.createEmptyPositionSet(),this.spreadingRelations=new vV,this.formulaDependencies=ut((()=>{const e=[...this.getAllCells()].flatMap((e=>this.getDirectDependencies(e).filter((e=>!e.invalidSheetName&&!e.invalidXc)).map((t=>({data:e,boundingBox:{zone:t.zone,sheetId:t.sheetId}})))));return new pV(this.createEmptyPositionSet.bind(this),e)}))}evaluateAllCells(){const e=performance.now();this.evaluatedCells=new $D,this.evaluate(this.getAllCells()),console.debug("evaluate all cells",performance.now()-e,"ms")}evaluateFormulaResult(e,t){const o=HS(t),s=o.dependencies.map((t=>this.getters.getRangeFromSheetXC(e,t)));return this.updateCompilationParameters(),this.evaluateCompiledFormula(e,{...o,dependencies:s})}evaluateCompiledFormula(e,t,o){try{const s=xV(t,this.compilationParams,e,this.buildSafeGetSymbolValue(o),this.compilationParams.evalContext.__originCellPosition);return js(s)?ki(s,IV):IV(s)}catch(e){return TS(e,"")}}getAllCells(){const e=this.createEmptyPositionSet();return e.fillAllPositions(),e}getArrayFormulasBlockedBy(e,t){const o=this.createEmptyPositionSet(),s=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e,t);o.addMany(s);const i=[...s].filter((e=>!this.blockedArrayFormulas.has(e)));return i.length&&o.deleteMany(i),o.addMany(this.getCellsDependingOn(o)),o}nextPositionsToUpdate=new fV({});cellsBeingComputed=new Set;symbolsBeingComputed=new Set;evaluate(e){this.cellsBeingComputed=new Set,this.nextPositionsToUpdate=e;let t=0;for(;!this.nextPositionsToUpdate.isEmpty()&&t++<30;){this.updateCompilationParameters();const e=this.nextPositionsToUpdate.clear();for(let t=0;t<e.length;++t)this.evaluatedCells.delete(e[t]);for(let t=0;t<e.length;++t){const o=e[t];if(this.nextPositionsToUpdate.has(o))continue;const s=this.computeCell(o);s!==CV&&this.evaluatedCells.set(o,s)}Gk.getAll().forEach((e=>e(this.getters)))}t>=30&&console.warn("Maximum iteration reached while evaluating cells")}computeCell(e){const t=this.evaluatedCells.get(e);if(t)return t;this.blockedArrayFormulas.has(e)||this.invalidateSpreading(e),this.spreadingRelations.isArrayFormula(e)&&this.spreadingRelations.removeNode(e);const o=this.getters.getCell(e);if(void 0===o)return CV;const s=o.id,i={format:o.format,locale:this.getters.getLocale()};try{return this.cellsBeingComputed.has(s)?SV:(this.cellsBeingComputed.add(s),o.isFormula?this.computeFormulaCell(e,o):Xn(o,i))}catch(e){return e.value=e?.value||ti.GenericError,e.message=e?.message||DS,Jn(e)}finally{this.cellsBeingComputed.delete(s)}}computeAndSave(e){const t=this.computeCell(e);return this.evaluatedCells.has(e)||this.evaluatedCells.set(e,t),t}computeFormulaCell(e,t){const o=xV(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e);if(!js(o)){const s=Jn(IV(o),this.getters.getLocale(),t);return s.type===_s.error&&(s.errorOriginPosition=o.errorOriginPosition??e),s}this.assertSheetHasEnoughSpaceToSpreadFormulaResult(e,o);const s=o.length,i=o[0].length,n={top:e.row,bottom:e.row+i-1,left:e.col,right:e.col+s-1};return this.spreadingRelations.addRelation({resultZone:n,arrayFormulaPosition:e}),this.assertNoMergedCellsInSpreadZone(e,o),wV(s,i,this.checkCollision(e)),wV(s,i,this.spreadValues(e,o)),this.invalidatePositionsDependingOnSpread(e.sheetId,n),Jn(IV(o[0][0]),this.getters.getLocale(),t)}invalidatePositionsDependingOnSpread(e,t){const o=this.formulaDependencies().getCellsDependingOn(function(e){const{top:t,left:o,bottom:s,right:i}=e;if(1===Lr(e))return[];const n={top:t+1,bottom:s,left:o,right:o};if(i===o)return[n];const r={top:t,bottom:s,left:o+1,right:i};return t===s?[r]:[n,r]}(t).map((t=>({sheetId:e,zone:t}))));o.delete({sheetId:e,col:t.left,row:t.top}),this.nextPositionsToUpdate.addMany(o)}assertSheetHasEnoughSpaceToSpreadFormulaResult({sheetId:e,col:t,row:o},s){const i=this.getters.getNumberCols(e),n=this.getters.getNumberRows(e),r=t+s.length<=i,a=o+s[0].length<=n;if(!r||!a){if(r)throw new ci(Ho("Result couldn't be automatically expanded. Please insert more rows."));if(a)throw new ci(Ho("Result couldn't be automatically expanded. Please insert more columns."));throw new ci(Ho("Result couldn't be automatically expanded. Please insert more columns and rows."))}}assertNoMergedCellsInSpreadZone({sheetId:e,col:t,row:o},s){if(0!==this.getters.getMergesInZone(e,{top:o,bottom:o+s[0].length-1,left:t,right:t+s.length-1}).length)throw new ci(Ho("Merged cells found in the spill zone. Please unmerge cells before using array formulas."))}checkCollision(e){const{sheetId:t,col:o,row:s}=e;return(i,n)=>{const r={sheetId:t,col:i+o,row:n+s},a=this.getters.getCell(r);if(a?.content||this.getters.getEvaluatedCell(r).type!==_s.empty)throw this.blockedArrayFormulas.add(e),new ci(Ho("Array result was not expanded because it would overwrite data in %s.",Po(r.col,r.row)));this.blockedArrayFormulas.delete(e)}}spreadValues({sheetId:e,col:t,row:o},s){return(i,n)=>{const r={sheetId:e,col:i+t,row:n+o},a=this.getters.getCell(r),l=Jn(IV(s[i][n]),this.getters.getLocale(),a);l.type===_s.error&&(l.errorOriginPosition=s[i][n].errorOriginPosition??r),this.evaluatedCells.set(r,l)}}invalidateSpreading(e){const t=this.spreadingRelations.getArrayResultZone(e);if(!t)return;for(let o=t.left;o<=t.right;o++)for(let s=t.top;s<=t.bottom;s++){const t={sheetId:e.sheetId,col:o,row:s},i=this.getters.getCell(t)?.content;i||this.evaluatedCells.delete(t)}const o=e.sheetId;this.invalidatePositionsDependingOnSpread(o,t),this.nextPositionsToUpdate.addMany(this.getArrayFormulasBlockedBy(o,t))}buildSafeGetSymbolValue(e){return t=>{if(this.symbolsBeingComputed.has(t))return SV;this.symbolsBeingComputed.add(t);try{const o=e?.(t);return o||new ii(Ho("Invalid formula"))}finally{this.symbolsBeingComputed.delete(t)}}}getDirectDependencies(e){const t=this.getters.getCell(e);return t?.isFormula?t.compiledFormula.dependencies:[]}getCellsDependingOn(e){const t=[],o=Dr(e);for(const e in o)t.push(...o[e].map((t=>({sheetId:e,zone:t}))));return this.formulaDependencies().getCellsDependingOn(t)}}function wV(e,t,o){for(let s=0;s<e;++s)for(let e=0;e<t;++e)0===s&&0===e||o(s,e)}function IV(e){return null===e.value||void 0===e.value?{...e,value:0}:e}function xV(e,t,o,s,i){return t.evalContext.__originCellPosition=i,t.evalContext.__originSheetId=o,e.execute(e.dependencies,t.referenceDenormalizer,t.ensureRange,s,t.evalContext)}const EV=/"(#[0-9a-fA-F]{6})"/g;const RV={isValid:!0};const TV=new n;function AV(e,t){const o=t.model.getters.getPivotCellFromPosition(e),s=t.model.getters.getPivotIdFromPosition(e);if(!s||"HEADER"!==o.type)return;const i=t.model.getters.getPivotCoreDefinition(s),n=i.collapsedDomains?.[o.dimension]?[...i.collapsedDomains[o.dimension]]:[],r=n.findIndex((e=>mt(e,o.domain)));-1!==r?n.splice(r,1):n.push(o.domain);const a=i.collapsedDomains?{...i.collapsedDomains}:{COL:[],ROW:[]};a[o.dimension]=n,t.model.dispatch("UPDATE_PIVOT",{pivotId:s,pivot:{...i,collapsedDomains:a}})}TV.add("data_validation_checkbox",((e,t)=>{if(e.isCellValidCheckbox(t)){const o=!!e.getEvaluatedCell(t).value;return{svg:o?jR:qR,hoverSvg:o?jR:ZR,priority:2,horizontalAlign:"center",size:17,margin:2,position:t,type:"data_validation_checkbox",onClick:(e,t)=>{const s=t.model.getters.getCell(e);if(t.model.getters.isReadonly()||!!s?.isFormula)return;const i=o?"FALSE":"TRUE";t.model.dispatch("UPDATE_CELL",{...e,content:i})}}}})),TV.add("data_validation_chip_icon",((e,t)=>{const o=e.getDataValidationChipStyle(t);if(o){const s=e.getCellComputedStyle(t);return{svg:GR(o),hoverSvg:WR(o),priority:10,horizontalAlign:"right",size:$a(s),margin:4,position:t,onClick:(e,t)=>{const{col:o,row:s}=e;t.model.selection.selectCell(o,s),t.startCellEdition()},type:"data_validation_chip_icon"}}})),TV.add("data_validation_list_icon",((e,t)=>{if(!e.isReadonly()&&e.cellHasListDataValidationIcon(t)){const s=e.getCellComputedStyle(t);return{svg:(o=s,{name:"CARET_DOWN",width:512,height:512,paths:[{fillColor:o.textColor||N,path:"M120 195 h270 l-135 130"}]}),hoverSvg:zR(s),priority:2,horizontalAlign:"right",size:17,margin:2,position:t,onClick:(e,t)=>{const{col:o,row:s}=e;t.model.selection.selectCell(o,s),t.startCellEdition()},type:"data_validation_list_icon"}}var o})),TV.add("filter_icon",((e,t)=>{if(e.isFilterHeader(t)){const o=e.isFilterActive(t),s=jt(e.getCellComputedStyle(t).fillColor||"#fff")<.45;return{type:"filter_icon",svg:XR(o,s,!1),hoverSvg:XR(o,s,!0),priority:3,horizontalAlign:"right",size:17,margin:2,position:t,onClick:(e,t)=>{const o=t.getStore(jx),s=o.persistentCellPopover;s.isOpen&&s.col===e.col&&s.row===e.row&&"FilterMenu"===s.type?o.close():o.open(e,"FilterMenu")}}}})),TV.add("conditional_formatting",((e,t)=>{const o=e.getConditionalIcon(t);if(o){const s=e.getCellStyle(t);return{type:"conditional_formatting",svg:KR[o].svg,priority:1,horizontalAlign:"left",size:$a(s),margin:4,position:t}}})),TV.add("pivot_collapse",((e,t)=>{if(!e.isSpillPivotFormula(t))return;const o=e.getPivotCellFromPosition(t),s=e.getPivotIdFromPosition(t);if("HEADER"===o.type&&s&&o.domain.length){const i=e.getPivotCoreDefinition(s),n=e.isDashboard(),r="COL"===o.dimension?i.columns:i.rows,a=!n&&o.domain.length!==r.length,l=(i.collapsedDomains?.[o.dimension]??[]).some((e=>mt(e,o.domain))),c="ROW"===o.dimension?15*(o.domain.length-1):0;return{type:"pivot_collapse",priority:4,horizontalAlign:"left",size:a||!n&&"ROW"===o.dimension&&i.rows.length>1?12:0,margin:a?4+c:c,svg:a?YR(l,!1):void 0,hoverSvg:a?YR(l,!0):void 0,position:t,onClick:AV}}}));const DV="0.00%";function _V(e){return class extends e{getters;cache={};rankAsc={};rankDesc={};runningTotal={};runningTotalInPercent={};constructor(e,t){super(e,t),this.getters=t.getters}markAsDirtyForEvaluation(){this.cache={},this.rankAsc={},this.rankDesc={},this.runningTotal={},this.runningTotalInPercent={},super.markAsDirtyForEvaluation?.()}getPivotCellValueAndFormat(e,t){return this.getMeasureDisplayValue(e,t)}_getPivotCellValueAndFormat(e,t){const o=`${e}-${t.map((e=>e.field+"="+e.value)).join(",")}`;if(this.cache[o])return this.cache[o];const s=this.getMeasure(e),i=s.computedBy?this.computeMeasure(s,t):super.getPivotCellValueAndFormat(e,t);return s.format?this.cache[o]={...i,format:s.format}:this.cache[o]=i,this.cache[o]}computeMeasure(e,t){if(!e.computedBy)return{value:0};const{columns:o,rows:s}=super.definition;if(e.aggregator&&o.length+s.length!==t.length){const o=this.getValuesToAggregate(e,t),s=Nc[e.aggregator];if(!s)return{value:0};try{return s([o],this.getters.getLocale())}catch(t){return TS(t,e.aggregator.toUpperCase())}}const i=this.getters.getMeasureCompiledFormula(e),n=this.getters.evaluateCompiledFormula(e.computedBy.sheetId,i,(e=>{const{columns:o,rows:s}=this.definition;if(o.find((t=>t.nameWithGranularity===e))){const{colDomain:o}=NO(this,t),s=o.findIndex((t=>t.field===e));return-1===s?new ai:this.getPivotHeaderValueAndFormat(o.slice(0,s+1))}if(s.find((t=>t.nameWithGranularity===e))){const{rowDomain:o}=NO(this,t),s=o.findIndex((t=>t.field===e));return-1===s?new ai:this.getPivotHeaderValueAndFormat(o.slice(0,s+1))}return this.getPivotCellValueAndFormat(e,t)}));return js(n)?n[0][0]:n}getValuesToAggregate(e,t){const{rowDomain:o,colDomain:s}=NO(this,t),i=super.getExpandedTableStructure(),n=[];if(0===s.length&&o.length<this.definition.rows.length&&this.definition.rows.length&&this.definition.columns.length){const t=this.treeToLeafDomains(i.getColTree()),s=this.getSubTreeMatchingDomain(i.getRowTree(),o),r=this.treeToLeafDomains(s);for(const s of t)for(const t of r)n.push(this._getPivotCellValueAndFormat(e.id,o.concat(t).concat(s)));return n}if(o.length===this.definition.rows.length&&0===s.length){const t=i.getColTree(),r=this.getSubTreeMatchingDomain(t,s),a=this.treeToLeafDomains(r,s);for(const t of a)n.push(this._getPivotCellValueAndFormat(e.id,o.concat(t)));return n}if(o.length===this.definition.rows.length&&s.length&&s.length<this.definition.columns.length){const t=this.getSubTreeMatchingDomain(i.getColTree(),s),r=this.treeToLeafDomains(t,s);for(const t of r)n.push(this._getPivotCellValueAndFormat(e.id,o.concat(t)));return n}{const t=i.getRowTree(),r=this.getSubTreeMatchingDomain(t,o),a=this.treeToLeafDomains(r,o);for(const t of a)n.push(this._getPivotCellValueAndFormat(e.id,t.concat(s)));return n}}getSubTreeMatchingDomain(e,t,o=0){if(o>t.length)return[];if(t.length===o)return e;for(const s of e){const e=Gc(this.definition.getDimension(s.field),t[o]?.value);if(s.field===t[o]?.field&&s.value===e)return this.getSubTreeMatchingDomain(s.children,t,o+1)}return[]}treeToLeafDomains(e,t=[]){const o=[];for(const s of e){const e=this.definition.getDimension(s.field),i=[...t,{field:s.field,value:s.value,type:e.type}];0===s.children.length?o.push(i):o.push(...this.treeToLeafDomains(s.children,i))}return o}getMeasureDisplayValue(e,t){const o=this.getMeasure(e),s=this._getPivotCellValueAndFormat(e,t);if(!o.display||"no_calculations"===o.display.type||s.message)return s;const i=o.display.fieldNameWithGranularity;if(i&&!this.isFieldInPivot(i))return{value:ti.NotAvailable,message:Ho('Field "%s" not found in pivot for measure display calculation',i)};try{const e=o.display;switch(e.type){case"%_of_grand_total":return this.asPercentOfGrandTotal(s,o);case"%_of_col_total":return this.asPercentOfColumnTotal(s,o,t);case"%_of_row_total":return this.asPercentOfRowTotal(s,o,t);case"%_of_parent_row_total":return this.asPercentOfParentRowTotal(s,o,t);case"%_of_parent_col_total":return this.asPercentOfParentColumnTotal(s,o,t);case"index":return this.asIndex(s,o,t);case"%_of_parent_total":return this.asPercentOfParentTotal(s,o,t,e);case"running_total":return this.asRunningTotal(s,o,t,e,"running_total");case"%_running_total":return this.asRunningTotal(s,o,t,e,"%_running_total");case"rank_asc":return this.asRank(s,o,t,e,"asc");case"rank_desc":return this.asRank(s,o,t,e,"desc");case"%_of":return this.asPercentOf(s,o,t,e);case"difference_from":return this.asDifferenceFrom(s,o,t,e);case"%_difference_from":return this.asDifferenceFromInPercent(s,o,t,e)}return s}catch(e){return TS(e,"COMPUTE_MEASURE_DISPLAY_VALUE")}}asPercentOfGrandTotal(e,t){const o=this.getGrandTotal(t.id);return 0===o?{value:ti.DivisionByZero}:{value:this.measureValueToNumber(e)/o,format:DV}}asPercentOfRowTotal(e,t,o){const s=this.getRowTotal(t.id,o);return 0===s?{value:ti.DivisionByZero}:{value:this.measureValueToNumber(e)/s,format:DV}}asPercentOfColumnTotal(e,t,o){const s=this.getColumnTotal(t.id,o);return 0===s?{value:ti.DivisionByZero}:{value:this.measureValueToNumber(e)/s,format:DV}}asPercentOfParentRowTotal(e,t,o){const s=function(e,t){const{colDomain:o,rowDomain:s}=NO(e,t);return[...o,...s.slice(0,s.length-1)]}(this,o),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,s));return 0===i?{value:""}:{value:this.measureValueToNumber(e)/i,format:DV}}asPercentOfParentColumnTotal(e,t,o){const s=function(e,t){const{colDomain:o,rowDomain:s}=NO(e,t);return[...o.slice(0,o.length-1),...s]}(this,o),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,s));return 0===i?{value:""}:{value:this.measureValueToNumber(e)/i,format:DV}}asPercentOfParentTotal(e,t,o,s){const{fieldNameWithGranularity:i}=s;if(!i)return e;if(!UO(i,o))return{value:""};const n=function(e,t,o){let{rowDomain:s,colDomain:i}=NO(e,o);if("row"===BO(e,t)){const e=s.findIndex((e=>e.field===t));if(-1===e)return o;s=s.slice(0,e+1)}else{const e=i.findIndex((e=>e.field===t));if(-1===e)return o;i=i.slice(0,e+1)}return[...s,...i]}(this,i,o),r=this._getPivotCellValueAndFormat(t.id,n),a=this.measureValueToNumber(r);return 0===a?{value:""}:{value:this.measureValueToNumber(e)/a,format:DV}}asIndex(e,t,o){const s=this.measureValueToNumber(e),i=this.getRowTotal(t.id,o),n=this.getColumnTotal(t.id,o),r=this.getGrandTotal(t.id);return 0===i||0===n?{value:ti.DivisionByZero}:{value:s*r/(n*i),format:void 0}}asRunningTotal(e,t,o,s,i){const{fieldNameWithGranularity:n}=s;if(!n)return e;const r="running_total"===i?this.runningTotal:this.runningTotalInPercent;let a=r[t.id]?.[n];a||(a=this.computeRunningTotal(t,n,i),r[t.id]||(r[t.id]={}),r[t.id][n]=a);const{rowDomain:l,colDomain:c}=NO(this,o),h=zO(c),d=zO(l),u=a[h]?.[d];return{value:u??"",format:"running_total"===i?e.format:DV}}asPercentOf(e,t,o,s){const{fieldNameWithGranularity:i,value:n}=s;if(void 0===n||!i)return e;if(!UO(i,o))return{value:""};const r=this.getComparisonValue(t,o,i,n),a=this.strictMeasureValueToNumber(e);return 0===r||"sameValue"===r&&0===a?{value:ti.DivisionByZero}:!r||"sameValue"===r&&!a?{value:""}:"sameValue"===r?{value:1,format:DV}:void 0===a?{value:ti.NullError}:{value:a/r,format:DV}}asDifferenceFrom(e,t,o,s){const{fieldNameWithGranularity:i,value:n}=s;if(void 0===n||!i)return e;if(!UO(i,o))return{value:""};const r=this.getComparisonValue(t,o,i,n)||0;return"sameValue"===r?{value:""}:{value:this.measureValueToNumber(e)-r,format:e.format}}asDifferenceFromInPercent(e,t,o,s){const{fieldNameWithGranularity:i,value:n}=s;if(void 0===n||!i)return e;if(!UO(i,o))return{value:""};const r=this.getComparisonValue(t,o,i,n),a=this.strictMeasureValueToNumber(e);return 0===r?{value:ti.DivisionByZero}:r&&"sameValue"!==r?void 0===a?{value:ti.NullError}:{value:(a-r)/r,format:DV}:{value:""}}asRank(e,t,o,s,i){const{fieldNameWithGranularity:n}=s;if(!n)return e;if(!UO(n,o))return{value:""};const r="asc"===i?this.rankAsc:this.rankDesc;let a=r[t.id]?.[n];a||(a=this.computeRank(t,n,i),r[t.id]||(r[t.id]={}),r[t.id][n]=a);const{rowDomain:l,colDomain:c}=NO(this,o),h=zO(c),d=zO(l),u=a[h]?.[d];return{value:u??""}}computeRank(e,t,o){const s={},i=BO(this,t),n="row"===i?"column":"row";let r=this.getPivotValueCells(e.id);"column"===i&&(r=Vi(r));for(const a of r){const r=zO(kO(this,n,a[0].domain)),l=a.map((t=>({...t,value:this.strictMeasureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain)),rowDomain:kO(this,i,t.domain)}))).filter((e=>UO(t,e.rowDomain))),c=Object.groupBy(l,(e=>GO(e.rowDomain,t)));for(const e in c)c[e]=Nt(c[e]||[],(e=>e.value)).filter((e=>void 0!==e.value)).sort(((e,t)=>"asc"===o?e.value-t.value:t.value-e.value));s[r]={};for(const e of l){const o=zO(kO(this,i,e.domain)),n=c[GO(e.rowDomain,t)];if(!n)continue;const a=n.findIndex((t=>t.value===e.value));-1!==a&&(s[r][o]=a+1)}}return"row"===i?s:kt(s)}computeRunningTotal(e,t,o){const s={},i=BO(this,t),n="row"===i?"column":"row";let r=this.getPivotValueCells(e.id);"column"===i&&(r=Vi(r));for(const a of r){const r=zO(kO(this,n,a[0].domain));s[r]={};const l={},c=a.map((t=>({...t,rowDomain:kO(this,i,t.domain),value:this.measureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain))}))).filter((e=>UO(t,e.rowDomain)));for(const e of c){const o=zO(e.rowDomain),i=WO(e.rowDomain,t),n=(l[i]||0)+e.value;l[i]=n,s[r][o]=n}if("%_running_total"===o)for(const e of c){const o=e.rowDomain,i=zO(o),n=WO(o,t),a=s[r][i]||0,c=l[n];s[r][i]=c?a/c:void 0}}return"row"===i?s:kt(s)}getGrandTotal(e){const t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){const o=NO(this,t).rowDomain,s=this._getPivotCellValueAndFormat(e,o);return this.measureValueToNumber(s)}getColumnTotal(e,t){const o=NO(this,t).colDomain,s=this._getPivotCellValueAndFormat(e,o);return this.measureValueToNumber(s)}isFieldInPivot(e){return this.definition.columns.some((t=>t.nameWithGranularity===e))||this.definition.rows.some((t=>t.nameWithGranularity===e))}getComparisonValue(e,t,o,s){const i=s===PO||s===MO?function(e,t,o,s){const i=BO(e,o),n="row"===i?e.getExpandedTableStructure().getRowTree():e.getExpandedTableStructure().getColTree(),r=LO(kO(e,i,t),n,o),a=r?.map((e=>e.value))??[],l=function(e,t){const o=t.find((t=>t.field===e));return o?.value}(o,t);if(void 0===l)return;const c=a.indexOf(l);if(void 0===l||-1===c)return;return HO(t,o,a[Ze(c+(s===PO?-1:1),0,a.length-1)])}(this,t,o,s):HO(t,o,s);if(mt(i,t))return"sameValue";if(!i||!function(e,t){for(const o of t)if(void 0===e.definition.rows.find((e=>e.nameWithGranularity===o.field))&&void 0===e.definition.columns.find((e=>e.nameWithGranularity===o.field)))return!1;const{rowDomain:o,colDomain:s}=NO(e,t);return VO(o,e.getExpandedTableStructure().getRowTree())&&VO(s,e.getExpandedTableStructure().getColTree())}(this,i))throw new ai;const n=this._getPivotCellValueAndFormat(e.id,i);return this.strictMeasureValueToNumber(n)}getPivotValueCells(e){return this.getCollapsedTableStructure().getPivotCells().map((t=>t.filter((t=>"VALUE"===t.type&&t.measure===e)))).filter((e=>e.length>0))}measureValueToNumber(e){if("number"==typeof e.value)return e.value;if(!e.value)return 0;throw new Error(`Value ${e.value} is not a number`)}strictMeasureValueToNumber(e){if("number"==typeof e.value)return e.value;if(e.value)throw new Error(`Value ${e.value} is not a number`)}getCollapsedTableStructure(){const e=super.getCollapsedTableStructure();return this.sortTableStructure(e),e}getExpandedTableStructure(){const e=super.getExpandedTableStructure();return this.sortTableStructure(e),e}sortTableStructure(e){if(!this.definition.sortedColumn||e.isSorted)return;const t=this.definition.sortedColumn.measure;Kc(this.definition.sortedColumn,this)&&e.sort(t,this.definition.sortedColumn,((e,t)=>this._getPivotCellValueAndFormat(e,t)))}}}const OV=["ADD_PIVOT","UPDATE_PIVOT","REMOVE_PIVOT"];function FV(e){return OV.includes(e.type)}const PV=new n;PV.add("ALPHANUMERIC_INCREMENT_MODIFIER",{apply:(e,t)=>{e.current+=e.increment;const o=`${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:o},tooltip:{props:{content:o}}}}}).add("INCREMENT_MODIFIER",{apply:(e,t,o)=>{e.current+=e.increment;const s=e.current.toString(),i=o.getLocale(),n=In(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:s},tooltip:s?{props:{content:n}}:void 0}}}).add("DATE_INCREMENT_MODIFIER",{apply:(e,t,o)=>{const s=Ri(e.current,o.getLocale());s.setFullYear(s.getFullYear()+e.increment.years||0),s.setMonth(s.getMonth()+e.increment.months||0),s.setDate(s.getDate()+e.increment.days||0);const i=ps(s);e.current=i;const n=o.getLocale(),r=In(i,{format:t.cell?.format,locale:n});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:i.toString()},tooltip:i?{props:{content:r}}:void 0}}}).add("COPY_MODIFIER",{apply:(e,t,o)=>{const s=t.cell?.content||"",i={locale:o.getLocale(),format:t.cell?.format};return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:s},tooltip:s?{props:{content:t.cell?Xn(t.cell,i).formattedValue:""}}:void 0}}}).add("FORMULA_MODIFIER",{apply:(e,t,o,s)=>{e.current+=e.increment;let i=0,n=0;switch(s){case"up":i=0,n=-e.current;break;case"down":i=0,n=e.current;break;case"left":i=-e.current,n=0;break;case"right":i=e.current,n=0}const r=t.cell;if(!r||!r.isFormula)return{cellData:{}};const a=t.sheetId,l=o.getTranslatedCellFormula(a,i,n,r.compiledFormula.tokens);return{cellData:{border:t.border,style:r.style,format:r.format,content:l},tooltip:l?{props:{content:l}}:void 0}}});const MV=new n,NV=/(\d+)$/,kV=/^(.*\D+)/,VV=/^(.*\D+)(\d+)$/;function LV(e,t,o){let s=[],i=!1;for(const n of t){n===e&&(i=!0);const t=void 0===n||n.isFormula?void 0:Xn(n,{locale:qs,format:n.format});if(t&&o(t))s.push(t);else{if(i)return s;s=[]}}return s}function HV(e){let t=1;return e.length>=2&&(t=function(e){const t=[];let o=e[0];for(let s=1;s<e.length;s++){const i=e[s];t.push(i-o),o=i}return t.reduce(((e,t)=>e+t),0)/t.length}(e)*e.length),t}function UV(e){if(e.length<2)return 1;const t=e.map((e=>Ri(e,qs))),o=function(e){if(e.length<2)return[{years:0,months:0,days:0}];const t=e.map(((t,o)=>{if(0===o)return{years:0,months:0,days:0};const s=Yo.fromTimestamp(e[o-1].getTime()),i=ws(s,t),n=Cs(s,t)%12;s.setFullYear(s.getFullYear()+i),s.setMonth(s.getMonth()+n);return{years:i,months:n,days:ys(s,t)}}));return t.slice(1)}(t),s=(i=o).length<2?i[0]||{years:0,months:0,days:0}:i.every((e=>e.years===i[0].years&&e.months===i[0].months&&e.days===i[0].days))?i[0]:void 0;var i;if(void 0===s)return;const n=1===Object.values(s).filter((e=>0!==e)).length,r=Object.values(s).every((e=>0===e));if(!n||r){const o=t.map(((e,o)=>{if(0===o)return 0;const s=t[o-1];return Math.floor(e.getTime())-Math.floor(s.getTime())})).slice(1);if(o.every((e=>e===o[0])))return e.length*(e[1]-e[0])}return{years:s.years*e.length,months:s.months*e.length,days:s.days*e.length}}MV.add("simple_value_copy",{condition:(e,t)=>!(1!==t.length||e.isFormula||e.format&&On(e.format)),generateRule:()=>({type:"COPY_MODIFIER"}),sequence:10}).add("increment_alphanumeric_value",{condition:e=>!e.isFormula&&Xn(e,{locale:qs}).type===_s.text&&VV.test(e.content),generateRule:(e,t,o)=>{const s=parseInt(e.content.match(NV)[0]),i=e.content.match(kV)[0],n=e.content.length-i.length,r=LV(e,t,(e=>e.type===_s.text&&VV.test(e.value))).filter((e=>i===(e.value??"").toString().match(kV)[0])).map((e=>parseInt((e.value??"").toString().match(NV)[0])));let a=HV(r);return["up","left"].includes(o)&&1===r.length&&(a=-a),{type:"ALPHANUMERIC_INCREMENT_MODIFIER",prefix:i,current:s,increment:a,numberPostfixLength:n}},sequence:15}).add("copy_text",{condition:e=>!e.isFormula&&Xn(e,{locale:qs}).type===_s.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&&Xn(e,{locale:qs}).type===_s.number&&!!e.format&&On(e.format),generateRule:(e,t)=>{const o=UV(LV(e,t,(e=>e.type===_s.number&&!!e.format&&On(e.format))).map((e=>Number(e.value))));if(void 0===o)return{type:"COPY_MODIFIER"};const s=Xn(e,{locale:qs});return"object"==typeof o?{type:"DATE_INCREMENT_MODIFIER",increment:o,current:s.type===_s.number?s.value:0}:{type:"INCREMENT_MODIFIER",increment:o,current:s.type===_s.number?s.value:0}},sequence:25}).add("increment_number",{condition:e=>!e.isFormula&&Xn(e,{locale:qs}).type===_s.number,generateRule:(e,t,o)=>{const s=LV(e,t,(e=>e.type===_s.number&&!On(e.format||""))).map((e=>Number(e.value)));let i=HV(s);["up","left"].includes(o)&&1===s.length&&(i=-i);const n=Xn(e,{locale:qs});return{type:"INCREMENT_MODIFIER",increment:i,current:n.type===_s.number?n.value:0}},sequence:40});class BV extends Mk{static layers=[];getters;ui;selection;dispatch;canDispatch;constructor({getters:e,stateObserver:t,dispatch:o,canDispatch:s,uiActions:i,selection:n}){super(t),this.getters=e,this.ui=i,this.selection=n,this.dispatch=o,this.canDispatch=s}drawLayer(e,t){}}class zV{cells;getters;index=0;direction;constructor(e,t,o){this.cells=e,this.getters=t,this.direction=o}next(){const e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:o,tooltip:s}=PV.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:o,tooltip:s,origin:{col:e.data.col,row:e.data.row}}}}const $V=new class extends n{addTransformation(e,t,o){this.content[e]||(this.content[e]=new Map);for(const s of t)this.content[e].set(s,o);return this}getTransformation(e,t){return this.content[t]&&this.content[t].get(e)}};const GV=new class extends n{add(e,t){return super.add(e,t),this}replace(e,t){return super.replace(e,t),this}get(e){return this.content[e]}};function WV(e,t){if("SPREADSHEET"!==e.pivot.type)return e;if(e.pivot.dataSet?.sheetId!==t.sheetId)return e;const o=th(e.pivot.dataSet.zone,t),s=o?{...e.pivot.dataSet,zone:o}:void 0;return{...e,pivot:{...e.pivot,dataSet:s}}}function qV(e,t){if(e.sheetId!==t.sheetId)return e;if(("FREEZE_COLUMNS"===e.type?"COL":"ROW")!==t.dimension)return e;let o=e.quantity;if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));for(const t of e)o>t&&o--}if("ADD_COLUMNS_ROWS"===t.type){o=o>("before"===t.position?t.base-1:t.base)?o+t.quantity:o}return o>0?{...e,quantity:o}:void 0}function ZV(e,t){if(e.sheetId!==t.sheetId)return e;const o=th(e.zone,t);if(!o)return;const s=e.newTableRange?oh(e.newTableRange,t):void 0;return{...e,newTableRange:s,zone:o}}function jV(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let o;if("REMOVE_COLUMNS_ROWS"===t.type)o=ha(t.elements,[e.base])[0];else if("ADD_COLUMNS_ROWS"===t.type){o=ca(pt(t.position,t.base),t.quantity,[e.base])[0]}return void 0!==o?{...e,base:o}:void 0}function YV(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;const o=je(e.start,e.end+1);let s=[];if("REMOVE_COLUMNS_ROWS"===t.type)s=ha(t.elements,o);else if("ADD_COLUMNS_ROWS"===t.type){s=ca(pt(t.position,t.base),t.quantity,o)}return 0!==s.length?{...e,start:Math.min(...s),end:Math.max(...s)}:void 0}function XV(e,t){return(e=ze(e)).pivot.measures.map((e=>{e.computedBy&&(e.computedBy.formula=WS(e.computedBy.sheetId,e.computedBy.formula,t))})),e}function KV(e,t){return{...e,definition:hx(e.sheetId,e.definition,t)}}$V.addTransformation("ADD_COLUMNS_ROWS",["ADD_COLUMNS_ROWS"],jV),$V.addTransformation("REMOVE_COLUMNS_ROWS",["ADD_COLUMNS_ROWS"],jV),$V.addTransformation("DELETE_SHEET",["MOVE_RANGES"],(function(e,t){const o=t.sheetId;if(e.targetSheetId===o||e.sheetId===o)return;return e})),$V.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART"],(function(e,t){if(e.figureId===t.figureId)return;return e})),$V.addTransformation("CREATE_SHEET",["CREATE_SHEET"],(function(e,t){e.sheetId===t.sheetId&&(e={...e,sheetId:`${e.sheetId}~`});if(e.name===t.name)return{...e,name:e.name?.match(/\d+/)?e.name.replace(/\d+/,(e=>(parseInt(e)+1).toString())):`${e.name}~`,position:e.position+1};return e})),$V.addTransformation("ADD_MERGE",["ADD_MERGE","REMOVE_MERGE"],(function(e,t){if(e.sheetId!==t.sheetId)return e;const o=[];for(const s of e.target)t.target.every((e=>!xr(s,e)))&&o.push(s);if(o.length)return{...e,target:o};return})),$V.addTransformation("ADD_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],qV),$V.addTransformation("REMOVE_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],qV),$V.addTransformation("ADD_COLUMNS_ROWS",["UPDATE_TABLE"],ZV),$V.addTransformation("REMOVE_COLUMNS_ROWS",["UPDATE_TABLE"],ZV),$V.addTransformation("REMOVE_TABLE_STYLE",["CREATE_TABLE","UPDATE_TABLE"],(function(e,t){if(e.config?.styleId!==t.tableStyleId)return e;return{...e,config:{...e.config,styleId:wR.styleId}}})),$V.addTransformation("ADD_COLUMNS_ROWS",["GROUP_HEADERS","UNGROUP_HEADERS","FOLD_HEADER_GROUP","UNFOLD_HEADER_GROUP"],YV),$V.addTransformation("REMOVE_COLUMNS_ROWS",["GROUP_HEADERS","UNGROUP_HEADERS","FOLD_HEADER_GROUP","UNFOLD_HEADER_GROUP"],YV),$V.addTransformation("REMOVE_PIVOT",["RENAME_PIVOT","DUPLICATE_PIVOT","INSERT_PIVOT","UPDATE_PIVOT"],(function(e,t){if(e.pivotId===t.pivotId)return;return e})),$V.addTransformation("DELETE_SHEET",["ADD_PIVOT","UPDATE_PIVOT"],(function(e,t){if("SPREADSHEET"!==e.pivot.type)return e;if(e.pivot.dataSet?.sheetId===t.sheetId)return{...e,pivot:{...e.pivot,dataSet:void 0}};return e})),$V.addTransformation("ADD_COLUMNS_ROWS",["ADD_PIVOT","UPDATE_PIVOT"],WV),$V.addTransformation("REMOVE_COLUMNS_ROWS",["ADD_PIVOT","UPDATE_PIVOT"],WV),GV.add("UPDATE_CELL",(function(e,t){const o=e.content&&WS(e.sheetId,e.content,t);return{...e,content:o}})),GV.add("ADD_CONDITIONAL_FORMAT",(function(e,t){const o=e.cf.rule;if(e={...e,cf:{...e.cf}},"CellIsRule"===o.type)e.cf.rule={...o,values:o.values.map((o=>WS(e.sheetId,o,t)))};else if("ColorScaleRule"===o.type){const{minimum:s,maximum:i,midpoint:n}=o;e.cf.rule={...o,minimum:{...s,value:s.value&&WS(e.sheetId,s.value,t)},maximum:{...i,value:i.value&&WS(e.sheetId,i.value,t)},midpoint:n?{...n,value:WS(e.sheetId,n.value,t)}:void 0}}else if("IconSetRule"===o.type){const{upperInflectionPoint:s,lowerInflectionPoint:i}=o;e.cf.rule={...o,upperInflectionPoint:{...s,value:WS(e.sheetId,s.value,t)},lowerInflectionPoint:{...i,value:WS(e.sheetId,i.value,t)}}}else"DataBarRule"===o.type&&(e.cf.rule={...o,rangeValues:o.rangeValues?qS(e.sheetId,o.rangeValues,t):void 0});return e})),GV.add("ADD_DATA_VALIDATION_RULE",(function(e,t){return(e={...e,rule:{...e.rule,criterion:{...e.rule.criterion}}}).rule.criterion.values=e.rule.criterion.values.map((o=>WS(e.sheetId,o,t))),e})),GV.add("ADD_PIVOT",XV),GV.add("UPDATE_PIVOT",XV),GV.add("CREATE_CHART",KV),GV.add("UPDATE_CHART",KV);const JV=[{match:function(e){return"sheetId"in e},fn:tL},{match:function(e){return"target"in e&&"sheetId"in e},fn:function(e,t){const o=tL(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;const s=[];for(const o of e.target){const e=th(o,t);e&&s.push(e)}if(!s.length)return"IGNORE_COMMAND";return{...e,target:s}}},{match:function(e){return"sheetId"in e&&"zone"in e},fn:function(e,t){const o=tL(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;const s=th(e.zone,t);if(s)return{...e,zone:s};return"IGNORE_COMMAND"}},{match:function(e){return"col"in e&&"row"in e&&"sheetId"in e},fn:function(e,t){const o=tL(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"===t.type||"REMOVE_COLUMNS_ROWS"===t.type)return function(e,t){const o="COL"===t.dimension?"col":"row";let s=e[o];if("REMOVE_COLUMNS_ROWS"===t.type){const e=[...t.elements].sort(((e,t)=>t-e));if(e.includes(s))return"IGNORE_COMMAND";for(const t of e)s>=t&&s--}"ADD_COLUMNS_ROWS"===t.type&&(s>t.base||s===t.base&&"before"===t.position)&&(s+=t.quantity);return{...e,[o]:s}}(e,t);if("ADD_MERGE"===t.type)return function(e,t){for(const o of t.target){if(!(e.col===o.left&&e.row===o.top)&&Er(e.col,e.row,o))return"IGNORE_COMMAND"}return e}(e,t);return"SKIP_TRANSFORMATION"}},{match:function(e){return"dimension"in e&&"sheetId"in e&&"elements"in e},fn:function(e,t){const o=tL(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;if("ADD_COLUMNS_ROWS"!==t.type&&"REMOVE_COLUMNS_ROWS"!==t.type)return"SKIP_TRANSFORMATION";if(t.dimension!==e.dimension)return e;let s=[];if("REMOVE_COLUMNS_ROWS"===t.type)s=ha(t.elements,e.elements);else if("ADD_COLUMNS_ROWS"===t.type){s=ca(pt(t.position,t.base),t.quantity,e.elements)}if(0===s.length)return"IGNORE_COMMAND";return{...e,elements:s}}},{match:function(e){return"ranges"in e},fn:function(e,t){if(!("sheetId"in t))return e;const o=e.ranges.map((e=>oh(e,t))).filter(lt);if(!o.length)return"IGNORE_COMMAND";return{...e,ranges:o}}}];function QV(e,t){const o=$V.getTransformation(e.type,t.type),s=o?o(e,t):function(e,t){for(const{match:o,fn:s}of JV)if(o(e)){const o=s(e,t);if("SKIP_TRANSFORMATION"===o)continue;if("IGNORE_COMMAND"===o)return;e=o}return e}(e,t);return s?function(e,t){const o=GV.get(e.type);if(!o)return e;const s=Ia(t);if(s)return o(e,s);return e}(s,t):s}function eL(e,t){let o=[...e];const s=new Set($V.getKeys());for(const e of t)(s.has(e.type)||xa.contains(e.type))&&(o=o.reduce(((t,o)=>{const s=QV(o,e);return s&&t.push(s),t}),[]));return o}function tL(e,t){if(!("sheetId"in t))return e;const o="DELETE_SHEET"===t.type&&t.sheetId;return e.sheetId===o?"IGNORE_COMMAND":"CREATE_SHEET"===e.type||"CREATE_SHEET"===t.type||e.sheetId!==t.sheetId?e:"SKIP_TRANSFORMATION"}class oL{rootCommand;timestamp;id;clientId;_commands=[];_changes=[];constructor(e,t,o,s,i,n){this.rootCommand=s,this.timestamp=n,this.id=e,this.clientId=t,this._commands=[...o],this._changes=i?[...i]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}}class sL extends Error{}class iL extends sh{revisions;transportService;serverRevisionId;clients={};clientId="local";debouncedMove;pendingMessages=[];awaitingClientPosition;waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;uuidGenerator=new Ka;lastLocalOperation;constructor(e,t,o=Se){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=o,this.debouncedMove=ht(this._move.bind(this),200)}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,o){if(!t.length||!o.length||!this.canApplyOptimisticUpdate())return;const s=new oL(this.uuidGenerator.uuidv4(),this.clientId,t,e,o,Date.now());this.revisions.append(s.id,s),"REQUEST_REDO"!==e.type&&(this.lastLocalOperation=s),this.trigger("new-local-state-update",{id:s.id}),this.sendUpdateMessage({type:"REMOTE_REVISION",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:s.id,clientId:s.clientId,commands:s.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:"REVISION_UNDONE",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:"REVISION_REDONE",version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}move(e){this.debouncedMove(e)}join(e){e?(this.clients[e.id]=e,this.clientId=e.id):(this.clients.local={id:"local",name:"local"},this.clientId="local"),this.transportService.onNewMessage(this.clientId,this.onMessageReceived.bind(this)),this.awaitingClientPosition&&(this._move(this.awaitingClientPosition),this.awaitingClientPosition=void 0)}loadInitialMessages(e){const t=performance.now(),o=e.reduce(((e,t)=>e+("REMOTE_REVISION"===t.type?t.commands.length:1)),0);this.isReplayingInitialRevisions=!0;for(const t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1,console.debug("Replayed",o,"commands in",performance.now()-t,"ms")}async leave(e){e&&1===Object.keys(this.clients).length&&this.lastRevisionMessage&&"SNAPSHOT_CREATED"!==this.lastRevisionMessage?.type&&await this.snapshot(e()),delete this.clients[this.clientId],this.transportService.leave(this.clientId),this.transportService.sendMessage({type:"CLIENT_LEFT",clientId:this.clientId,version:1})}async snapshot(e){if(0!==this.pendingMessages.length)return;const t=this.uuidGenerator.uuidv4();await this.transportService.sendMessage({type:"SNAPSHOT",nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getCurrentClient(){return this.getClient(this.clientId)}getClient(e){const t=this.clients[e];if(!t)throw new sL("The client left the session");return t}getConnectedClients(){return new Set(Object.values(this.clients).filter(lt))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return 0===this.pendingMessages.length}getLastLocalNonEmptyRevision(){return this.lastLocalOperation}_move(e){if(!this.clients[this.clientId])return void(this.awaitingClientPosition=e);const t=this.clients[this.clientId]?.position;if(t?.col===e.col&&t.row===e.row&&t.sheetId===e.sheetId)return;const o=t?"CLIENT_MOVED":"CLIENT_JOINED",s=this.getCurrentClient();this.clients[this.clientId]={...s,position:e},this.transportService.sendMessage({type:o,version:1,client:{...s,position:e}})}onMessageReceived(e){if(!this.isAlreadyProcessed(e))if(this.isWrongServerRevisionId(e))this.trigger("unexpected-revision-id");else{switch(e.type){case"CLIENT_MOVED":this.onClientMoved(e);break;case"CLIENT_JOINED":this.onClientJoined(e);break;case"CLIENT_LEFT":this.onClientLeft(e);break;case"REVISION_REDONE":this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-redone",{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case"REVISION_UNDONE":this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger("revision-undone",{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case"REMOTE_REVISION":const{clientId:t,commands:o,timestamp:s}=e,i=new oL(e.nextRevisionId,t,o,void 0,void 0,s);if(i.clientId!==this.clientId){this.revisions.insert(i.id,i,e.serverRevisionId);const t=this.pendingMessages.filter((e=>"REMOTE_REVISION"===e.type)).map((e=>e.commands)).flat();this.trigger("remote-revision-received",{commands:eL(o,t)})}break;case"SNAPSHOT_CREATED":{const t=new oL(e.nextRevisionId,"server",[],void 0,void 0,Date.now());this.revisions.insert(t.id,t,e.serverRevisionId),this.dropPendingHistoryMessages(),this.trigger("snapshot"),this.lastLocalOperation=void 0;break}}this.acknowledge(e),this.trigger("collaborative-event-received")}}onClientMoved(e){e.client.id!==this.clientId&&(this.clients[e.client.id]=e.client)}onClientJoined(e){if(e.client.id!==this.clientId){this.clients[e.client.id]=e.client;const t=this.clients[this.clientId];if(t){const{position:e}=t;e&&this.transportService.sendMessage({type:"CLIENT_MOVED",version:1,client:{...t,position:e}})}}}onClientLeft(e){e.clientId!==this.clientId&&delete this.clients[e.clientId]}sendUpdateMessage(e){this.pendingMessages.push(e),this.waitingAck||this.sendPendingMessage()}sendPendingMessage(){let e=this.pendingMessages[0];if(e){if("REMOTE_REVISION"===e.type){let t=this.revisions.get(e.nextRevisionId);0===t.commands.length&&(this.revisions.rebase(t.id),t=this.revisions.get(e.nextRevisionId)),e={...e,clientId:t.clientId,commands:t.commands}}if(this.isReplayingInitialRevisions)throw new Error(`Trying to send a new revision while replaying initial revision. This can lead to endless dispatches every time the spreadsheet is open.\n ${JSON.stringify(e)}`);this.waitingAck=!0,this.transportService.sendMessage({...e,serverRevisionId:this.serverRevisionId})}}acknowledge(e){switch("REVISION_UNDONE"!==e.type&&"REVISION_REDONE"!==e.type||(this.waitingUndoRedoAck=!1),e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"SNAPSHOT_CREATED":this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter((t=>t.nextRevisionId!==e.nextRevisionId)),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.lastRevisionMessage=e,this.sendPendingMessage();break;case"REVISION_UNDONE":{this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter((t=>t.nextRevisionId!==e.nextRevisionId));const t=this.pendingMessages.findIndex((e=>"REMOTE_REVISION"===e.type));-1!==t&&this.revisions.rebase(this.pendingMessages[t].nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.sendPendingMessage();break}}}isAlreadyProcessed(e){if("CLIENT_MOVED"===e.type&&e.client.id===this.clientId)return!0;switch(e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":case"SNAPSHOT_CREATED":return this.processedRevisions.has(e.nextRevisionId);default:return!1}}isWrongServerRevisionId(e){switch(e.type){case"REMOTE_REVISION":case"REVISION_REDONE":case"REVISION_UNDONE":case"SNAPSHOT_CREATED":return e.serverRevisionId!==this.serverRevisionId;default:return!1}}dropPendingHistoryMessages(){this.waitingUndoRedoAck=!1,this.pendingMessages=this.pendingMessages.filter((({type:e})=>"REVISION_REDONE"!==e&&"REVISION_UNDONE"!==e))}}const nL=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 rL(e){return nL.has(e.type)}const aL=[lL,function(e,t){return"target"in t&&Array.isArray(t.target)?{...ze(t),target:e.getSelectedZones()}:t},hL,function(e,t){return"ranges"in t?{...ze(t),ranges:e.getSelectedZones().map((t=>e.getRangeDataFromZone(e.getActiveSheetId(),t)))}:t}];function lL(e,t){return"sheetId"in t?{...ze(t),sheetId:e.getActiveSheetId()}:t}function cL(e,t){return"zone"in t?{...ze(t),zone:e.getSelectedZone()}:t}function hL(e,t){if(!("row"in t)||!("col"in t))return t;const{col:o,row:s}=e.getActivePosition();return{...ze(t),col:o,row:s}}const dL=new Ka;function uL(e,t){const o=e.getSelectedZone();return{...lL(e,t),elements:"COL"===t.dimension?je(o.left,o.right+1):je(o.top,o.bottom+1)}}function gL(e,t){const o=e.getSelectedZone();return{...ze(t),zone:o}}function pL(e,t){const o=ze(t),s=e.getSelectedZone(),{top:i,bottom:n,left:r,right:a}=s;return"cols"in o?o.cols=je(r,a+1):"rows"in o&&(o.rows=je(i,n+1)),o}function mL(e,t){const o=e.getSelectedZone();return{...lL(e,t),start:"COL"===t.dimension?o.left:o.top,end:"COL"===t.dimension?o.right:o.bottom}}const fL=new n;fL.add("UPDATE_CELL",bL),fL.add("CLEAR_CELL",bL),fL.add("CLEAR_CELLS",bL),fL.add("DELETE_CONTENT",bL),fL.add("ADD_MERGE",bL),fL.add("REMOVE_MERGE",bL),fL.add("SET_FORMATTING",bL),fL.add("CLEAR_FORMATTING",bL),fL.add("SET_BORDER",bL),fL.add("CREATE_TABLE",bL),fL.add("REMOVE_TABLE",bL),fL.add("HIDE_SHEET",bL),fL.add("ADD_COLUMNS_ROWS",(function(e,t){const o=e.getActivePosition();return{...lL(e,t),base:"COL"===t.dimension?o.col:o.row}})),fL.add("REMOVE_COLUMNS_ROWS",uL),fL.add("HIDE_COLUMNS_ROWS",uL),fL.add("RESIZE_COLUMNS_ROWS",uL),fL.add("CREATE_SHEET",(function(e,t){const o=ze(t);o.sheetId=dL.smallUuid();const s=t.name||e.getSheet(e.getActiveSheetId()).name,i=s.match(/(.+?)\d*$/)?.[1]||s;return o.name=e.getNextSheetName(i),o})),fL.add("CREATE_FIGURE",(function(e,t){const o=hL(e,lL(e,t));return o.figureId=dL.smallUuid(),o})),fL.add("CREATE_CHART",(function(e,t){return{...lL(e,t),figureId:dL.smallUuid()}})),fL.add("CREATE_IMAGE",(function(e,t){return{...lL(e,t),figureId:dL.smallUuid()}})),fL.add("GROUP_HEADERS",mL),fL.add("UNGROUP_HEADERS",mL),fL.add("UNFOLD_HEADER_GROUPS_IN_ZONE",cL),fL.add("FOLD_HEADER_GROUPS_IN_ZONE",cL);const vL=new n;function bL(e,t){let o=ze(t);for(const t of aL)o=t(e,o);return o}function SL(e,t){if(e.rootCommand&&"object"==typeof e.rootCommand)return Hs(e.rootCommand)?function(e,t){if(!t)return;if(!fL.contains(t.type))return;return fL.get(t.type)(e,t)}(t,e.rootCommand):function(e,t,o){if(!vL.contains(t.type))return;return vL.get(t.type)(e,t,o)}(t,e.rootCommand,e.commands)}vL.add("PASTE",(function(e,t){return{type:"REPEAT_PASTE",pasteOption:ze(t.pasteOption),target:e.getSelectedZones()}})),vL.add("INSERT_CELL",gL),vL.add("DELETE_CELL",gL),vL.add("AUTORESIZE_COLUMNS",pL),vL.add("AUTORESIZE_ROWS",pL),vL.add("SORT_CELLS",(function(e,t){const o=e.getSelectedZone();return{...lL(e,t),col:o.left,row:o.top,zone:o}})),vL.add("SUM_SELECTION",bL),vL.add("SET_DECIMAL",bL),vL.add("DELETE_UNFILTERED_CONTENT",bL);class CL{trackedValues=new Set;domainToArray(e){return e.flatMap((e=>[e.field,wi(e.value)]))}isValuePresent(e,t){const o=JSON.stringify({measure:e,domain:this.domainToArray(t)});return this.trackedValues.has(o)}isHeaderPresent(e){const t=JSON.stringify({domain:this.domainToArray(e)});return this.trackedValues.has(t)}trackValue(e,t){const o=JSON.stringify({measure:e,domain:this.domainToArray(t)});this.trackedValues.add(o)}trackHeader(e){const t=JSON.stringify({domain:this.domainToArray(e)});this.trackedValues.add(t)}}const yL=5242880;const wL={filterType:"criterion",type:"none",values:[]};class IL{getters;sheetId;boundaries;top;bottom;left;right;offsetX;offsetY;canScrollVertically;canScrollHorizontally;viewportWidth;viewportHeight;offsetCorrectionX;offsetCorrectionY;constructor(e,t,o,s,i,n){if(this.getters=e,this.sheetId=t,this.boundaries=o,s.width<0||s.height<0)throw new Error("Viewport size cannot be negative");this.viewportWidth=s.height&&s.width,this.viewportHeight=s.width&&s.height,this.top=o.top,this.bottom=o.bottom,this.left=o.left,this.right=o.right,this.offsetX=n.x,this.offsetY=n.y,this.canScrollVertically=i.canScrollVertically,this.canScrollHorizontally=i.canScrollHorizontally,this.offsetCorrectionX=this.getters.getColDimensions(this.sheetId,this.boundaries.left).start,this.offsetCorrectionY=this.getters.getRowDimensions(this.sheetId,this.boundaries.top).start,this.adjustViewportOffsetX(),this.adjustViewportOffsetY()}getMaxSize(){const e=this.getters.findLastVisibleColRowIndex(this.sheetId,"COL",{first:this.boundaries.left,last:this.boundaries.right}),t=this.getters.findLastVisibleColRowIndex(this.sheetId,"ROW",{first:this.boundaries.top,last:this.boundaries.bottom}),{end:o}=this.getters.getColDimensions(this.sheetId,e),{end:s}=this.getters.getRowDimensions(this.sheetId,t);let i=o-this.offsetCorrectionX;this.canScrollHorizontally&&(i=Math.max(i,this.viewportWidth));let n=s-this.offsetCorrectionY;return this.canScrollVertically&&(n=Math.max(n,this.viewportHeight),s+he>n&&!this.getters.isReadonly()&&(n+=he)),{width:i,height:n}}getColIndex(e){return e<this.offsetCorrectionX||e>this.offsetCorrectionX+this.viewportWidth?-1:this.searchHeaderIndex("COL",e-this.offsetCorrectionX+this.snapCorrection.x,this.left)}getRowIndex(e){return e<this.offsetCorrectionY||e>this.offsetCorrectionY+this.viewportHeight?-1:this.searchHeaderIndex("ROW",e-this.offsetCorrectionY+this.snapCorrection.y,this.top)}adjustPosition(e){const t=this.sheetId,o=this.getters.getMainCellPosition({sheetId:t,...e}),{col:s,row:i}=this.getters.getNextVisibleCellPosition(o);Er(s,this.boundaries.top,this.boundaries)&&this.adjustPositionX(s),Er(this.boundaries.left,i,this.boundaries)&&this.adjustPositionY(i)}adjustPositionX(e){const t=this.sheetId,{start:o,end:s}=this.getters.getColDimensions(t,e);this.offsetX+this.viewportWidth+this.offsetCorrectionX<s?this.offsetX=s-this.viewportWidth:this.offsetX+this.offsetCorrectionX>o&&(this.offsetX=o-this.offsetCorrectionX),this.adjustViewportZoneX()}adjustPositionY(e){const t=this.sheetId,{start:o,end:s}=this.getters.getRowDimensions(t,e);this.offsetY+this.viewportHeight+this.offsetCorrectionY<s?this.offsetY=s-this.viewportHeight:this.offsetY+this.offsetCorrectionY>o&&(this.offsetY=o-this.offsetCorrectionY),this.adjustViewportZoneY()}willNewOffsetScrollViewport(e,t){return this.canScrollHorizontally&&this.offsetX!==e||this.canScrollVertically&&this.offsetY!==t}setViewportOffset(e,t){this.setViewportOffsetX(e),this.setViewportOffsetY(t)}adjustViewportZone(){this.adjustViewportZoneX(),this.adjustViewportZoneY()}getVisibleRect(e){const t=wr(e,this),o=this.snapCorrection.x,s=this.snapCorrection.y;if(t){return{x:this.getters.getColRowOffset("COL",this.left,t.left)+this.offsetCorrectionX-(this.left!==t.left?o:0),y:this.getters.getColRowOffset("ROW",this.top,t.top)+this.offsetCorrectionY-(this.top!==t.top?s:0),width:Math.min(this.getters.getColRowOffset("COL",t.left,t.right+1)-(this.left===t.left?o:0),this.viewportWidth),height:Math.min(this.getters.getColRowOffset("ROW",t.top,t.bottom+1)-(this.top===t.top?s:0),this.viewportHeight)}}}getFullRect(e){const t=wr(e,this.boundaries),o=this.snapCorrection.x,s=this.snapCorrection.y;if(t){return{x:this.getters.getColRowOffset("COL",this.left,e.left)+this.offsetCorrectionX-o,y:this.getters.getColRowOffset("ROW",this.top,e.top)+this.offsetCorrectionY-s,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,o=0){if(this.viewportWidth<=0||this.viewportHeight<=0)return-1;const s=this.sheetId,i=this.getters.getNumberHeaders(s,e);let n=o,r=i;for(;n<=r&&n!==i&&-1!==r;){const i=Math.floor((n+r)/2),a=this.getters.getColRowOffset(e,o,i),l=this.getters.getHeaderSize(s,e,i);if(t>=a&&t<a+l)return i;t>=a+l?n=i+1:r=i-1}return-1}setViewportOffsetX(e){this.canScrollHorizontally&&(this.offsetX=e,this.adjustViewportZoneX())}setViewportOffsetY(e){this.canScrollVertically&&(this.offsetY=e,this.adjustViewportZoneY())}adjustViewportOffsetX(){if(this.canScrollHorizontally){const{width:e}=this.getMaxSize();this.viewportWidth+this.offsetX>e&&(this.offsetX=Math.max(0,e-this.viewportWidth))}this.adjustViewportZoneX()}adjustViewportOffsetY(){if(this.canScrollVertically){const{height:e}=this.getMaxSize();this.viewportHeight+this.offsetY>e&&(this.offsetY=Math.max(0,e-this.viewportHeight))}this.adjustViewportZoneY()}adjustViewportZoneX(){this.left=this.searchHeaderIndex("COL",this.offsetX,this.boundaries.left),this.right=Math.min(this.boundaries.right,this.searchHeaderIndex("COL",Math.max(this.viewportWidth+this.snapCorrection.x-.1),this.left)),this.viewportWidth&&(-1===this.left&&(this.left=this.boundaries.left),-1===this.right&&(this.right=this.boundaries.right))}adjustViewportZoneY(){this.top=this.searchHeaderIndex("ROW",this.offsetY,this.boundaries.top),this.bottom=Math.min(this.boundaries.bottom,this.searchHeaderIndex("ROW",Math.max(this.viewportHeight+this.snapCorrection.y-.1,0),this.top)),this.viewportHeight&&(-1===this.top&&(this.top=this.boundaries.top),-1===this.bottom&&(this.bottom=this.boundaries.bottom))}get snapCorrection(){return{x:Math.abs(this.offsetX-this.getters.getColRowOffset("COL",this.boundaries.left,Math.max(0,this.left))),y:Math.abs(this.offsetY-this.getters.getColRowOffset("ROW",this.boundaries.top,Math.max(0,this.top)))}}}const xL=(new n).add("settings",class extends Nk{static getters=["getLocale"];locale=qs;allowDispatch(e){return"UPDATE_LOCALE"===e.type?El(e.locale)?"Success":"InvalidLocale":"Success"}handle(e){if("UPDATE_LOCALE"===e.type){const t=this.locale,o=e.locale;this.history.update("locale",o),this.changeCellsDateFormatWithLocale(t,o)}}getLocale(){return this.locale}changeCellsDateFormatWithLocale(e,t){for(const o of this.getters.getSheetIds())for(const[s,i]of Object.entries(this.getters.getCells(o))){let o;if(i.format===e.dateFormat&&(o=t.dateFormat),i.format===e.timeFormat&&(o=t.timeFormat),i.format===Hl(e)&&(o=Hl(t)),o){const{col:e,row:t,sheetId:i}=this.getters.getCellPosition(s);this.dispatch("UPDATE_CELL",{col:e,row:t,sheetId:i,format:o})}}}import(e){this.locale=e.settings?.locale??qs}export(e){e.settings={locale:this.locale}}}).add("sheet",class extends Nk{static getters=["getSheetName","tryGetSheetName","getSheet","tryGetSheet","getSheetIdByName","getSheetIds","getVisibleSheetIds","isSheetVisible","doesHeaderExist","doesHeadersExist","getCell","getCellPosition","getColsZone","getRowCells","getRowsZone","getNumberCols","getNumberRows","getNumberHeaders","getGridLinesVisibility","getNextSheetName","getSheetSize","getSheetZone","getPaneDivisions","checkZonesExistInSheet","getCommandZones","getUnboundedZone","checkElementsIncludeAllNonFrozenHeaders","getDuplicateSheetName"];sheetIdsMapName={};orderedSheetIds=[];sheets={};cellPosition={};allowDispatch(e){const t=this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e);if("Success"!==t)return t;switch(e.type){case"HIDE_SHEET":return 1===this.getVisibleSheetIds().length?"NotEnoughSheets":"Success";case"CREATE_SHEET":return this.checkValidations(e,this.checkSheetName,this.checkSheetPosition);case"DUPLICATE_SHEET":return this.sheets[e.sheetIdTo]?"DuplicatedSheetId":this.orderedSheetIds.map(this.getSheetName.bind(this)).includes(e.sheetNameTo)?"DuplicatedSheetName":"Success";case"MOVE_SHEET":try{const t=this.orderedSheetIds.findIndex((t=>t===e.sheetId));return this.findIndexOfTargetSheet(t,e.delta),"Success"}catch(e){return"WrongSheetMove"}case"RENAME_SHEET":return this.isRenameAllowed(e);case"COLOR_SHEET":return!e.color||Wt(e.color)?"Success":"InvalidColor";case"DELETE_SHEET":return this.getVisibleSheetIds().length>1?"Success":"NotEnoughSheets";case"ADD_COLUMNS_ROWS":return this.doesHeaderExist(e.sheetId,e.dimension,e.base)?e.quantity<=0?"InvalidQuantity":"Success":"InvalidHeaderIndex";case"REMOVE_COLUMNS_ROWS":{const t=Pt(e.elements),o=Ft(e.elements);return t<0||!this.doesHeaderExist(e.sheetId,e.dimension,o)?"InvalidHeaderIndex":this.checkElementsIncludeAllNonFrozenHeaders(e.sheetId,e.dimension,e.elements)?"NotEnoughElements":"Success"}case"FREEZE_ROWS":return this.checkValidations(e,this.checkRowFreezeQuantity,this.checkRowFreezeOverlapMerge);case"FREEZE_COLUMNS":return this.checkValidations(e,this.checkColFreezeQuantity,this.checkColFreezeOverlapMerge);default:return"Success"}}handle(e){switch(e.type){case"SET_GRID_LINES_VISIBILITY":this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);break;case"CREATE_SHEET":const t=this.createSheet(e.sheetId,e.name||this.getNextSheetName(),e.cols||26,e.rows||100,e.position);this.history.update("sheetIdsMapName",t.name,t.id);break;case"MOVE_SHEET":this.moveSheet(e.sheetId,e.delta);break;case"RENAME_SHEET":this.renameSheet(this.sheets[e.sheetId],e.newName);break;case"COLOR_SHEET":this.history.update("sheets",e.sheetId,"color",e.color);break;case"HIDE_SHEET":this.hideSheet(e.sheetId);break;case"SHOW_SHEET":this.showSheet(e.sheetId);break;case"DUPLICATE_SHEET":this.duplicateSheet(e.sheetId,e.sheetIdTo,e.sheetNameTo);break;case"DELETE_SHEET":this.deleteSheet(this.sheets[e.sheetId]);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case"UPDATE_CELL_POSITION":this.updateCellPosition(e);break;case"FREEZE_COLUMNS":this.setPaneDivisions(e.sheetId,e.quantity,"COL");break;case"FREEZE_ROWS":this.setPaneDivisions(e.sheetId,e.quantity,"ROW");break;case"UNFREEZE_ROWS":this.setPaneDivisions(e.sheetId,0,"ROW");break;case"UNFREEZE_COLUMNS":this.setPaneDivisions(e.sheetId,0,"COL");break;case"UNFREEZE_COLUMNS_ROWS":this.setPaneDivisions(e.sheetId,0,"COL"),this.setPaneDivisions(e.sheetId,0,"ROW")}}import(e){for(const t of e.sheets)this.sheetIdsMapName[t.name]=t.id;for(const t of e.sheets){const e=t.name||"Sheet"+(Object.keys(this.sheets).length+1),{colNumber:o,rowNumber:s}=this.getImportedSheetSize(t),i={id:t.id,name:e,numberOfCols:o,rows:la(s),areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible,isVisible:t.isVisible,panes:{xSplit:t.panes?.xSplit||0,ySplit:t.panes?.ySplit||0},color:t.color};this.orderedSheetIds.push(i.id),this.sheets[i.id]=i}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(lt).map((e=>{const t=this.sheets[e],o={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},styles:{},formats:{},borders:{},conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],areGridLinesVisible:void 0===t.areGridLinesVisible||t.areGridLinesVisible,isVisible:t.isVisible,color:t.color};return(t.panes.xSplit||t.panes.ySplit)&&(o.panes=t.panes),o}))}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}tryGetSheet(e){return this.sheets[e]}getSheet(e){const t=this.sheets[e];if(!t)throw new Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){return this.tryGetSheet(e)?.name}getSheetIdByName(e){if(e){const t=$e(e);for(const e in this.sheetIdsMapName)if(ga(e,t))return this.sheetIdsMapName[e]}}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}doesHeaderExist(e,t,o){return"COL"===t?o>=0&&o<this.getNumberCols(e):o>=0&&o<this.getNumberRows(e)}doesHeadersExist(e,t,o){return o.every((o=>this.doesHeaderExist(e,t,o)))}getCell({sheetId:e,col:t,row:o}){const s=this.tryGetSheet(e),i=s?.rows[o]?.cells[t];if(void 0!==i)return this.getters.getCellById(i)}getColsZone(e,t,o){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:o}}getRowCells(e,t){return Object.values(this.getSheet(e).rows[t]?.cells).filter(lt)}getRowsZone(e,t,o){return{top:t,bottom:o,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){const t=this.cellPosition[e];if(!t)throw new Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return"COL"===t?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e="Sheet"){return da(this.orderedSheetIds.map(this.getSheetName.bind(this)),e)}getSheetSize(e){return{numberOfRows:this.getNumberRows(e),numberOfCols:this.getNumberCols(e)}}getSheetZone(e){return{top:0,left:0,bottom:this.getNumberRows(e)-1,right:this.getNumberCols(e)-1}}getUnboundedZone(e,t){if(void 0===t.bottom||void 0===t.right)return t;const o=0===t.left&&t.right===this.getNumberCols(e)-1,s=0===t.top&&t.bottom===this.getNumberRows(e)-1;return{...t,bottom:s?void 0:t.bottom,right:o&&!s?void 0:t.right}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,o){const s={...this.getPaneDivisions(e)};"COL"===o?s.xSplit=t:"ROW"===o&&(s.ySplit=t),this.history.update("sheets",e,"panes",s)}checkElementsIncludeAllNonFrozenHeaders(e,t,o){const s=this.getters.getPaneDivisions(e),i="ROW"===t?s.ySplit:s.xSplit,n=this.getters.getNumberHeaders(e,t);if(!i)return!1;return vt(o,je(i,n))}getCommandZones(e){const t=[];return"zone"in e&&t.push(e.zone),"target"in e&&t.push(...e.target),"ranges"in e&&t.push(...e.ranges.map((e=>this.getters.getRangeFromRangeData(e).zone))),"col"in e&&void 0!==e.col&&"row"in e&&void 0!==e.row&&t.push({top:e.row,left:e.col,bottom:e.row,right:e.col}),t}checkZonesExistInSheet(e,t){if(!t.every(pr))return"InvalidRange";if(t.length){const o=this.getSheetZone(e);return t.every((e=>Rr(e,o)))?"Success":"TargetOutOfSheet"}return"Success"}updateCellPosition(e){const{sheetId:t,cellId:o,col:s,row:i}=e;o?this.setNewPosition(o,t,s,i):this.clearPosition(t,s,i)}setNewPosition(e,t,o,s){const i=this.cellPosition[e];i&&this.clearPosition(t,i.col,i.row),this.history.update("cellPosition",e,{row:s,col:o,sheetId:t}),this.history.update("sheets",t,"rows",s,"cells",o,e)}clearPosition(e,t,o){const s=this.sheets[e]?.rows[o].cells[t];s&&(this.history.update("cellPosition",s,void 0),this.history.update("sheets",e,"rows",o,"cells",t,void 0))}setGridLinesVisibility(e,t){this.history.update("sheets",e,"areGridLinesVisible",t)}createSheet(e,t,o,s,i){const n={id:e,name:t,numberOfCols:o,rows:la(s),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0}},r=this.orderedSheetIds.slice();r.splice(i,0,n.id);const a=this.sheets;return this.history.update("orderedSheetIds",r),this.history.update("sheets",Object.assign({},a,{[n.id]:n})),n}moveSheet(e,t){const o=this.orderedSheetIds.slice(),s=o.findIndex((t=>t===e)),i=o.splice(s,1),n=this.findIndexOfTargetSheet(s,t);o.splice(n,0,i[0]),this.history.update("orderedSheetIds",o)}findIndexOfTargetSheet(e,t){for(;0!==t&&0<=e&&e<=this.orderedSheetIds.length;)t>0?(e++,this.isSheetVisible(this.orderedSheetIds[e])&&t--):t<0&&(e--,this.isSheetVisible(this.orderedSheetIds[e])&&t++);if(0===t)return e;throw new Error("There is not enough visible sheets")}checkSheetName(e){const t=this.getters.tryGetSheetName(e.sheetId),o="RENAME_SHEET"===e.type?e.newName:e.name;if(void 0!==t&&o===t)return"UnchangedSheetName";const{orderedSheetIds:s,sheets:i}=this,n=o&&o.trim().toLowerCase();return s.find((t=>ga(i[t]?.name,n)&&t!==e.sheetId))?"DuplicatedSheetName":_e.test(n)?"ForbiddenCharactersInSheetName":"Success"}checkSheetPosition(e){const{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?"WrongSheetPosition":"Success"}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?"Success":"InvalidFreezeQuantity"}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?"Success":"InvalidFreezeQuantity"}checkRowFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(const o of t)if(o.top<e.quantity&&e.quantity<=o.bottom)return"MergeOverlap";return"Success"}checkColFreezeOverlapMerge(e){const t=this.getters.getMerges(e.sheetId);for(const o of t)if(o.left<e.quantity&&e.quantity<=o.right)return"MergeOverlap";return"Success"}isRenameAllowed(e){return e.newName&&e.newName.trim().toLowerCase()?this.checkSheetName(e):"MissingSheetName"}renameSheet(e,t){const o=e.name;this.history.update("sheets",e.id,"name",t.trim());const s=Object.assign({},this.sheetIdsMapName);delete s[o],s[t]=e.id,this.history.update("sheetIdsMapName",s)}hideSheet(e){this.history.update("sheets",e,"isVisible",!1)}showSheet(e){this.history.update("sheets",e,"isVisible",!0)}duplicateSheet(e,t,o){const s=ze(this.getSheet(e));s.id=t,s.name=o;for(let e=0;e<=s.numberOfCols;e++)for(let t=0;t<=s.rows.length;t++)s.rows[t]&&(s.rows[t].cells[e]=void 0);const i=this.orderedSheetIds.slice(),n=i.indexOf(e);i.splice(n+1,0,s.id),this.history.update("orderedSheetIds",i),this.history.update("sheets",Object.assign({},this.sheets,{[s.id]:s}));for(const t of Object.values(this.getters.getCells(e))){const{col:e,row:o}=this.getCellPosition(t.id);this.dispatch("UPDATE_CELL",{sheetId:s.id,col:e,row:o,content:t.content,format:t.format,style:t.style})}const r=Object.assign({},this.sheetIdsMapName);r[s.name]=s.id,this.history.update("sheetIdsMapName",r)}getDuplicateSheetName(e){return ua(e,this.orderedSheetIds.map(this.getSheetName.bind(this)))}deleteSheet(e){const t=e.name,o=Object.assign({},this.sheets);delete o[e.id],this.history.update("sheets",o);const s=this.orderedSheetIds.slice(),i=s.indexOf(e.id);s.splice(i,1),this.history.update("orderedSheetIds",s);const n=Object.assign({},this.sheetIdsMapName);delete n[t],this.history.update("sheetIdsMapName",n)}removeColumns(e,t){t.sort(((e,t)=>t-e));for(const o of t)this.moveCellOnColumnsDeletion(e,o);const o=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",o-t.length);const s=t.filter((t=>t<e.panes.xSplit)).length;s&&this.setPaneDivisions(e.id,e.panes.xSplit-s,"COL")}removeRows(e,t){t.sort(((e,t)=>t-e));for(const o of Ye(t)){const t=o[o.length-1],s=o[0];this.moveCellOnRowsDeletion(e,t,s),this.updateRowsStructureOnDeletion(e,t,s)}const o=t.filter((t=>t<e.panes.ySplit)).length;o&&this.setPaneDivisions(e.id,e.panes.ySplit-o,"ROW")}addColumns(e,t,o,s){const i="before"===o?t:t+1;this.moveCellsOnAddition(e,i,s,"columns");const n=this.sheets[e.id].numberOfCols;this.history.update("sheets",e.id,"numberOfCols",n+s),i<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+s,"COL")}addRows(e,t,o,s){const i="before"===o?t:t+1;this.addEmptyRows(e,s),this.moveCellsOnAddition(e,i,s,"rows"),i<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+s,"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 o=0;o<e.rows.length;o++){const s=e.rows[o];for(const i in s.cells){const n=Number(i),r=s.cells[i];r&&n>t&&this.setNewPosition(r,e.id,n-1,o)}}}moveCellsOnAddition(e,t,o,s){const i=[];for(let n=0;n<e.rows.length;n++){const r=e.rows[n];if("rows"!==s||n>=t)for(const a in r.cells){const l=Number(a),c=r.cells[a];c&&("rows"===s||l>=t)&&i.push({sheetId:e.id,cellId:c,col:l+("columns"===s?o:0),row:n+("rows"===s?o:0),type:"UPDATE_CELL_POSITION"})}}for(const e of i.reverse())this.updateCellPosition(e)}moveCellOnRowsDeletion(e,t,o){this.dispatch("CLEAR_CELLS",{sheetId:e.id,target:[{left:0,top:t,right:this.getters.getNumberCols(e.id),bottom:o}]});const s=o-t+1;for(let t=0;t<e.rows.length;t++){const i=e.rows[t];if(t>o)for(const o in i.cells){const n=Number(o),r=i.cells[o];r&&this.setNewPosition(r,e.id,n,t-s)}}}updateRowsStructureOnDeletion(e,t,o){const s=[],i=e.rows.map((e=>e.cells)).reverse();for(const n in e.rows){const e=Number(n);e>=t&&e<=o||s.push({cells:i.pop()})}this.history.update("sheets",e.id,"rows",s)}addEmptyRows(e,t){const o=e.rows.slice();for(let e=0;e<t;e++)o.push({cells:{}});this.history.update("sheets",e.id,"rows",o)}getImportedSheetSize(e){const t=Object.keys(e.cells).map(Fo);let o=e.rowNumber,s=e.colNumber;for(const{col:e,row:i}of t)o=Math.max(o,i+1),s=Math.max(s,e+1);return{rowNumber:o,colNumber:s}}checkSheetExists(e){return"CREATE_SHEET"!==e.type&&"sheetId"in e&&void 0===this.sheets[e.sheetId]?"InvalidSheetId":"CREATE_SHEET"===e.type&&void 0!==this.sheets[e.sheetId]?"DuplicatedSheetId":"Success"}checkZonesAreInSheet(e){return"sheetId"in e?"ranges"in e&&e.ranges.some((e=>""!==e._sheetId&&!this.getters.tryGetSheet(e._sheetId)))?"InvalidSheetId":this.checkZonesExistInSheet(e.sheetId,this.getCommandZones(e)):"Success"}}).add("header grouping",class extends Nk{static getters=["getHeaderGroups","getGroupsLayers","getVisibleGroupLayers","getHeaderGroup","getHeaderGroupsInZone","isGroupFolded","isRowFolded","isColFolded"];groups={};allowDispatch(e){switch(e.type){case"GROUP_HEADERS":{const{start:t,end:o,sheetId:s}=e;if(!this.getters.tryGetSheet(s))return"InvalidSheetId";if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,o]))return"InvalidHeaderGroupStartEnd";if(t>o)return"InvalidHeaderGroupStartEnd";if(this.findGroupWithStartEnd(e.sheetId,e.dimension,t,o))return"HeaderGroupAlreadyExists";break}case"UNGROUP_HEADERS":{const{start:t,end:o,sheetId:s}=e;if(!this.getters.tryGetSheet(s))return"InvalidSheetId";if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,o]))return"InvalidHeaderGroupStartEnd";if(t>o)return"InvalidHeaderGroupStartEnd";break}case"UNFOLD_HEADER_GROUP":case"FOLD_HEADER_GROUP":if(!this.getters.tryGetSheet(e.sheetId))return"InvalidSheetId";const t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);if(!t)return"UnknownHeaderGroup";if(je(0,this.getters.getNumberHeaders(e.sheetId,e.dimension)).every((o=>o>=t.start&&o<=t.end||this.getters.isHeaderHiddenByUser(e.sheetId,e.dimension,o))))return"NotEnoughElements"}return"Success"}handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("groups",e.sheetId,{ROW:[],COL:[]});break;case"GROUP_HEADERS":this.groupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case"UNGROUP_HEADERS":this.unGroupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case"DUPLICATE_SHEET":{const t=ze(this.groups[e.sheetId]);this.history.update("groups",e.sheetIdTo,t);break}case"DELETE_SHEET":{const t={...this.groups};delete t[e.sheetId],this.history.update("groups",t);break}case"ADD_COLUMNS_ROWS":const t=pt(e.position,e.base);this.moveGroupsOnHeaderInsertion(e.sheetId,e.dimension,t,e.quantity);break;case"REMOVE_COLUMNS_ROWS":this.moveGroupsOnHeaderDeletion(e.sheetId,e.dimension,e.elements);break;case"UNFOLD_HEADER_GROUP":{const t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.unfoldHeaderGroup(e.sheetId,e.dimension,t);break}case"FOLD_HEADER_GROUP":{const t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.foldHeaderGroup(e.sheetId,e.dimension,t);break}case"UNFOLD_ALL_HEADER_GROUPS":{const t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(const o of t)this.unfoldHeaderGroup(e.sheetId,e.dimension,o);break}case"FOLD_ALL_HEADER_GROUPS":{const t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(const o of t)this.foldHeaderGroup(e.sheetId,e.dimension,o);break}case"FOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_HEADER_GROUPS_IN_ZONE":{const t="UNFOLD_HEADER_GROUPS_IN_ZONE"===e.type?"unfold":"fold",o=this.getGroupsLayers(e.sheetId,e.dimension);"fold"===t&&o.reverse();const s=o.flat(),i="ROW"===e.dimension?e.zone.top:e.zone.left,n="ROW"===e.dimension?e.zone.bottom:e.zone.right,r=new Set;for(let e=i;e<=n;e++){const o=s.filter((t=>t.start-1<=e&&e<=t.end));for(const e of o)if(!("fold"===t&&e.isFolded||"unfold"===t&&!e.isFolded)){r.add(e);break}}for(const o of r)"unfold"===t?this.unfoldHeaderGroup(e.sheetId,e.dimension,o):this.foldHeaderGroup(e.sheetId,e.dimension,o);break}}}getHeaderGroups(e,t){return this.groups[e][t]}getHeaderGroup(e,t,o,s){return this.getHeaderGroups(e,t).find((e=>e.start===o&&e.end===s))}getHeaderGroupsInZone(e,t,o){return this.getHeaderGroups(e,t).filter((e=>{const s="ROW"===t?o.top:o.left,i="ROW"===t?o.bottom:o.right;return this.doGroupOverlap(e,s,i)}))}getGroupsLayers(e,t){const o=this.getHeaderGroups(e,t);return this.bricksFallingAlgorithm(o,0,0)}getVisibleGroupLayers(e,t){const o=this.getGroupsLayers(e,t);for(const s of o)for(let o=s.length-1;o>=0;o--){const i=s[o];if(0===i.start)continue;je(i.start-1,i.end+1).every((o=>this.getters.isHeaderHiddenByUser(e,t,o)))&&s.splice(o,1)}return o.filter((e=>e.length>0))}isGroupFolded(e,t,o,s){return this.getHeaderGroup(e,t,o,s)?.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,o,s=0){const i={};for(const t of e)i[this.getGroupId(t)]=t.isFolded;const n={};for(const t of e)for(let e=t.start;e<=t.end;e++)n[e]=n[e]?n[e]+1:1;for(let e=t;e<=o;e++)n[e]=n[e]?n[e]+s:s;const r=Math.max(...Object.values(n),0),a=Array.from({length:r},(()=>[])),l=Math.max(o,...e.map((e=>e.end)));for(let o=Math.min(t,...e.map((e=>e.start)));o<=l;o++){const e=n[o]||0;for(let t=0;t<e;t++){const e=a[t].at(-1);if(e&&xt([e.end,o]))e.end++;else{const e={start:o,end:o};a[t].push(e)}}}for(const e of a)for(const t of e)t.isFolded=i[this.getGroupId(t)];return a}groupHeaders(e,t,o,s){const i=this.getHeaderGroups(e,t),n=this.bricksFallingAlgorithm(i,o,s,1).flat();this.history.update("groups",e,t,this.removeDuplicateGroups(n))}unGroupHeaders(e,t,o,s){const i=this.getHeaderGroups(e,t),n=this.bricksFallingAlgorithm(i,o,s,-1).flat();this.history.update("groups",e,t,this.removeDuplicateGroups(n))}moveGroupsOnHeaderInsertion(e,t,o,s){const i=this.groups[e][t];for(let n=0;n<i.length;n++){const r=i[n],[a,l]=ca(o,s,[r.start,r.end]);a===r.start&&l===r.end||this.history.update("groups",e,t,n,{...r,start:a,end:l})}}moveGroupsOnHeaderDeletion(e,t,o){const s=this.getHeaderGroups(e,t),i=[];for(const e of s){const t=ha(o,je(e.start,e.end+1));0!==t.length&&i.push({...e,start:Math.min(...t),end:Math.max(...t)})}this.history.update("groups",e,t,this.bricksFallingAlgorithm(i,0,0).flat())}doGroupOverlap(e,t,o){return e.start<=o&&e.end>=t}removeDuplicateGroups(e){const t={};for(const o of e)t[this.getGroupId(o)]=o;return Object.values(t)}findGroupWithStartEnd(e,t,o,s){return this.getHeaderGroups(e,t).find((e=>e.start===o&&e.end===s))}foldHeaderGroup(e,t,o){const s=this.getGroupIndex(e,t,o.start,o.end);if(void 0===s)return;this.history.update("groups",e,t,s,"isFolded",!0);const i=this.getters.getHeaderGroups(e,t);for(let s=0;s<i.length;s++){const n=i[s];n.start===o.start&&n.end<=o.end&&this.history.update("groups",e,t,s,"isFolded",!0)}}unfoldHeaderGroup(e,t,o){const s=this.getGroupIndex(e,t,o.start,o.end);if(void 0===s)return;this.history.update("groups",e,t,s,"isFolded",!1);const i=this.getters.getHeaderGroups(e,t);for(let s=0;s<i.length;s++){const n=i[s];n.start===o.start&&n.end>=o.end&&this.history.update("groups",e,t,s,"isFolded",!1)}}getGroupIndex(e,t,o,s){const i=this.groups[e][t].findIndex((e=>e.start===o&&e.end===s));return-1===i?void 0:i}import(e){for(const t of e.sheets)if(this.groups[t.id]={ROW:[],COL:[]},t.headerGroups)for(const e of["ROW","COL"])for(const o of t.headerGroups[e]||[])this.groups[t.id][e].push({...o})}export(e){for(const t of e.sheets)t.headerGroups=this.groups[t.id]}exportForExcel(e){for(const t of e.sheets)for(const e of["ROW","COL"]){const o=this.getGroupsLayers(t.id,e);for(let s=0;s<o.length;s++){const i=o[s];for(const o of i){for(let i=o.start;i<=o.end;i++){const n=MT(t,e,i);n.outlineLevel=s+1,o.isFolded&&(n.isHidden=!0)}if(o.isFolded){MT(t,e,o.end+1).collapsed=!0}}}}}}).add("header visibility",class extends Nk{static getters=["checkElementsIncludeAllVisibleHeaders","getHiddenColsGroups","getHiddenRowsGroups","isHeaderHiddenByUser","isRowHiddenByUser","isColHiddenByUser"];hiddenHeaders={};allowDispatch(e){switch(e.type){case"HIDE_COLUMNS_ROWS":{if(!this.getters.tryGetSheet(e.sheetId))return"InvalidSheetId";const t="COL"===e.dimension?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),o="COL"===e.dimension?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=o?"TooManyHiddenElements":Pt(e.elements)<0||Ft(e.elements)>o?"InvalidHeaderIndex":"Success"}case"REMOVE_COLUMNS_ROWS":return this.getters.tryGetSheet(e.sheetId)?this.checkElementsIncludeAllVisibleHeaders(e.sheetId,e.dimension,e.elements)?"NotEnoughElements":"Success":"InvalidSheetId"}return"Success"}handle(e){switch(e.type){case"CREATE_SHEET":const t={COL:Array(this.getters.getNumberCols(e.sheetId)).fill(!1),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(!1)};this.history.update("hiddenHeaders",e.sheetId,t);break;case"DUPLICATE_SHEET":this.history.update("hiddenHeaders",e.sheetIdTo,ze(this.hiddenHeaders[e.sheetId]));break;case"DELETE_SHEET":this.history.update("hiddenHeaders",e.sheetId,void 0);break;case"REMOVE_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(const o of[...e.elements].sort(((e,t)=>t-e)))t.splice(o,1);this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{const t=[...this.hiddenHeaders[e.sheetId][e.dimension]],o=pt(e.position,e.base);t.splice(o,0,...Array(e.quantity).fill(!1)),this.history.update("hiddenHeaders",e.sheetId,e.dimension,t);break}case"HIDE_COLUMNS_ROWS":for(const t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!0);break;case"UNHIDE_COLUMNS_ROWS":for(const t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!1)}}checkElementsIncludeAllVisibleHeaders(e,t,o){return vt(o,this.getAllVisibleHeaders(e,t))}isHeaderHiddenByUser(e,t,o){return"COL"===t?this.isColHiddenByUser(e,o):this.isRowHiddenByUser(e,o)}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]||this.getters.isRowFolded(e,t)}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]||this.getters.isColFolded(e,t)}getHiddenColsGroups(e){const t=[[]],o=this.hiddenHeaders[e].COL;for(let e=0;e<o.length;e++){o[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getHiddenRowsGroups(e){const t=[[]],o=this.hiddenHeaders[e].ROW;for(let e=0;e<o.length;e++){o[e]?t[t.length-1].push(e):0!==t[t.length-1].length&&t.push([])}return 0===t[t.length-1].length&&t.pop(),t}getAllVisibleHeaders(e,t){const o=je(0,this.getters.getNumberHeaders(e,t)),s=[];return this.getters.getHeaderGroups(e,t).forEach((e=>{e.isFolded&&s.push(...je(e.start,e.end+1))})),o.filter((o=>!this.hiddenHeaders[e][t][o]&&!s.includes(o)))}import(e){for(const t of e.sheets){this.hiddenHeaders[t.id]={COL:[],ROW:[]};for(let e=0;e<t.rowNumber;e++)this.hiddenHeaders[t.id].ROW[e]=Boolean(t.rows[e]?.isHidden);for(let e=0;e<t.colNumber;e++)this.hiddenHeaders[t.id].COL[e]=Boolean(t.cols[e]?.isHidden)}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(const o of e.sheets){void 0===o.rows&&(o.rows={});for(let e=0;e<this.getters.getNumberRows(o.id);e++)(t||this.hiddenHeaders[o.id].ROW[e])&&(void 0===o.rows[e]&&(o.rows[e]={}),o.rows[e].isHidden||=this.hiddenHeaders[o.id].ROW[e]);void 0===o.cols&&(o.cols={});for(let e=0;e<this.getters.getNumberCols(o.id);e++)(t||this.hiddenHeaders[o.id].COL[e])&&(void 0===o.cols[e]&&(o.cols[e]={}),o.cols[e].isHidden||=this.hiddenHeaders[o.id].COL[e])}}}).add("tables",class extends Nk{static getters=["getCoreTable","getCoreTables","getCoreTableMatchingTopLeft"];tables={};nextTableId=1;adaptRanges(e,t){for(const o of this.getCoreTables(t))this.applyRangeChangeOnTable(t,o,e)}allowDispatch(e){switch(e.type){case"CREATE_TABLE":if(e.ranges.some((t=>!this.getters.tryGetSheet(t._sheetId)||t._sheetId!==e.sheetId)))return"InvalidSheetId";const t=e.ranges.map((e=>this.getters.getRangeFromRangeData(e).zone));return Ur(t)?this.checkValidations(e,(e=>this.getTablesOverlappingZones(e.sheetId,t).length?"TableOverlap":"Success"),(e=>this.checkTableConfigUpdateIsValid(e.config))):"NonContinuousTargets";case"UPDATE_TABLE":return this.getCoreTableMatchingTopLeft(e.sheetId,e.zone)?this.checkValidations(e,this.checkUpdatedTableZoneIsValid,(e=>this.checkTableConfigUpdateIsValid(e.config))):"TableNotFound";case"ADD_MERGE":for(const t of this.getCoreTables(e.sheetId)){const o=t.range.zone;for(const t of e.target)if(xr(o,t))return"MergeInTable"}}return"Success"}handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("tables",e.sheetId,{});break;case"DELETE_SHEET":{const t={...this.tables};delete t[e.sheetId],this.history.update("tables",t);break}case"DUPLICATE_SHEET":{const t={};for(const o of this.getCoreTables(e.sheetId))t[o.id]="dynamic"===o.type?this.copyDynamicTableForSheet(e.sheetIdTo,o):this.copyStaticTableForSheet(e.sheetIdTo,o);this.history.update("tables",e.sheetIdTo,t);break}case"CREATE_TABLE":{const t=e.ranges.map((e=>this.getters.getRangeFromRangeData(e))),o=this.getters.getRangesUnion(t),s=this.getters.getMergesInZone(e.sheetId,o.zone);s.length&&this.dispatch("REMOVE_MERGE",{sheetId:e.sheetId,target:s});const i=this.consumeNextId(),n=e.config||wR,r="dynamic"===e.tableType?this.createDynamicTable(i,o,n):this.createStaticTable(i,e.tableType,o,n);this.history.update("tables",e.sheetId,r.id,r);break}case"REMOVE_TABLE":{const t={};for(const o of this.getCoreTables(e.sheetId))e.target.every((e=>!wr(o.range.zone,e)))&&(t[o.id]=o);this.history.update("tables",e.sheetId,t);break}case"UPDATE_TABLE":this.updateTable(e);break;case"UPDATE_CELL":{const t=e.sheetId;for(const o of this.getCoreTables(t)){if("dynamic"===o.type)continue;const s=this.canUpdateCellCmdExtendTable(e,o);"down"===s?this.extendTableDown(t,o):"right"===s&&this.extendTableRight(t,o)}break}case"DELETE_CONTENT":{const t={...this.tables[e.sheetId]};for(const o in t){const s=t[o];s&&e.target.some((e=>Rr(s.range.zone,e)))&&this.dispatch("REMOVE_TABLE",{sheetId:e.sheetId,target:[s.range.zone]})}break}}}getCoreTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(lt):[]}getCoreTable({sheetId:e,col:t,row:o}){return this.getCoreTables(e).find((e=>Er(t,o,e.range.zone)))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter((e=>t.some((t=>xr(e.range.zone,t)))))}extendTableDown(e,t){const o=this.getters.extendRange(t.range,"ROW",1);this.history.update("tables",e,t.id,this.updateStaticTable(t,o))}extendTableRight(e,t){const o=this.getters.extendRange(t.range,"COL",1);this.history.update("tables",e,t.id,this.updateStaticTable(t,o))}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:o,row:s},i){if(!e)return"none";const n=i.range.zone;let r="none";if(n.bottom+1===s&&o>=n.left&&o<=n.right?r="down":n.right+1===o&&s>=n.top&&s<=n.bottom&&(r="right"),"none"===r)return"none";const a="down"===r?{...n,bottom:n.bottom+1,top:n.bottom+1}:{...n,right:n.right+1,left:n.right+1};for(let e=a.top;e<=a.bottom;e++)for(let o=a.left;o<=a.right;o++){const s={sheetId:t,col:o,row:e},i=this.getters.getCell(s)?.content;if(i||this.getters.isInMerge(s)||this.getTablesOverlappingZones(t,[Mr(s)]).length)return"none"}return r}getCoreTableMatchingTopLeft(e,t){for(const o of this.getCoreTables(e)){const e=o.range.zone;if(e.left===t.left&&e.top===t.top)return o}}checkUpdatedTableZoneIsValid(e){if(!e.newTableRange)return"Success";const t=this.getters.getRangeFromRangeData(e.newTableRange).zone,o=this.getters.checkZonesExistInSheet(e.sheetId,[t]);if("Success"!==o)return o;const s=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!s)return"TableNotFound";return this.getTablesOverlappingZones(e.sheetId,[t]).filter((e=>e.id!==s.id)).length?"TableOverlap":"Success"}checkTableConfigUpdateIsValid(e){return e&&(void 0!==e.numberOfHeaders&&e.numberOfHeaders<0||e.hasFilters&&0===e.numberOfHeaders)?"InvalidTableConfig":"Success"}createStaticTable(e,t,o,s,i){const n=o.zone;if(!i){i=[];for(const e of je(n.left,n.right+1)){const t={...n,left:e,right:e},r=this.consumeNextId();i.push(this.createFilterFromZone(r,o.sheetId,t,s))}}return{id:e,range:o,filters:i,config:s,type:t}}createDynamicTable(e,t,o){const s=Nr(t.zone);return{id:e,range:this.getters.getRangeFromZone(t.sheetId,s),config:o,type:"dynamic"}}updateTable(e){const t=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return;const o=e.newTableRange?this.getters.getRangeFromRangeData(e.newTableRange):void 0;if(o){const t=this.getters.getMergesInZone(e.sheetId,o.zone);this.dispatch("REMOVE_MERGE",{sheetId:e.sheetId,target:t})}const s=o||t.range,i=this.updateTableConfig(e.config,t.config),n=e.tableType??t.type;if("dynamic"===n&&"dynamic"!==t.type||"dynamic"!==n&&"dynamic"===t.type){const o="dynamic"===n?this.createDynamicTable(t.id,s,i):this.createStaticTable(t.id,n,s,i);this.history.update("tables",e.sheetId,t.id,o)}else{const o="dynamic"===t.type?this.updateDynamicTable(t,s,i):this.updateStaticTable(t,s,i,n);this.history.update("tables",e.sheetId,t.id,o)}}updateStaticTable(e,t,o,s=e.type){if("dynamic"===s)throw new Error("Cannot use updateStaticTable to update a dynamic table");const i=t||e.range,n=i.zone,r=this.updateTableConfig(o,e.config),a=r||e.config,l=[];if(t||r&&"numberOfHeaders"in r)for(const t of je(n.left,n.right+1)){const o=n.top===e.range.zone.top?e.filters.find((e=>e.col===t)):void 0,s={...n,left:t,right:t},r=o?.id||this.consumeNextId();l.push(this.createFilterFromZone(r,i.sheetId,s,a))}return{...e,range:i,config:a,filters:l.length?l:e.filters,type:s}}updateDynamicTable(e,t,o){const s=t?this.getters.getRangeFromZone(t.sheetId,Nr(t.zone)):e.range,i=o||e.config;return{...e,range:s,config:i}}updateTableConfig(e,t){if(!e)return t;const o={...t,...e};return 0===e.numberOfHeaders?o.hasFilters=!1:!0===e.hasFilters&&(o.numberOfHeaders||=1),o}createFilterFromZone(e,t,o,s){return C_(e,this.getters.getRangeFromZone(t,o),s,this.getters.getRangeFromZone)}copyStaticTableForSheet(e,t){const o=this.getters.getRangeFromZone(e,t.range.zone),s=t.filters.map((o=>{const s=this.getters.getRangeFromZone(e,o.rangeWithHeaders.zone);return C_(o.id,s,t.config,this.getters.getRangeFromZone)}));return{id:t.id,range:o,filters:s,config:ze(t.config),type:t.type}}copyDynamicTableForSheet(e,t){const o=this.getters.getRangeFromZone(e,t.range.zone);return{id:t.id,range:o,config:ze(t.config),type:"dynamic"}}applyRangeChangeOnTable(e,t,o){const s=o(t.range);let i;switch(s.changeType){case"REMOVE":return void this.history.update("tables",e,t.id,void 0);case"NONE":return;default:i=s.range}if("dynamic"===t.type){const o=this.updateDynamicTable(t,i);return void this.history.update("tables",e,t.id,o)}const n=[];for(const e of t.filters){const s=o(e.rangeWithHeaders);switch(s.changeType){case"REMOVE":continue;case"NONE":n.push(e);break;default:const o=s.range,i=C_(e.id,o,t.config,this.getters.getRangeFromZone);n.push(i)}}const r=i.zone;if(n.length<Tr(r).numberOfCols){for(let o=r.left;o<=r.right;o++)if(!n.find((e=>e.col===o))){const s=this.consumeNextId(),i={...r,left:o,right:o};n.push(this.createFilterFromZone(s,e,i,t.config))}n.sort(((e,t)=>e.col-t.col))}const a=this.createStaticTable(t.id,t.type,i,t.config,n);this.history.update("tables",e,t.id,a)}consumeNextId(){const e=`${this.nextTableId}`;return this.history.update("nextTableId",this.nextTableId+1),e}import(e){for(const t of e.sheets)for(const e of t.tables||[]){const o=this.consumeNextId(),s=e.config||wR,i=this.getters.getRangeFromSheetXC(t.id,e.range),n=e.type||"static",r="dynamic"===n?this.createDynamicTable(o,i,s):this.createStaticTable(o,n,i,s);this.history.update("tables",t.id,r.id,r)}}export(e){for(const t of e.sheets)for(const e of this.getCoreTables(t.id)){const o={range:fr(e.range.zone),type:e.type};mt(e.config,wR)||(o.config=e.config),t.tables.push(o)}}exportForExcel(e){for(const t of e.sheets)for(const e of this.getCoreTables(t.id)){const o=fr(e.range.zone);t.tables.push({range:o,filters:[],config:e.config})}}}).add("dataValidation",class extends Nk{static getters=["cellHasListDataValidationIcon","getDataValidationRule","getDataValidationRules","getValidationRuleForCell"];rules={};adaptRanges(e,t){this.adaptDVRanges(t,e),this.adaptDVFormulas(e)}adaptDVFormulas(e){for(const t in this.rules){for(let o=this.rules[t].length-1;o>=0;o--){const s=this.rules[t][o];for(let i=0;i<s.criterion.values.length;i++){const n=this.getters.adaptFormulaStringDependencies(t,s.criterion.values[i],e);this.history.update("rules",t,o,"criterion","values",i,n)}}}}adaptDVRanges(e,t){for(let o=this.rules[e].length-1;o>=0;o--){const s=this.rules[e][o];for(let i=s.ranges.length-1;i>=0;i--){const n=t(s.ranges[i]);switch(n.changeType){case"REMOVE":if(1===s.ranges.length)this.removeDataValidationRule(e,s.id);else{const t=s.ranges.slice();t.splice(i,1),this.history.update("rules",e,o,"ranges",t)}break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("rules",e,o,"ranges",i,n.range)}}}}allowDispatch(e){switch(e.type){case"ADD_DATA_VALIDATION_RULE":return this.getters.tryGetSheet(e.sheetId)?e.ranges.some((e=>!this.getters.tryGetSheet(e._sheetId)))?"InvalidSheetId":this.checkValidations(e,this.chainValidations(this.checkEmptyRange,this.checkValidRange,this.checkCriterionTypeIsValid,this.checkCriterionHasValidNumberOfValues,this.checkCriterionValuesAreValid)):"InvalidSheetId";case"REMOVE_DATA_VALIDATION_RULE":if(!this.getters.tryGetSheet(e.sheetId))return"InvalidSheetId";if(!this.rules[e.sheetId].find((t=>t.id===e.id)))return"UnknownDataValidationRule"}return"Success"}handle(e){switch(e.type){case"CREATE_SHEET":this.history.update("rules",e.sheetId,[]);break;case"DUPLICATE_SHEET":{const t=ze(this.rules[e.sheetId]).map((t=>({...t,ranges:t.ranges.map((t=>Ca(e.sheetId,e.sheetIdTo,t)))})));this.history.update("rules",e.sheetIdTo,t);break}case"DELETE_SHEET":{const t={...this.rules};delete t[e.sheetId],this.history.update("rules",t);break}case"REMOVE_DATA_VALIDATION_RULE":this.removeDataValidationRule(e.sheetId,e.id);break;case"ADD_DATA_VALIDATION_RULE":{const t=e.ranges.map((e=>this.getters.getRangeFromRangeData(e)));this.addDataValidationRule(e.sheetId,{...e.rule,ranges:t});break}case"DELETE_CONTENT":{const t=nr(e.target),o=e.sheetId;for(const e of t)for(let t=e.top;t<=e.bottom;t++)for(let s=e.left;s<=e.right;s++){const e=this.getValidationRuleForCell({sheetId:o,col:s,row:t});if(e&&("isBoolean"===e.criterion.type||"isValueInList"===e.criterion.type&&!this.getters.getCell({sheetId:o,col:s,row:t})?.content)){const e=this.rules[o],i=[this.getters.getRangeFromSheetXC(o,Po(s,t))],n=this.removeRangesFromRules(o,i,e);this.history.update("rules",o,n)}}}}}getDataValidationRules(e){return this.rules[e]}getDataValidationRule(e,t){return this.rules[e].find((e=>e.id===t))}getValidationRuleForCell({sheetId:e,col:t,row:o}){if(this.rules[e])for(const s of this.rules[e])for(const e of s.ranges)if(Er(t,o,e.zone))return s}cellHasListDataValidationIcon(e){const t=this.getValidationRuleForCell(e);return!!t&&!("isValueInList"!==t.criterion.type&&"isValueInRange"!==t.criterion.type||"arrow"!==t.criterion.displayStyle&&"chip"!==t.criterion.displayStyle)}addDataValidationRule(e,t){const o=this.rules[e];"isBoolean"===t.criterion.type?this.setCenterStyleToBooleanCells(t):"isValueInList"===t.criterion.type&&(t.criterion.values=Array.from(new Set(t.criterion.values)));const s=this.removeRangesFromRules(e,t.ranges,o,t.id),i=s.findIndex((e=>e.id===t.id));-1!==i?(s[i]=t,this.history.update("rules",e,s)):this.history.update("rules",e,[...s,t])}removeRangesFromRules(e,t,o,s){o=ze(o);for(const e of o)e.id!==s&&(e.ranges=this.getters.recomputeRanges(e.ranges,t));return o.filter((e=>e.ranges.length>0))}removeDataValidationRule(e,t){const o=this.rules[e].filter((e=>e.id!==t));this.history.update("rules",e,o)}setCenterStyleToBooleanCells(e){for(const t of wa(e.ranges)){const e=this.getters.getCell(t),o={...e?.style,align:e?.style?.align??"center",verticalAlign:e?.style?.verticalAlign??"middle"};this.dispatch("UPDATE_CELL",{...t,style:o})}}checkEmptyRange(e){return e.ranges.length?"Success":"EmptyRange"}import(e){for(const t of e.sheets)if(this.rules[t.id]=[],t.dataValidationRules)for(const e of t.dataValidationRules)this.rules[t.id].push({...e,ranges:e.ranges.map((e=>this.getters.getRangeFromSheetXC(t.id,e)))})}export(e){if(e.sheets)for(const t of e.sheets){t.dataValidationRules=[];for(const e of this.rules[t.id])t.dataValidationRules.push({...e,ranges:e.ranges.map((e=>this.getters.getRangeString(e,t.id)))})}}exportForExcel(e){if(e.sheets)for(const t of e.sheets){t.dataValidationRules=[];for(const e of this.rules[t.id]){const o={...ze(e),ranges:e.ranges.map((e=>this.getters.getRangeString(e,t.id,{useBoundedReference:!0})))};"isValueInRange"===e.criterion.type&&(o.criterion.values=e.criterion.values.map((e=>{const o=this.getters.getRangeFromSheetXC(t.id,e);return this.getters.getRangeString(o,t.id,{useBoundedReference:!0,useFixedReference:!0})}))),t.dataValidationRules.push(o)}}}checkCriterionTypeIsValid(e){return eE.contains(e.rule.criterion.type)?"Success":"UnknownDataValidationCriterionType"}checkCriterionHasValidNumberOfValues(e){const t=e.rule.criterion,o=eE.get(t.type).numberOfValues(t);return void 0!==o&&t.values.length!==o?"InvalidNumberOfCriterionValues":"Success"}checkCriterionValuesAreValid(e){const t=e.rule.criterion,o=eE.get(t.type);return t.values.some((e=>"onlyFormulas"===o.allowedValues&&!e.startsWith("=")||(e.startsWith("=")?"onlyLiterals"===o.allowedValues||HS(e).isBadExpression:!o.isCriterionValueValid(e))))?"InvalidDataValidationCriterionValue":"Success"}checkValidRange(e){const t=e.ranges.map((e=>this.getters.getRangeFromRangeData(e))),o=t.map((t=>this.getters.getRangeString(t,e.sheetId)));return o.some((e=>!this.getters.isRangeValid(e)))?"InvalidRange":"Success"}}).add("cell",class extends Nk{static getters=["zoneToXC","getCells","getTranslatedCellFormula","getCellStyle","getCellById","getFormulaString","getFormulaMovedInSheet"];nextId=1;cells={};adaptRanges(e,t,o){for(const s of Object.keys(this.cells))for(const i of Object.values(this.cells[s]||{}))if(i.isFormula)for(const n of i.compiledFormula.dependencies)if(n.sheetId===t||n.invalidSheetName===o.old){const t=e(n);"NONE"!==t.changeType&&this.history.update("cells",s,i.id,"compiledFormula","dependencies",i.compiledFormula.dependencies.indexOf(n),t.range)}}allowDispatch(e){switch(e.type){case"UPDATE_CELL":return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessUpdateCell);case"CLEAR_CELL":return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessClearCell);case"UPDATE_CELL_POSITION":return!e.cellId||this.cells[e.sheetId]?.[e.cellId]?"Success":"InvalidCellId";default:return"Success"}}handle(e){switch(e.type){case"SET_FORMATTING":"style"in e&&this.setStyle(e.sheetId,e.target,e.style),"format"in e&&void 0!==e.format&&this.setFormatter(e.sheetId,e.target,e.format);break;case"CLEAR_FORMATTING":this.clearFormatting(e.sheetId,e.target);break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case"UPDATE_CELL":this.updateCell(e.sheetId,e.col,e.row,e);break;case"CLEAR_CELL":this.dispatch("UPDATE_CELL",{sheetId:e.sheetId,col:e.col,row:e.row,content:"",style:null,format:""});break;case"CLEAR_CELLS":this.clearCells(e.sheetId,e.target);break;case"DELETE_CONTENT":this.clearZones(e.sheetId,e.target);break;case"DELETE_SHEET":this.history.update("cells",e.sheetId,void 0)}}clearZones(e,t){for(const o of nr(t))for(let t=o.left;t<=o.right;t++)for(let s=o.top;s<=o.bottom;s++){const o=this.getters.getCell({sheetId:e,col:t,row:s});(o?.isFormula||o?.content)&&this.dispatch("UPDATE_CELL",{sheetId:e,content:"",col:t,row:s})}}setFormatter(e,t,o){for(const s of nr(t))for(let t=s.top;t<=s.bottom;t++)for(let i=s.left;i<=s.right;i++)this.dispatch("UPDATE_CELL",{sheetId:e,col:i,row:t,format:o})}clearFormatting(e,t){for(const o of nr(t))for(let t=o.left;t<=o.right;t++)for(let s=o.top;s<=o.bottom;s++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:s,style:null,format:""})}clearCells(e,t){for(const o of t)for(let t=o.left;t<=o.right;t++)for(let s=o.top;s<=o.bottom;s++)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:s,content:"",style:null,format:""})}handleAddColumnsRows(e,t){let o,s;"before"===e.position?(o=je(e.base,e.base+e.quantity),s=e.base+e.quantity):(o=je(e.base+1,e.base+e.quantity+1),s=e.base),t(e.sheetId,s,o)}import(e){for(const t of e.sheets){const o=t.id,s=new $D;for(const e in t.cells)if(t.cells[e]){const{col:o,row:i}=Fo(e),n={sheetId:t.id,col:o,row:i};s.set(n,{content:t.cells[e]})}for(const[e,o]of[["style",t.styles],["format",t.formats]])for(const[i,n]of qr(t.id,o)){const t=s.get(i);t?t[e]=n:s.set(i,{[e]:n})}for(const i of s.keysForSheet(o)){const o=s.get(i);if(o?.content||o?.format||o?.style){const s=this.importCell(t.id,o?.content,o?.style?e.styles[o?.style]:void 0,o?.format?e.formats[o?.format]:void 0);this.history.update("cells",t.id,s.id,s),this.dispatch("UPDATE_CELL_POSITION",{cellId:s.id,...i})}}}}export(e){const t={},o={};for(const s of e.sheets){const e=[],i=[],n={},r=Object.keys(this.cells[s.id]||{}).map((e=>this.getters.getCellPosition(e))).sort(((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col));for(const s of r){const r=this.getters.getCell(s),a=Po(s.col,s.row),l=this.removeDefaultStyleValues(r.style);if(Object.keys(l).length){const o=Gr(l,t);e[o]??=[],e[o].push(s)}if(r.format){const e=Gr(r.format,o);i[e]??=[],i[e].push(s)}r.content&&(n[a]=r.content)}s.styles=Wr(e),s.formats=Wr(i),s.cells=n}e.styles=t,e.formats=o}importCell(e,t,o,s){const i=this.getNextUid();return this.createCell(i,t||"",s,o,e)}exportForExcel(e){this.export(e);const t=[];for(const o in e.formats||[])jn(e.formats[o])||(t.push(Number(o)),delete e.formats[o]);if(t.length)for(const o of e.sheets)for(const e in o.formats){const s=o.formats[e];s&&t.includes(s)&&delete o.formats[e]}}removeDefaultStyleValues(e){const t={...e};for(const e in de)t[e]===de[e]&&delete t[e];return t}getCells(e){return this.cells[e]||{}}getCellById(e){const t=this.getters.getCellPosition(e);return this.cells[t.sheetId][e]}getFormulaString(e,t,o,s=!1){if(!o.length)return dt(t.map((e=>e.value)));let i=0;return dt(t.map((t=>{if("REFERENCE"===t.type){const t=o[i++];return this.getters.getRangeString(t,e,{useBoundedReference:s})}return t.value})))}getTranslatedCellFormula(e,t,o,s){const i=this.getters.createAdaptedRanges(US(s).dependencies.map((t=>this.getters.getRangeFromSheetXC(e,t))),t,o,e);return this.getFormulaString(e,s,i)}getFormulaMovedInSheet(e,t,o){const s=US(o).dependencies.map((t=>this.getters.getRangeFromSheetXC(e,t))),i=this.getters.removeRangesSheetPrefix(t,s);return this.getFormulaString(t,o,i)}getCellStyle(e){return this.getters.getCell(e)?.style||{}}zoneToXC(e,t,o=[{colFixed:!1,rowFixed:!1}]){const s=Po((t=this.getters.expandZone(e,t)).left,t.top,o[0]),i=Po(t.right,t.bottom,o.length>1?o[1]:o[0]),n=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),r=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),a=n.col===r.col&&n.row===r.row;return s===i||a?s:s+":"+i}setStyle(e,t,o){for(const s of nr(t))for(let t=s.left;t<=s.right;t++)for(let i=s.top;i<=s.bottom;i++){const s=this.getters.getCell({sheetId:e,col:t,row:i});this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:i,style:o?{...s?.style,...o}:void 0})}}copyColumnStyle(e,t,o){for(let s=0;s<this.getters.getNumberRows(e);s++){const i=this.getFormat(e,t,s);if(i.style||i.format)for(const t of o)this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:s,...i})}}copyRowStyle(e,t,o){for(let s=0;s<this.getters.getNumberCols(e);s++){const i=this.getFormat(e,s,t);if(i.style||i.format)for(const t of o)this.dispatch("UPDATE_CELL",{sheetId:e,col:s,row:t,...i})}}getFormat(e,t,o){const s={},i=this.getters.getMainCellPosition({sheetId:e,col:t,row:o}),n=this.getters.getCell(i);return n&&(n.style&&(s.style=n.style),n.format&&(s.format=n.format)),s}getNextUid(){const e=this.nextId.toString();return this.history.update("nextId",this.nextId+1),e}updateCell(e,t,o,s){const i=this.getters.getCell({sheetId:e,col:t,row:o}),n="content"in s||"formula"in s,r=n?It(s?.content):i?.content||"";let a;a=void 0!==s.style?s.style||void 0:i?i.style:void 0;const l="format"in s?s.format:i&&i.format;if((n&&!r&&!s.formula||!n&&(!i||""===i.content))&&!a&&!l)return void(i&&(this.history.update("cells",e,i.id,void 0),this.dispatch("UPDATE_CELL_POSITION",{cellId:void 0,col:t,row:o,sheetId:e})));const c=i?.id||this.getNextUid(),h=this.createCell(c,r,l,a,e);this.history.update("cells",e,h.id,h),this.dispatch("UPDATE_CELL_POSITION",{cellId:h.id,col:t,row:o,sheetId:e})}createCell(e,t,o,s,i){return t.startsWith("=")?this.createFormulaCell(e,t,o,s,i):this.createLiteralCell(e,t,o,s)}createLiteralCell(e,t,o,s){const i=this.getters.getLocale(),n=Kn(t,i);return Yn(o=o||("number"==typeof n?Nn(t,i)||kn(t):void 0))||gi(t)||(t=wi(n)),{id:e,content:t,style:s,format:o,isFormula:!1,parsedValue:n}}createFormulaCell(e,t,o,s,i){const n=HS(t);return n.dependencies.length?this.createFormulaCellWithDependencies(e,n,o,s,i):{id:e,content:t,style:s,format:o,isFormula:!0,compiledFormula:{...n,dependencies:[]}}}createFormulaCellWithDependencies(e,t,o,s,i){const n=[];for(const e of t.dependencies)n.push(this.getters.getRangeFromSheetXC(i,e));return new kk(e,t,o,s,n,i,this.getters.getRangeString)}checkCellOutOfSheet(e){const{sheetId:t,col:o,row:s}=e;if(!this.getters.tryGetSheet(t))return"InvalidSheetId";return Er(o,s,this.getters.getSheetZone(t))?"Success":"TargetOutOfSheet"}checkUselessClearCell(e){const t=this.getters.getCell(e);return t&&(t.content||t.style||t.format)?"Success":"NoChanges"}checkUselessUpdateCell(e){const t=this.getters.getCell(e),o="style"in e,s="format"in e;return("content"in e||"formula"in e)&&t?.content!==e.content||o&&!mt(t?.style,e.style)||s&&t?.format!==e.format?"Success":"NoChanges"}}).add("merge",class extends Nk{static getters=["isInMerge","isInSameMerge","isMergeHidden","getMainCellPosition","expandZone","doesIntersectMerge","doesColumnsHaveCommonMerges","doesRowsHaveCommonMerges","getMerges","getMerge","getMergesInZone","isSingleCellOrMerge","getSelectionRangeString","isMainCellPosition"];nextId=1;merges={};mergeCellMap={};allowDispatch(e){const t="force"in e&&!!e.force;switch(e.type){case"ADD_MERGE":return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case"UPDATE_CELL":return this.checkMergedContentUpdate(e);case"REMOVE_MERGE":return this.checkMergeExists(e);default:return"Success"}}handle(e){switch(e.type){case"CREATE_SHEET":case"DELETE_SHEET":this.history.update("merges",e.sheetId,{}),this.history.update("mergeCellMap",e.sheetId,{});break;case"DUPLICATE_SHEET":const t=this.merges[e.sheetId];if(!t)break;for(const o of Object.values(t).filter(lt))this.addMerge(e.sheetIdTo,o.zone);break;case"ADD_MERGE":for(const t of e.target)this.addMerge(e.sheetId,t);break;case"REMOVE_MERGE":for(const t of e.target)this.removeMerge(e.sheetId,t)}}adaptRanges(e,t){this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map((t=>this.getMergeById(e,parseInt(t,10)))).filter(lt)}getMerge({sheetId:e,col:t,row:o}){const s=this.mergeCellMap[e],i=s?t in s&&s[t]?.[o]:void 0;return i?this.getMergeById(e,i):void 0}getMergesInZone(e,t){const o=this.mergeCellMap[e];if(!o)return[];const s=new Set;for(let e=t.left;e<=t.right;e++)for(let i=t.top;i<=t.bottom;i++){const t=o[e]?.[i];t&&s.add(t)}return Array.from(s).map((t=>this.getMergeById(e,t))).filter(lt)}getSelectionRangeString(e,t){const o=this.getters.expandZone(e.sheetId,e.zone),s=pa({...e,zone:{...o,bottom:va(e)?void 0:o.bottom,right:ba(e)?void 0:o.right}},this.getters.getSheetSize),i=this.getters.getRangeString(s,t);if(this.isSingleCellOrMerge(e.sheetId,e.zone)){const{sheetName:e,xc:t}=ra(i);return aa(e,t.split(":")[0])}return i}doesIntersectMerge(e,t){for(const o of this.getMerges(e))if(xr(t,o))return!0;return!1}doesColumnsHaveCommonMerges(e,t,o){const s=this.getters.getSheet(e);for(let i=0;i<this.getters.getNumberRows(e);i++)if(this.isInSameMerge(s.id,t,i,o,i))return!0;return!1}doesRowsHaveCommonMerges(e,t,o){const s=this.getters.getSheet(e);for(let i=0;i<=this.getters.getNumberCols(e);i++)if(this.isInSameMerge(s.id,i,t,i,o))return!0;return!1}expandZone(e,t){const{left:o,right:s,top:i,bottom:n}=t;let r={left:o,right:s,top:i,bottom:n};for(const t in this.merges[e]){const o=this.getMergeById(e,parseInt(t));o&&xr(o,r)&&(r=yr(o,r))}return Ir(r,t)?r:this.expandZone(e,r)}isInSameMerge(e,t,o,s,i){const n=this.getMerge({sheetId:e,col:t,row:o}),r=this.getMerge({sheetId:e,col:s,row:i});return!(!n||!r)&&Ir(n,r)}isInMerge({sheetId:e,col:t,row:o}){const s=this.mergeCellMap[e];return!!s&&(t in s&&Boolean(s[t]?.[o]))}getMainCellPosition(e){const t=this.getMerge(e);return t?{sheetId:e.sheetId,col:t.left,row:t.top}:e}isMergeHidden(e,t){const o=this.getters.getHiddenColsGroups(e),s=this.getters.getHiddenRowsGroups(e);for(const e of o)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(const e of s)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){const o=this.getMerge({sheetId:e,col:t.left,row:t.top});if(o)return Ir(t,o);const{numberOfCols:s,numberOfRows:i}=Tr(t);return 1===s&&1===i}isMainCellPosition(e){return mt(this.getMainCellPosition(e),e)}isMergeDestructive(e,t){let{left:o,right:s,top:i,bottom:n}=t;s=Ze(s,0,this.getters.getNumberCols(e)-1),n=Ze(n,0,this.getters.getNumberRows(e)-1);for(let t=i;t<=n;t++)for(let n=o;n<=s;n++)if(n!==o||t!==i){const o=this.getters.getCell({sheetId:e,col:n,row:t});if(o&&""!==o.content)return!0}return!1}getMergeById(e,t){const o=this.merges[e]?.[t];return void 0!==o?Uk(t,o):void 0}checkDestructiveMerge({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return"Success";return t.some((t=>this.isMergeDestructive(e,t)))?"MergeIsDestructive":"Success"}checkOverlap({target:e}){for(const t of e)for(const o of e)if(t!==o&&xr(t,o))return"MergeOverlap";return"Success"}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return"Success";const{xSplit:o,ySplit:s}=this.getters.getPaneDivisions(e);return Hr(t,o,s)?"FrozenPaneOverlap":"Success"}checkMergedContentUpdate(e){const{col:t,row:o,content:s}=e;if(void 0===s)return"Success";const{col:i,row:n}=this.getMainCellPosition(e);return i===t&&n===o?"Success":"CellIsMerged"}checkMergeExists(e){const{sheetId:t,target:o}=e;for(const e of o){const{left:o,top:s}=e,i=this.getMerge({sheetId:t,col:o,row:s});if(void 0===i||!Ir(e,i))return"InvalidTarget"}return"Success"}addMerge(e,t){let{left:o,right:s,top:i,bottom:n}=t;s=Ze(s,0,this.getters.getNumberCols(e)-1),n=Ze(n,0,this.getters.getNumberRows(e)-1);if(Po(o,i)===Po(s,n))return;const r=this.getters.getCell({sheetId:e,col:o,row:i}),a=this.nextId++;this.history.update("merges",e,a,this.getters.getRangeFromSheetXC(e,fr({left:o,top:i,right:s,bottom:n})));const l=new Set;for(let t=i;t<=n;t++)for(let n=o;n<=s;n++){n===o&&t===i||this.dispatch("UPDATE_CELL",{sheetId:e,col:n,row:t,style:r?r.style:null,content:""});const s=this.getMerge({sheetId:e,col:n,row:t});s&&l.add(s.id),this.history.update("mergeCellMap",e,n,t,a)}for(const t of l){const{top:o,bottom:s,left:i,right:n}=this.getMergeById(e,t);for(let t=o;t<=s;t++)for(let o=i;o<=n;o++){const s={sheetId:e,col:o,row:t},i=this.getMerge(s);i&&i.id===a||(this.history.update("mergeCellMap",e,o,t,void 0),this.dispatch("CLEAR_CELL",s))}this.history.update("merges",e,t,void 0)}}removeMerge(e,t){const{left:o,top:s,bottom:i,right:n}=t,r=this.getMerge({sheetId:e,col:o,row:s});if(void 0!==r&&Ir(t,r)){this.history.update("merges",e,r.id,void 0);for(let t=s;t<=i;t++)for(let s=o;s<=n;s++)this.history.update("mergeCellMap",e,s,t,void 0)}}applyRangeChangeOnSheet(e,t){const o=Object.entries(this.merges[e]||{});for(const[s,i]of o)if(i){const o=i.zone,n=t(i);switch(n.changeType){case"NONE":break;case"REMOVE":this.removeMerge(e,o);break;default:const{numberOfCols:t,numberOfRows:i}=Tr(n.range.zone);1===t&&1===i?this.removeMerge(e,o):this.history.update("merges",e,parseInt(s,10),n.range)}}this.history.update("mergeCellMap",e,{});for(const t of this.getMerges(e))for(const{col:o,row:s}of _r(t))this.history.update("mergeCellMap",e,o,s,t.id)}import(e){const t=e.sheets||[];for(const e of t)this.history.update("merges",e.id,{}),this.history.update("mergeCellMap",e.id,{}),e.merges&&this.importMerges(e.id,e.merges)}importMerges(e,t){for(const o of t)this.addMerge(e,ur(o))}export(e){for(const t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...Hk(e))}}exportForExcel(e){this.export(e)}}).add("headerSize",class extends Nk{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,ze(this.sizes[e.sheetId]));break;case"DELETE_SHEET":const t={...this.sizes};delete t[e.sheetId],this.history.update("sizes",t);break;case"REMOVE_COLUMNS_ROWS":{const t=Rt(this.sizes[e.sheetId][e.dimension],e.elements);this.history.update("sizes",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{const t=[...this.sizes[e.sheetId][e.dimension]],o=pt(e.position,e.base),s=t[e.base];t.splice(o,0,...Array(e.quantity).fill(s)),this.history.update("sizes",e.sheetId,e.dimension,t);break}case"RESIZE_COLUMNS_ROWS":if("ROW"===e.dimension)for(const t of e.elements)this.history.update("sizes",e.sheetId,e.dimension,t,e.size||void 0);else for(const t of e.elements)this.history.update("sizes",e.sheetId,e.dimension,t,e.size||void 0)}}getColSize(e,t){return Math.round(this.sizes[e]?.COL[t]||se)}getUserRowSize(e,t){const o=this.sizes[e]?.ROW[t];return o?Math.round(o):void 0}import(e){for(const t of e.sheets){const e={COL:Array(t.colNumber).fill(void 0),ROW:Array(t.rowNumber).fill(void 0)};for(const[o,s]of Object.entries(t.rows))s.size&&(e.ROW[o]=s.size);for(const[o,s]of Object.entries(t.cols))s.size&&(e.COL[o]=s.size);this.sizes[t.id]=e}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(const o of e.sheets){void 0===o.rows&&(o.rows={});for(const e of je(0,this.getters.getNumberRows(o.id)))(t||this.sizes[o.id].ROW[e])&&(o.rows[e]={...o.rows[e],size:this.getUserRowSize(o.id,e)??ie});void 0===o.cols&&(o.cols={});for(const e of je(0,this.getters.getNumberCols(o.id)))(t||this.sizes[o.id].COL[e])&&(o.cols[e]={...o.cols[e],size:this.getColSize(o.id,e)})}}}).add("borders",class extends Nk{static getters=["getCellBorder","getBordersColors"];borders={};allowDispatch(e){return"SET_BORDER"===e.type?this.checkBordersUnchanged(e):"Success"}handle(e){switch(e.type){case"ADD_MERGE":for(const t of e.target)this.addBordersToMerge(e.sheetId,t);break;case"DUPLICATE_SHEET":const t=this.borders[e.sheetId];if(t){const o=t.slice().map((e=>e?.slice().map((e=>ze(e)))));this.history.update("borders",e.sheetIdTo,o)}break;case"DELETE_SHEET":const o={...this.borders};delete o[e.sheetId],this.history.update("borders",o);break;case"SET_BORDER":this.setBorder(e.sheetId,e.col,e.row,e.border);break;case"SET_BORDERS_ON_TARGET":for(const t of e.target)for(let o=t.top;o<=t.bottom;o++)for(let s=t.left;s<=t.right;s++)this.setBorder(e.sheetId,s,o,e.border);break;case"SET_ZONE_BORDERS":if(e.border){const 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||ve,color:e.border.color||be})}break;case"CLEAR_FORMATTING":this.clearBorders(e.sheetId,e.target);break;case"REMOVE_COLUMNS_ROWS":const s=[...e.elements].sort(((e,t)=>t-e));for(const t of Ye(s))if("COL"===e.dimension){const o=this.getters.getColsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[o]),this.shiftBordersHorizontally(e.sheetId,t[0]+1,-t.length)}else{const o=this.getters.getRowsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[o]),this.shiftBordersVertically(e.sheetId,t[0]+1,-t.length)}break;case"ADD_COLUMNS_ROWS":"COL"===e.dimension?this.handleAddColumns(e):this.handleAddRows(e)}}handleAddColumns(e){let t,o;"before"===e.position?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity),t=e.base-1,o=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity),t=e.base,o=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,o)}handleAddRows(e){let t,o;"before"===e.position?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity),t=e.base-1,o=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity),t=e.base,o=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,o)}getCellBorder({sheetId:e,col:t,row:o}){const s=this.borders[e]?.[t]?.[o];return s?.top||s?.bottom||s?.left||s?.right?ze(s):null}getBordersColors(e){const t=[],o=this.borders[e];if(o)for(const e of o.filter(lt))for(const o of e)if(o)for(const e of["top","bottom","left","right"]){const s=o[e]?.color;s&&t.push(s)}return t}ensureColumnBorderContinuity(e,t,o){const s=je(t+1,o);for(let i=0;i<this.getters.getNumberRows(e);i++){const n=this.getCellBorder({sheetId:e,col:t,row:i}),r=this.getCellBorder({sheetId:e,col:o,row:i});if(n&&r){const t=this.getCommonSides(n,r);for(const o of s)this.addBorder(e,o,i,t)}}}ensureRowBorderContinuity(e,t,o){const s=je(t+1,o);for(let i=0;i<this.getters.getNumberCols(e);i++){const n=this.getCellBorder({sheetId:e,col:i,row:t}),r=this.getCellBorder({sheetId:e,col:i,row:o});if(n&&r){const t=this.getCommonSides(n,r);for(const o of s)this.addBorder(e,i,o,t)}}}getCommonSides(e,t){const o={};for(const s of["top","bottom","left","right"])e[s]&&mt(e[s],t[s])&&(o[s]=e[s]);return o}getColumnsWithBorders(e){const t=this.borders[e];return t?Object.keys(t).map((e=>parseInt(e,10))):[]}getRowsWithBorders(e){const t=this.borders[e]?.filter(lt);if(!t)return[];const o=new Set;for(const e of t)for(const t in e)o.add(parseInt(t,10));return Array.from(o)}getRowsRange(e){return this.borders[e]?je(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,o){this.borders[e]&&this.getColumnsWithBorders(e).filter((e=>e>=t)).sort(((e,t)=>o<0?e-t:t-e)).forEach((t=>{this.moveBordersOfColumn(e,t,o)}))}shiftBordersVertically(e,t,o){this.borders[e]&&(o<0&&this.moveBordersOfRow(e,t,o,{destructive:!1}),this.getRowsWithBorders(e).filter((e=>e>=t)).sort(((e,t)=>o<0?e-t:t-e)).forEach((t=>{this.moveBordersOfRow(e,t,o)})))}moveBordersOfRow(e,t,o,{destructive:s}={destructive:!0}){const i=this.borders[e];i&&this.getColumnsWithBorders(e).forEach((n=>{const r=i[n]?.[t+o],a=i[n]?.[t];this.history.update("borders",e,n,t+o,s?a:a||r),this.history.update("borders",e,n,t,void 0)}))}moveBordersOfColumn(e,t,o,{destructive:s}={destructive:!0}){const i=this.borders[e];i&&this.getRowsRange(e).forEach((n=>{const r=i[t+o]?.[n],a=i[t]?.[n];this.history.update("borders",e,t+o,n,s?a:a||r),s&&this.history.update("borders",e,t,n,void 0)}))}setBorder(e,t,o,s,i=!0){const n=this.getters.getNumberCols(e)-1,r=this.getters.getNumberRows(e)-1;!i&&this.borders[e]?.[t]?.[o]?.left||(this.history.update("borders",e,t,o,"left",s?.left),s?.left&&t>0&&!mt(this.borders[e]?.[t-1]?.[o]?.right,s?.left)&&this.history.update("borders",e,t-1,o,"right",void 0)),!i&&this.borders[e]?.[t]?.[o]?.top||(this.history.update("borders",e,t,o,"top",s?.top),s?.top&&o>0&&!mt(this.borders[e]?.[t]?.[o-1]?.bottom,s?.top)&&this.history.update("borders",e,t,o-1,"bottom",void 0)),!i&&this.borders[e]?.[t]?.[o]?.right||(this.history.update("borders",e,t,o,"right",s?.right),s?.right&&t<n&&!mt(this.borders[e]?.[t+1]?.[o]?.left,s?.right)&&this.history.update("borders",e,t+1,o,"left",void 0)),!i&&this.borders[e]?.[t]?.[o]?.bottom||(this.history.update("borders",e,t,o,"bottom",s?.bottom),s?.bottom&&o<r&&!mt(this.borders[e]?.[t]?.[o+1]?.top,s?.bottom)&&this.history.update("borders",e,t,o+1,"top",void 0))}clearBorders(e,t,o=!1){const s=this.getters.getNumberCols(e)-1,i=this.getters.getNumberRows(e)-1;for(const n of nr(t))for(let t=n.top;t<=n.bottom;t++){o&&(n.left>0&&this.history.update("borders",e,n.left-1,t,"right",void 0),n.right<s&&this.history.update("borders",e,n.right+1,t,"left",void 0));for(let s=n.left;s<=n.right;s++)this.history.update("borders",e,s,t,void 0),o&&(n.top>0&&this.history.update("borders",e,s,n.top-1,"bottom",void 0),n.bottom<i&&this.history.update("borders",e,s,n.bottom+1,"top",void 0))}}clearInsideBorders(e,t){for(const o of t)for(let t=o.top;t<=o.bottom;t++)for(let s=o.left;s<=o.right;s++)this.history.update("borders",e,s,t,void 0)}addBorder(e,t,o,s){this.setBorder(e,t,o,{...this.getCellBorder({sheetId:e,col:t,row:o}),...s})}setBorders(e,t,o,s){if("clear"===o)return this.clearBorders(e,t,!0);for(const i of nr(t)){if("all"===o)for(let t=i.top;t<=i.bottom;t++)for(let o=i.left;o<=i.right;o++)this.addBorder(e,o,t,{top:s,right:s,bottom:s,left:s});if("h"===o||"hv"===o){if(i.top===i.bottom)continue;for(let t=i.left;t<=i.right;t++){this.addBorder(e,t,i.top,{bottom:s});for(let o=i.top+1;o<i.bottom;o++)this.addBorder(e,t,o,{top:s,bottom:s});this.addBorder(e,t,i.bottom,{top:s})}}if("v"===o||"hv"===o){if(i.left===i.right)continue;for(let t=i.top;t<=i.bottom;t++){this.addBorder(e,i.left,t,{right:s});for(let o=i.left+1;o<i.right;o++)this.addBorder(e,o,t,{left:s,right:s});this.addBorder(e,i.right,t,{left:s})}}if("left"===o||"external"===o)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.left,t,{left:s});if("right"===o||"external"===o)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.right,t,{right:s});if("top"===o||"external"===o)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.top,{top:s});if("bottom"===o||"external"===o)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.bottom,{bottom:s})}}addBordersToMerge(e,t){const{left:o,right:s,top:i,bottom:n}=t,r=this.getCellBorder({sheetId:e,col:o,row:i}),a=this.getCellBorder({sheetId:e,col:s,row:n});this.clearBorders(e,[t]),r?.top&&this.setBorders(e,[{...t,bottom:i}],"top",r.top),r?.left&&this.setBorders(e,[{...t,right:o}],"left",r.left),a?.bottom?this.setBorders(e,[{...t,top:n}],"bottom",a.bottom):r?.bottom&&this.setBorders(e,[{...t,top:n}],"bottom",r.bottom),a?.right?this.setBorders(e,[{...t,left:s}],"right",a.right):r?.right&&this.setBorders(e,[{...t,left:s}],"right",r.right)}checkBordersUnchanged(e){const t=this.getCellBorder(e),o=!(e.border?.bottom||e.border?.left||e.border?.right||e.border?.top);return!t&&o||mt(t,e.border)?"NoChanges":"Success"}import(e){if(Object.keys(e.borders||{}).length)for(const t of e.sheets)for(const[o,s]of qr(t.id,t.borders)){const{sheetId:t,col:i,row:n}=o,r=e.borders[s];this.setBorder(t,i,n,r,!1)}for(const t of e.sheets)if(t.merges)for(const e of t.merges)this.addBordersToMerge(t.id,ur(e))}export(e){const t={};for(const o of e.sheets){const e={};for(let s=0;s<o.colNumber;s++)for(let i=0;i<o.rowNumber;i++){const n=this.getCellBorder({sheetId:o.id,col:s,row:i});if(n){const r=Gr(n,t),a={sheetId:o.id,col:s,row:i};e[r]??=[],e[r].push(a)}}o.borders=Wr(e)}e.borders=t}exportForExcel(e){this.export(e)}}).add("conditional formatting",class extends Nk{static getters=["getConditionalFormats","getRulesSelection","getRulesByCell","getAdaptedCfRanges"];cfRules={};adaptCFFormulas(e){for(const t in this.cfRules)for(const o of this.cfRules[t])if("DataBarRule"===o.rule.type&&o.rule.rangeValues){const s=e(o.rule.rangeValues);switch(s.changeType){case"REMOVE":this.history.update("cfRules",t,this.cfRules[t].indexOf(o),"rule","rangeValues",void 0);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",t,this.cfRules[t].indexOf(o),"rule","rangeValues",s.range)}}else if("CellIsRule"===o.rule.type)for(let s=0;s<o.rule.values.length;s++)this.history.update("cfRules",t,this.cfRules[t].indexOf(o),"rule","values",s,this.getters.adaptFormulaStringDependencies(t,o.rule.values[s],e));else if("IconSetRule"===o.rule.type)for(const s of["lowerInflectionPoint","upperInflectionPoint"])"formula"===o.rule[s].type&&this.history.update("cfRules",t,this.cfRules[t].indexOf(o),"rule",s,"value",this.getters.adaptFormulaStringDependencies(t,o.rule[s].value,e));else if("ColorScaleRule"===o.rule.type)for(const s of["minimum","maximum","midpoint"]){const i=o.rule[s];"formula"===i?.type&&i?.value&&this.history.update("cfRules",t,this.cfRules[t].indexOf(o),"rule",s,"value",this.getters.adaptFormulaStringDependencies(t,i.value,e))}}adaptCFRanges(e,t){for(const o of this.cfRules[e])for(const s of o.ranges){const i=t(s);switch(i.changeType){case"REMOVE":const t=o.ranges.slice();t.splice(o.ranges.indexOf(s),1),t.length>=1?this.history.update("cfRules",e,this.cfRules[e].indexOf(o),"ranges",t):this.removeConditionalFormatting(o.id,e);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",e,this.cfRules[e].indexOf(o),"ranges",o.ranges.indexOf(s),i.range)}}}adaptRanges(e,t){const o=t?[t]:Object.keys(this.cfRules);for(const t of o)this.adaptCFRanges(t,e);this.adaptCFFormulas(e)}allowDispatch(e){switch(e.type){case"ADD_CONDITIONAL_FORMAT":return e.ranges.some((e=>!this.getters.tryGetSheet(e._sheetId)))?"InvalidSheetId":this.checkValidations(e,this.checkCFRule,this.checkEmptyRange,this.checkCFHasChanged);case"CHANGE_CONDITIONAL_FORMAT_PRIORITY":return this.checkValidPriorityChange(e.cfId,e.delta,e.sheetId)}return"Success"}handle(e){switch(e.type){case"CREATE_SHEET":this.cfRules[e.sheetId]=[];break;case"DUPLICATE_SHEET":this.history.update("cfRules",e.sheetIdTo,[]);for(const t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case"DELETE_SHEET":const t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update("cfRules",t);break;case"ADD_CONDITIONAL_FORMAT":const o={...e.cf,ranges:e.ranges.map((t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId)))};this.addConditionalFormatting(o,e.sheetId);break;case"REMOVE_CONDITIONAL_FORMAT":this.removeConditionalFormatting(e.id,e.sheetId);break;case"CHANGE_CONDITIONAL_FORMAT_PRIORITY":this.changeCFPriority(e.cfId,e.delta,e.sheetId)}}import(e){for(const t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map((e=>this.mapToConditionalFormatInternal(t.id,e)))}export(e){if(e.sheets)for(const t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map((e=>this.mapToConditionalFormat(t.id,e))))}exportForExcel(e){if(e.sheets)for(const t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map((e=>this.mapToConditionalFormat(t.id,e,{useBoundedReference:!0}))))}getConditionalFormats(e){return this.cfRules[e]?.map((t=>this.mapToConditionalFormat(e,t)))||[]}getRulesSelection(e,t){const o=new Set;return t.forEach((t=>{this.getRulesByZone(e,t).forEach((e=>{o.add(e)}))})),Array.from(o)}getRulesByZone(e,t){const o=new Set;for(let s=t.top;s<=t.bottom;s++)for(let i=t.left;i<=t.right;i++){this.getRulesByCell(e,i,s).forEach((e=>{o.add(e.id)}))}return o}getRulesByCell(e,t,o){const s=[];for(const i of this.cfRules[e])for(const e of i.ranges)Er(t,o,e.zone)&&s.push(i);return new Set(s.map((t=>this.mapToConditionalFormat(e,t))))}getAdaptedCfRanges(e,t,o,s){if(0===o.length&&0===s.length)return;const i=this.getters.getConditionalFormats(e),n=i.findIndex((e=>e.id===t.id));let r=[];n>-1&&(r=i[n].ranges.map(dr));const a=nr(r,s);return nr([...o,...a],[]).map((t=>this.getters.getRangeDataFromZone(e,t)))}mapToConditionalFormat(e,t,{useBoundedReference:o}={useBoundedReference:!1}){const s=t.ranges.map((t=>this.getters.getRangeString(t,e,{useBoundedReference:o})));return"DataBarRule"!==t.rule.type?{...t,rule:{...t.rule},ranges:s}:{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues&&this.getters.getRangeString(t.rule.rangeValues,e,{useBoundedReference:o})},ranges:s}}mapToConditionalFormatInternal(e,t){const o=t.ranges.map((t=>this.getters.getRangeFromSheetXC(e,t)));return"DataBarRule"!==t.rule.type?{...t,rule:{...t.rule},ranges:o}:{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues?this.getters.getRangeFromSheetXC(e,t.rule.rangeValues):void 0},ranges:o}}addConditionalFormatting(e,t){const o=this.cfRules[t].slice(),s=o.findIndex((t=>t.id===e.id)),i=this.mapToConditionalFormatInternal(t,e);s>-1?o.splice(s,1,i):o.push(i),this.history.update("cfRules",t,o)}checkValidPriorityChange(e,t,o){if(!this.cfRules[o])return"InvalidSheetId";const s=this.cfRules[o].findIndex((t=>t.id===e));if(-1===s)return"InvalidConditionalFormatId";const i=s-t;return i<0||i>=this.cfRules[o].length?"InvalidConditionalFormatId":"Success"}checkEmptyRange(e){return e.ranges.length?"Success":"EmptyRange"}checkCFRule(e){const t=e.cf.rule;switch(t.type){case"CellIsRule":return this.checkValidations(t,this.checkOperatorArgsNumber,this.checkCFValues);case"ColorScaleRule":return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case"IconSetRule":return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)))}return"Success"}checkCFHasChanged(e){const t=this.mapToConditionalFormatInternal(e.sheetId,{...e.cf,ranges:e.ranges.map((t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId)))}),o=this.cfRules[e.sheetId]?.find((t=>t.id===e.cf.id));return o&&mt(t,o)?"NoChanges":"Success"}checkOperatorArgsNumber(e){const t=eE.get(e.operator).numberOfValues({type:e.operator,values:e.values});if(void 0===t||t>2)throw new Error("Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.");const o=[],s=e=>void 0===e||""===e;return t>=1&&s(e.values[0])&&o.push("FirstArgMissing"),t>=2&&s(e.values[1])&&o.push("SecondArgMissing"),o.length?o:"Success"}checkNaN(e,t){if(["number","percentage","percentile"].includes(e.type)&&(""===e.value||isNaN(e.value)))switch(t){case"min":return"MinNaN";case"max":return"MaxNaN";case"mid":return"MidNaN";case"upperInflectionPoint":return"ValueUpperInflectionNaN";case"lowerInflectionPoint":return"ValueLowerInflectionNaN"}return"Success"}checkFormulaCompilation(e,t){if("formula"!==e.type)return"Success";if(HS(e.value||"").isBadExpression)switch(t){case"min":return"MinInvalidFormula";case"max":return"MaxInvalidFormula";case"mid":return"MidInvalidFormula";case"upperInflectionPoint":return"ValueUpperInvalidFormula";case"lowerInflectionPoint":return"ValueLowerInvalidFormula"}return"Success"}checkThresholds(e){return this.batchValidations((t=>e(t.minimum,"min")),(t=>e(t.maximum,"max")),(t=>t.midpoint?e(t.midpoint,"mid"):"Success"))}checkInflectionPoints(e){return this.batchValidations((t=>e(t.lowerInflectionPoint,"lowerInflectionPoint")),(t=>e(t.upperInflectionPoint,"upperInflectionPoint")))}checkLowerBiggerThanUpper(e){const t=e.lowerInflectionPoint.value,o=e.upperInflectionPoint.value;return["number","percentage","percentile"].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(o)?"LowerBiggerThanUpper":"Success"}checkMinBiggerThanMax(e){const t=e.minimum.value,o=e.maximum.value;return["number","percentage","percentile"].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&Lk(t)>=Lk(o)?"MinBiggerThanMax":"Success"}checkMidBiggerThanMax(e){const t=e.midpoint?.value,o=e.maximum.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&Lk(t)>=Lk(o)?"MidBiggerThanMax":"Success"}checkMinBiggerThanMid(e){const t=e.minimum.value,o=e.midpoint?.value;return e.midpoint&&["number","percentage","percentile"].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&Lk(t)>=Lk(o)?"MinBiggerThanMid":"Success"}checkCFValues(e){for(const t of e.values){if(!t.startsWith("="))continue;if(HS(t||"").isBadExpression)return"ValueCellIsInvalidFormula"}return"Success"}removeConditionalFormatting(e,t){const o=this.cfRules[t].findIndex((t=>t.id===e));if(-1!==o){const e=this.cfRules[t].slice();e.splice(o,1),this.history.update("cfRules",t,e)}}changeCFPriority(e,t,o){const s=this.cfRules[o].findIndex((t=>t.id===e)),i=this.cfRules[o][s],n=s-t,r=[...this.cfRules[o]];r.splice(s,1),r.splice(n,0,i),this.history.update("cfRules",o,r)}}).add("figures",class extends Nk{static getters=["getFigures","getFigure","getFigureSheetId"];figures={};insertionOrders=[];adaptRanges(e,t){for(const o of this.getFigures(t)){const s=e(this.getters.getRangeFromZone(t,{left:o.col,right:o.col,top:o.row,bottom:o.row}));if("MOVE"===s.changeType)this.history.update("figures",t,o.id,"col",s.range.zone.right),this.history.update("figures",t,o.id,"row",s.range.zone.bottom);else if("REMOVE"===s.changeType){const s=e(this.getters.getRangeFromZone(t,{left:0,right:o.col-1,top:0,bottom:o.row-1}));let{offset:i,col:n,row:r}=o;"NONE"!==s.changeType&&(n=s.range.zone.right+1,r=s.range.zone.bottom+1),({offset:i,col:n,row:r}=this.getPositionInSheet(t,{...o,col:n,row:r})),this.history.update("figures",t,o.id,"offset",i),this.history.update("figures",t,o.id,"col",n),this.history.update("figures",t,o.id,"row",r)}}}allowDispatch(e){switch(e.type){case"CREATE_FIGURE":return this.checkValidations(e,this.checkFigureDuplicate,this.checkFigureAnchorOffset);case"UPDATE_FIGURE":return this.checkValidations(e,this.checkFigureExists,this.checkFigureAnchorOffset);case"DELETE_FIGURE":return this.checkFigureExists(e);default:return"Success"}}beforeHandle(e){if("DELETE_SHEET"===e.type)this.getters.getFigures(e.sheetId).forEach((t=>{this.dispatch("DELETE_FIGURE",{figureId:t.id,sheetId:e.sheetId})}))}handle(e){switch(e.type){case"CREATE_SHEET":this.figures[e.sheetId]={};break;case"DELETE_SHEET":this.deleteSheet(e.sheetId);break;case"CREATE_FIGURE":const t={id:e.figureId,col:e.col,row:e.row,offset:e.offset,width:e.size.width,height:e.size.height,tag:e.tag};this.addFigure(t,e.sheetId);break;case"UPDATE_FIGURE":this.updateFigure(e);break;case"DELETE_FIGURE":this.removeFigure(e.figureId,e.sheetId);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.onColRemove(e.sheetId):this.onRowRemove(e.sheetId)}}onColRemove(e){const t=this.getters.getNumberCols(e),o=new Array(t+1);o[t]=0;for(let s=t-1;s>=0;s--)o[s]=o[s+1]+this.getters.getColSize(e,s);for(const t of this.getFigures(e))if(t.offset.x+t.width>o[t.col]){let s=t.offset.x,i=t.col;for(s=Math.min(s,o[i]-t.width);s<0&&i>0;)i--,s=o[i]-t.width;s!==t.offset.x&&this.history.update("figures",e,t.id,"offset",{x:Math.max(s,0),y:t.offset.y}),i!==t.col&&this.history.update("figures",e,t.id,"col",i)}}onRowRemove(e){const t=this.getters.getNumberRows(e),o=new Array(t+1);o[t]=0;for(let s=t-1;s>=0;s--)o[s]=o[s+1]+(this.getters.getUserRowSize(e,s)??ie);for(const t of this.getFigures(e))if(t.offset.y+t.height>o[t.row]){let s=t.offset.y,i=t.row;for(let t=this.getters.getUserRowSize(e,i)??ie;t<s;t=this.getters.getUserRowSize(e,i)??ie)i+=1,s-=t;for(s=Math.min(s,o[i]-t.height);s<0&&i>0;)i--,s=o[i]-t.height;s!==t.offset.y&&this.history.update("figures",e,t.id,"offset",{x:t.offset.x,y:Math.max(0,s)}),i!==t.row&&this.history.update("figures",e,t.id,"row",i)}else t.offset.y+t.height>o[0]&&this.history.update("figures",e,t.id,"offset",{x:t.offset.x,y:Math.max(o[0]-t.height,0)})}getPositionInSheet(e,t){const{numberOfRows:o,numberOfCols:s}=this.getters.getSheetSize(e);let i,n,r=0,a=0,{col:l,row:c}=t;const h={...t.offset};for(i=o;r<t.height&&i>0;i--)r+=this.getters.getUserRowSize(e,i-1)??ie;for(c>i?(c=i,h.y=Math.max(r-t.height,0)):c===i&&(h.y=Ze(h.y,0,Math.max(r-t.height,0))),n=s;a<t.width&&n>0;n--)a+=this.getters.getColSize(e,n-1);return l>n?(l=n,h.x=Math.max(a-t.width,0)):n===l&&(h.x=Ze(h.x,0,Math.max(a-t.width,0))),{col:l,row:c,offset:h}}updateFigure(e){if(!("figureId"in e)||!("sheetId"in e))return;const{figureId:t,sheetId:o,...s}=e,i={...this.getFigure(o,t),...s};for(const[e,t]of Object.entries(s))switch(e){case"offset":this.history.update("figures",o,i.id,e,t);break;case"col":case"row":case"width":case"height":void 0!==t&&this.history.update("figures",o,i.id,e,t)}}addFigure(e,t){this.history.update("figures",t,e.id,e),this.history.update("insertionOrders",this.insertionOrders.length,e.id)}deleteSheet(e){this.history.update("insertionOrders",this.insertionOrders.filter((t=>!this.figures[e]?.[t]))),this.history.update("figures",e,void 0)}removeFigure(e,t){this.history.update("insertionOrders",this.insertionOrders.filter((t=>t!==e))),this.history.update("figures",t,e,void 0)}checkFigureExists(e){return void 0===this.figures[e.sheetId]?.[e.figureId]?"FigureDoesNotExist":"Success"}checkFigureDuplicate(e){return Object.values(this.figures).find((t=>t?.[e.figureId]))?"DuplicatedFigureId":"Success"}checkFigureAnchorOffset(e){return e.col<0||e.row<0||e.offset&&(e.offset.x<0||e.offset.y<0)?"WrongSheetPosition":"Success"}getFigures(e){const t=[];for(const o of this.insertionOrders){const s=this.figures[e]?.[o];s&&t.push(s)}return t}getFigure(e,t){return this.figures[e]?.[t]}getFigureSheetId(e){return Object.keys(this.figures).find((t=>void 0!==this.figures[t]?.[e]))}import(e){for(const t of e.sheets)for(const e of t.figures)this.addFigure(e,t.id)}export(e){for(const t of e.sheets)for(const e of this.getFigures(t.id)){const o=void 0;t.figures.push({...e,data:o})}}exportForExcel(e){return this.export(e)}}).add("chart",class extends Nk{static getters=["isChartDefined","getChartDefinition","getChartType","getChartIds","getChart","getContextCreationChart"];charts={};createChart=ax(this.getters);validateChartDefinition=e=>cx(this,e.definition);adaptRanges(e,t,o){for(const[s,i]of Object.entries(this.charts))this.history.update("charts",s,i?.updateRanges(e,t,o))}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,this.checkChartChanged));default:return"Success"}}handle(e){switch(e.type){case"CREATE_CHART":this.addFigure(e.figureId,e.sheetId,e.col,e.row,e.offset,e.size),this.addChart(e.figureId,e.definition);break;case"UPDATE_CHART":this.addChart(e.figureId,e.definition);break;case"DUPLICATE_SHEET":{const t=this.getters.getFigures(e.sheetId);for(const o of t)if("chart"===o.tag){const t=o.id.split(we).pop(),s=`${e.sheetIdTo}${we}${t}`,i=this.charts[o.id]?.duplicateInDuplicatedSheet(e.sheetIdTo);i&&this.dispatch("CREATE_CHART",{figureId:s,col:o.col,row:o.row,offset:o.offset,size:{width:o.width,height:o.height},definition:i.getDefinition(),sheetId:e.sheetIdTo})}break}case"DELETE_FIGURE":this.history.update("charts",e.figureId,void 0);break;case"DELETE_SHEET":for(const t of this.getChartIds(e.sheetId))this.history.update("charts",t,void 0)}}getContextCreationChart(e){return this.charts[e]?.getContextCreation()}getChart(e){return this.charts[e]}getChartType(e){const t=this.charts[e]?.type;if(!t)throw new Error("Chart not defined.");return t}isChartDefined(e){return e in this.charts&&void 0!==this.charts}getChartIds(e){return Object.entries(this.charts).filter((([,t])=>t?.sheetId===e)).map((([e])=>e))}getChartDefinition(e){const t=this.charts[e]?.getDefinition();if(!t)throw new Error(`There is no chart with the given figureId: ${e}`);return t}import(e){for(const t of e.sheets)if(t.figures)for(const e of t.figures)"chart"===e.tag&&(this.charts[e.id]=this.createChart(e.id,e.data,t.id))}export(e){if(e.sheets)for(const t of e.sheets){const e=this.getters.getFigures(t.id),o=[];for(const t of e){const e=t;if(e&&"chart"===e.tag){const t=this.charts[e.id]?.getDefinition();t&&(e.data=t,o.push(e))}else o.push(e)}t.figures=o}}addFigure(e,t,o,s,i,n={width:536,height:335}){this.dispatch("CREATE_FIGURE",{sheetId:t,figureId:e,col:o,row:s,offset:i,size:n,tag:"chart"})}addChart(e,t){const o=this.getters.getFigureSheetId(e);o&&this.history.update("charts",e,this.createChart(e,t,o))}checkChartDuplicate(e){return this.getters.getFigureSheetId(e.figureId)?"DuplicatedChartId":"Success"}checkChartExists(e){return this.isChartDefined(e.figureId)?"Success":"ChartDoesNotExist"}checkChartChanged(e){return mt(this.getChartDefinition(e.figureId),e.definition)?"NoChanges":"Success"}}).add("image",class extends Nk{static getters=["getImage","getImagePath","getImageSize"];fileStore;images={};syncedImages=new Set;constructor(e){super(e),this.fileStore=e.external.fileStore}allowDispatch(e){return"CREATE_IMAGE"===e.type&&this.getters.getFigure(e.sheetId,e.figureId)?"InvalidFigureId":"Success"}handle(e){switch(e.type){case"CREATE_IMAGE":this.addFigure(e.figureId,e.sheetId,e.col,e.row,e.offset,e.size),this.history.update("images",e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case"DUPLICATE_SHEET":{const t=this.getters.getFigures(e.sheetId);for(const o of t)if("image"===o.tag){const t=o.id.split(we).pop(),s=`${e.sheetIdTo}${we}${t}`,i=this.getImage(o.id);if(i){const t={width:o.width,height:o.height};this.dispatch("CREATE_IMAGE",{sheetId:e.sheetIdTo,figureId:s,offset:o.offset,col:o.col,row:o.row,size:t,definition:ze(i)})}}break}case"DELETE_FIGURE":this.history.update("images",e.sheetId,e.figureId,void 0);break;case"DELETE_SHEET":this.history.update("images",e.sheetId,void 0)}}garbageCollectExternalResources(){const e=new Set(this.getAllImages().map((e=>e.path)));for(const t of this.syncedImages)e.has(t)||this.fileStore?.delete(t)}getImage(e){for(const t of Object.values(this.images))if(t&&t[e])return t[e];throw new Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addFigure(e,t,o,s,i,n){this.dispatch("CREATE_FIGURE",{sheetId:t,figureId:e,col:o,row:s,offset:i,size:n,tag:"image"})}import(e){for(const t of e.sheets){const e=(t.figures||[]).filter((e=>"image"===e.tag));for(const o of e)this.history.update("images",t.id,o.id,o.data),this.syncedImages.add(o.data.path)}}export(e){for(const t of e.sheets){const e=t.figures.filter((e=>"image"===e.tag));for(const o of e)o.data=this.images[t.id]?.[o.id]}}exportForExcel(e){for(const t of e.sheets){t.images||(t.images=[]);const e=this.getters.getFigures(t.id),o=[];for(const t of e)if("image"===t?.tag){const e=this.getImage(t.id);e&&o.push({...t,data:ze(e)})}t.images=[...t.images,...o]}}getAllImages(){const e=[];for(const t in this.images)e.push(...Object.values(this.images[t]||{}).filter(lt));return e}}).add("pivot_core",class extends Nk{static getters=["getPivotCoreDefinition","getPivotDisplayName","getPivotId","getPivotFormulaId","getPivotIds","getMeasureCompiledFormula","getPivotName","isExistingPivot"];nextFormulaId=1;pivots={};formulaIds={};compiledMeasureFormulas={};allowDispatch(e){switch(e.type){case"ADD_PIVOT":return this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures);case"UPDATE_PIVOT":return e.pivotId in this.pivots?mt(e.pivot,this.pivots[e.pivotId]?.definition)?"NoChanges":""===e.pivot.name?"EmptyName":this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures):"PivotIdNotFound";case"RENAME_PIVOT":if(!(e.pivotId in this.pivots))return"PivotIdNotFound";if(""===e.name)return"EmptyName";break;case"REMOVE_PIVOT":case"DUPLICATE_PIVOT":case"INSERT_PIVOT":case"DUPLICATE_PIVOT":if(!(e.pivotId in this.pivots))return"PivotIdNotFound"}return"Success"}handle(e){switch(e.type){case"ADD_PIVOT":{const{pivotId:t,pivot:o}=e;this.addPivot(t,o);break}case"INSERT_PIVOT":{const{sheetId:t,col:o,row:s,pivotId:i,table:n}=e,r={sheetId:t,col:o,row:s},{cols:a,rows:l,measures:c,fieldsType:h}=n,d=new qN(a,l,c,h||{}),u=this.getPivotFormulaId(i);this.insertPivot(r,u,d);break}case"RENAME_PIVOT":this.history.update("pivots",e.pivotId,"definition","name",e.name);break;case"REMOVE_PIVOT":{const t={...this.pivots};delete t[e.pivotId];const o=this.getPivotFormulaId(e.pivotId);this.history.update("formulaIds",o,void 0),this.history.update("pivots",t);break}case"DUPLICATE_PIVOT":{const{pivotId:t,newPivotId:o}=e,s=ze(this.getPivotCore(t).definition);s.name=e.duplicatedPivotName??s.name+" (copy)",this.addPivot(o,s);break}case"UPDATE_PIVOT":this.history.update("pivots",e.pivotId,"definition",ze(e.pivot)),this.compileCalculatedMeasures(e.pivot.measures)}}adaptRanges(e){for(const t in this.compiledMeasureFormulas)for(const o in this.compiledMeasureFormulas[t]){const s=this.compiledMeasureFormulas[t][o],i=[];for(const t of s.dependencies){const o=e(t);"NONE"===o.changeType?i.push(t):i.push(o.range)}const n=this.getters.getFormulaString(t,s.tokens,i);n!==o&&this.replaceMeasureFormula(t,o,n)}}getPivotDisplayName(e){return`(#${this.getPivotFormulaId(e)}) ${this.getPivotName(e)}`}getPivotName(e){return this.getPivotCore(e).definition.name}getPivotCoreDefinition(e){return this.getPivotCore(e).definition}getPivotId(e){return this.formulaIds[e]}getPivotFormulaId(e){return this.getPivotCore(e).formulaId}getPivotIds(){return Object.keys(this.pivots)}isExistingPivot(e){return e in this.pivots}getMeasureCompiledFormula(e){if(!e.computedBy)throw new Error(`Measure ${e.fieldName} is not computed by formula`);const t=e.computedBy.sheetId;return this.compiledMeasureFormulas[t][e.computedBy.formula]}addPivot(e,t,o=this.nextFormulaId.toString()){this.history.update("pivots",e,{definition:ze(t),formulaId:o}),this.compileCalculatedMeasures(t.measures),this.history.update("formulaIds",o,e),this.history.update("nextFormulaId",this.nextFormulaId+1)}compileCalculatedMeasures(e){for(const t of e)if(t.computedBy){const e=t.computedBy.sheetId,o=this.compileMeasureFormula(t.computedBy.sheetId,t.computedBy.formula);this.history.update("compiledMeasureFormulas",e,t.computedBy.formula,o)}}insertPivot(e,t,o){this.resizeSheet(e.sheetId,e,o);const s=o.getPivotCells();for(let o=0;o<s.length;o++)for(let i=0;i<s[o].length;i++){const n=s[o][i];this.dispatch("UPDATE_CELL",{sheetId:e.sheetId,col:e.col+o,row:e.row+i,content:$c(t,n)})}}resizeSheet(e,{col:t,row:o},s){const i=s.getNumberOfDataColumns()+1,n=this.getters.getNumberCols(e),r=n-t;r<i&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:n-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-r,position:"after"});const a=s.columns.length+s.rows.length,l=this.getters.getNumberRows(e),c=l-o;c<a&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:l-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:a-c,position:"after"})}getPivotCore(e){const t=this.pivots[e];if(!t)throw new Error(`Pivot with id ${e} not found`);return t}compileMeasureFormula(e,t){const o=HS(t),s=o.dependencies.map((t=>this.getters.getRangeFromSheetXC(e,t)));return{...o,dependencies:s}}replaceMeasureFormula(e,t,o){this.history.update("compiledMeasureFormulas",e,t,void 0),this.history.update("compiledMeasureFormulas",e,o,this.compileMeasureFormula(e,o));for(const s in this.pivots){const i=this.pivots[s];if(i)for(const n of i.definition.measures)if(n.computedBy?.formula===t){const t=i.definition.measures.indexOf(n);this.history.update("pivots",s,"definition","measures",t,"computedBy",{formula:o,sheetId:e})}}}checkSortedColumnInMeasures(e){const t=e.measures.map((e=>e.id));return e.sortedColumn&&!t.includes(e.sortedColumn.measure)?"InvalidDefinition":"Success"}checkDuplicatedMeasureIds(e){const t=new Set(e.measures.map((e=>e.id)));return e.measures.length!==t.size?"InvalidDefinition":"Success"}import(e){if(e.pivots)for(const[t,o]of Object.entries(e.pivots))this.addPivot(t,o,o.formulaId);this.history.update("nextFormulaId",e.pivotNextId||kc(this.pivots)+1)}export(e){e.pivots={};for(const t in this.pivots)e.pivots[t]={...this.getPivotCoreDefinition(t),formulaId:this.getPivotFormulaId(t)};e.pivotNextId=this.nextFormulaId}}).add("spreadsheet_pivot_core",class extends Nk{allowDispatch(e){switch(e.type){case"ADD_PIVOT":case"UPDATE_PIVOT":const t=e.pivot;return this.checkDataSetValidity(t)}return"Success"}adaptRanges(e){for(const t of this.getters.getPivotIds()){const o=this.getters.getPivotCoreDefinition(t);if("SPREADSHEET"===o.type&&o.dataSet){const{sheetId:s,zone:i}=o.dataSet,n=zk(this.getters.getRangeFromZone(s,i),e),r=n&&{sheetId:n.sheetId,zone:n.zone};this.dispatch("UPDATE_PIVOT",{pivotId:t,pivot:{...o,dataSet:r}})}}}checkDataSetValidity(e){if("SPREADSHEET"===e.type&&e.dataSet){const{zone:t,sheetId:o}=e.dataSet;return o&&this.getters.tryGetSheet(o)&&t&&pr(t)?this.getters.checkZonesExistInSheet(o,[t]):"InvalidDataSet"}return"Success"}}).add("tableStyle",class extends Nk{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(!HR[e.templateName])return"InvalidTableStyle";try{Gt(e.primaryColor)}catch(e){return"InvalidTableStyle"}}return"Success"}handle(e){switch(e.type){case"CREATE_TABLE_STYLE":const t=UR(e.tableStyleName,e.templateName,e.primaryColor);this.history.update("styles",e.tableStyleId,t);break;case"REMOVE_TABLE_STYLE":const o={...this.styles};delete o[e.tableStyleId],this.history.update("styles",o);for(const t of this.getters.getSheetIds())for(const o of this.getters.getCoreTables(t))o.config.styleId===e.tableStyleId&&this.dispatch("UPDATE_TABLE",{sheetId:t,zone:o.range.zone,config:{styleId:wR.styleId}})}}getTableStyle(e){if(!this.styles[e])throw new Error(`Table style ${e} does not exist`);return this.styles[e]}getTableStyles(){return this.styles}getNewCustomTableStyleName(){return Vt(Ho("Custom Table Style"),Object.values(this.styles).map((e=>e.displayName)),{compute:(e,t)=>`${e} ${t}`,start:2})}isTableStyleEditable(e){return!LR[e]}import(e){for(const e in LR)this.styles[e]=LR[e];for(const t in e.customTableStyles){const o=e.customTableStyles[t];this.styles[t]=UR(o.displayName,o.templateName,o.primaryColor)}}export(e){const t={};for(const e in this.styles)LR[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}}),EL=(new n).add("ui_sheet",class extends BV{static getters=["getCellWidth","getTextWidth","getCellText","getCellMultiLineText","getContiguousZone","computeTextYCoordinate"];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(const t of e.cols){const o=this.getColMaxWidth(e.sheetId,t);0!==o&&this.dispatch("RESIZE_COLUMNS_ROWS",{elements:[t],dimension:"COL",size:o,sheetId:e.sheetId})}break;case"AUTORESIZE_ROWS":this.autoResizeRows(e.sheetId,e.rows);break;case"DELETE_UNFILTERED_CONTENT":const t=[];for(const o of e.target){const s=Ye(je(o.top,o.bottom+1).filter((t=>!this.getters.isRowFiltered(e.sheetId,t))));for(const e of s)t.push({...o,top:e[0],bottom:e[e.length-1]})}this.dispatch("DELETE_CONTENT",{sheetId:e.sheetId,target:t})}}getCellWidth(e){const t=this.getters.getCellComputedStyle(e);let o=0;const s=this.getters.getEvaluatedCell(e).formattedValue;if(s){const e=Wa(this.ctx,s,t,void 0);o+=Math.max(...e.map((e=>Va(this.ctx,e,t))))}for(const t of this.getters.getCellIcons(e))o+=t.margin+t.size;if(this.getters.getDataValidationChipStyle(e)&&(o+=10),0===o)return 0;if(o+=2*le,"wrap"===t.wrapping){const t=this.getters.getColSize(this.getters.getActiveSheetId(),e.col);return Math.min(t,o)}return o}getTextWidth(e,t){return Va(this.ctx,e,t)}getCellText(e,t){const o=this.getters.getCell(e),s=this.getters.getLocale();if(t?.showFormula&&o?.isFormula)return Ol(o.content,s);if(t?.showFormula&&!o?.content)return"";{const i=this.getters.getEvaluatedCell(e),n=t?.availableWidth?{availableWidth:t.availableWidth,measureText:e=>Va(this.ctx,e,o?.style||{})}:void 0;return In(i.value,{format:i.format,locale:s,formatWidth:n})}}getCellMultiLineText(e,t){const o=this.getters.getCellStyle(e),s=this.getters.getCellText(e,{showFormula:this.getters.shouldShowFormulas(),availableWidth:t.maxWidth});return Wa(this.ctx,s,o,t.wrapText?t.maxWidth:void 0)}computeTextYCoordinate(e,t,o=ue,s=1){const i=e.y+1,n=Pa(t,s);if(e.height>n+2*re){if("middle"===o)return Math.ceil(i+(e.height-n)/2);if("bottom"===o)return i+e.height-n-re}return i+re}getContiguousZone(e,t){const o=t=>{for(const o of je(t.left,t.right+1)){if(!this.isCellEmpty({sheetId:e,col:o,row:t.top-1}))return{...t,top:t.top-1};if(!this.isCellEmpty({sheetId:e,col:o,row:t.bottom+1}))return{...t,bottom:t.bottom+1}}for(const o of je(t.top,t.bottom+1)){if(!this.isCellEmpty({sheetId:e,col:t.left-1,row:o}))return{...t,left:t.left-1};if(!this.isCellEmpty({sheetId:e,col:t.right+1,row:o}))return{...t,right:t.right+1}}return t};let s=!1,i=t;do{s=!1;const e=o(i);Ir(i,e)||(s=!0,i=e)}while(s);return i}isCellEmpty(e){const t=this.getters.getMainCellPosition(e);return this.getters.getEvaluatedCell(t).type===_s.empty}getColMaxWidth(e,t){const o=_r(this.getters.getColsZone(e,t,t)).map((t=>this.getCellWidth({sheetId:e,...t})));return Math.max(0,Ft(o))}checkSheetExists(e){return"sheetId"in e&&void 0===this.getters.tryGetSheet(e.sheetId)?"InvalidSheetId":"Success"}checkZonesAreInSheet(e){const t="sheetId"in e?e.sheetId:this.getters.tryGetActiveSheetId();if("ranges"in e&&e.ranges.some((e=>!this.getters.tryGetSheet(e._sheetId))))return"InvalidSheetId";const o=this.getters.getCommandZones(e);return!t&&o.length>0?"NoActiveSheet":t&&o.length>0?this.getters.checkZonesExistInSheet(t,o):"Success"}autoResizeRows(e,t){const o=[];for(const s of t){let t=0;for(const o of this.getters.getRowCells(e,s)){const s=this.getters.getCellById(o);if(!s)continue;const i=this.getters.getCellPosition(s.id),n=this.getters.getColSize(e,i.col);if(s.isFormula||this.getters.getArrayFormulaSpreadingOn(i)){const e=this.getters.getEvaluatedCell(i).formattedValue,o=Ma(this.ctx,e,s?.style,n);o>t&&o>ie&&(t=o)}else{const e=s.content,o=Ma(this.ctx,e,s?.style,n);o>=t&&o>ie&&(t=0)}}o.push(t||null)}const s=new Map(o.map((e=>[e,[]])));for(let e=0;e<o.length;e++)s.get(o[e])?.push(t[e]);for(const[t,o]of s)this.dispatch("RESIZE_COLUMNS_ROWS",{elements:o,dimension:"ROW",size:t,sheetId:e})}}).add("ui_options",class extends BV{static getters=["shouldShowFormulas"];showFormulas=!1;handle(e){if("SET_FORMULA_VISIBILITY"===e.type)this.showFormulas=e.show}shouldShowFormulas(){return this.showFormulas}}).add("autofill",class extends BV{static layers=["Autofill"];static getters=["getAutofillTooltip"];autofillZone;steps;lastCellSelected={};direction;tooltip;allowDispatch(e){if("AUTOFILL_SELECT"===e.type){const t=this.getters.getActiveSheetId();return this.lastCellSelected.col=-1===e.col?this.lastCellSelected.col:Ze(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=-1===e.row?this.lastCellSelected.row:Ze(e.row,0,this.getters.getNumberRows(t)),void 0!==this.lastCellSelected.col&&void 0!==this.lastCellSelected.row?"Success":"InvalidAutofillSelection"}return"Success"}handle(e){switch(e.type){case"AUTOFILL":this.autofill(!0);break;case"AUTOFILL_SELECT":this.select(e.col,e.row);break;case"AUTOFILL_AUTO":this.autofillAuto()}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||void 0===this.direction)return void(this.tooltip=void 0);const t=this.getters.getSelectedZone(),o=this.autofillZone,s=[];switch(this.direction){case"down":for(let e=t.left;e<=t.right;e++){const i=[];for(let o=t.top;o<=t.bottom;o++)i.push(Po(e,o));const n=this.createGenerator(i);for(let t=o.top;t<=o.bottom;t++)s.push(this.computeNewCell(n,e,t))}break;case"up":for(let e=t.left;e<=t.right;e++){const i=[];for(let o=t.bottom;o>=t.top;o--)i.push(Po(e,o));const n=this.createGenerator(i);for(let t=o.bottom;t>=o.top;t--)s.push(this.computeNewCell(n,e,t))}break;case"left":for(let e=t.top;e<=t.bottom;e++){const i=[];for(let o=t.right;o>=t.left;o--)i.push(Po(o,e));const n=this.createGenerator(i);for(let t=o.right;t>=o.left;t--)s.push(this.computeNewCell(n,t,e))}break;case"right":for(let e=t.top;e<=t.bottom;e++){const i=[];for(let o=t.left;o<=t.right;o++)i.push(Po(o,e));const n=this.createGenerator(i);for(let t=o.left;t<=o.right;t++)s.push(this.computeNewCell(n,t,e))}}if(e){const e={},t={},o={},i=this.getters.getActiveSheetId();for(const n of s)this.collectBordersData(n,e),this.autofillMerge(i,n),this.autofillCell(i,n),this.collectConditionalFormatsData(i,n,t),this.collectDataValidationsData(i,n,o);this.autofillBorders(i,e),this.autofillConditionalFormats(i,t),this.autofillDataValidations(i,o),this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0}}collectBordersData(e,t){const o=JSON.stringify(e.border);o in t||(t[o]=[]),t[o].push(Mr({col:e.col,row:e.row}))}collectConditionalFormatsData(e,t,o){const{originCol:s,originRow:i,col:n,row:r}=t,a=this.getters.getRulesByCell(e,s,i),l=Po(n,r);for(const e of a)e.id in o||(o[e.id]=[]),o[e.id].push(l)}collectDataValidationsData(e,t,o){const{originCol:s,originRow:i,col:n,row:r}=t,a={sheetId:e,col:s,row:i},l=this.getters.getValidationRuleForCell(a);l&&(l.id in o||(o[l.id]=[]),o[l.id].push(Mr({col:n,row:r})))}autofillCell(e,t){this.dispatch("UPDATE_CELL",{sheetId:e,col:t.col,row:t.row,content:t.content||"",style:t.style||null,format:t.format||""}),this.dispatch("AUTOFILL_CELL",t)}autofillBorders(e,t){for(const o in t){const s="undefined"===o?void 0:JSON.parse(o);this.dispatch("SET_BORDERS_ON_TARGET",{sheetId:e,border:s,target:nr(t[o])})}}autofillConditionalFormats(e,t){for(const o in t){const s=t[o],i=this.getters.getConditionalFormats(e).find((e=>e.id===o));if(!i)continue;const n=this.getters.getAdaptedCfRanges(e,i,s.map(ur),[]);n&&this.dispatch("ADD_CONDITIONAL_FORMAT",{cf:{id:i.id,rule:i.rule,stopIfTrue:i.stopIfTrue},ranges:n,sheetId:e})}}autofillDataValidations(e,t){for(const o in t){const s=t[o],i=this.getters.getDataValidationRule(e,o);if(!i)continue;const n=i.ranges.map((e=>e.zone)),r=nr(n.concat(s),[]);this.dispatch("ADD_DATA_VALIDATION_RULE",{rule:i,ranges:r.map((t=>this.getters.getRangeDataFromZone(e,t))),sheetId:e})}}select(e,t){const o=this.getters.getSelectedZone();if(Er(e,t,o))this.autofillZone=void 0;else{switch(this.direction=this.getDirection(e,t),this.direction){case"up":this.saveZone(t,o.top-1,o.left,o.right),this.steps=o.top-t;break;case"down":this.saveZone(o.bottom+1,t,o.left,o.right),this.steps=t-o.bottom;break;case"left":this.saveZone(o.top,o.bottom,e,o.left-1),this.steps=o.left-e;break;case"right":this.saveZone(o.top,o.bottom,o.right+1,e),this.steps=e-o.right}this.autofill(!1)}}autofillAuto(){const e=this.getters.getActivePosition(),t=this.getters.getTable(e);let o=t?t.range.zone.bottom:this.getAutofillAutoLastRow();const s=this.getters.getSelectedZone();for(let t=s.bottom+1;t<=o;t++)if(this.getters.getEvaluatedCell({...e,row:t}).type!==_s.empty){o=t-1;break}o>s.bottom&&(this.select(e.col,o),this.autofill(!0))}getAutofillAutoLastRow(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();let o=e.left,s=e.bottom;if(o>0){let e={sheetId:t,col:o-1,row:s};for(;this.getters.getEvaluatedCell(e).type!==_s.empty;)s+=1,e={sheetId:t,col:o-1,row:s}}if(s===e.bottom&&(o=e.right,o<=this.getters.getNumberCols(t))){let e={sheetId:t,col:o+1,row:s};for(;this.getters.getEvaluatedCell(e).type!==_s.empty;)s+=1,e={sheetId:t,col:o+1,row:s}}return s-1}computeNewCell(e,t,o){const{cellData:s,tooltip:i,origin:n}=e.next(),{content:r,style:a,border:l,format:c}=s;return this.tooltip=i,{originCol:n.col,originRow:n.row,col:t,row:o,content:r,style:a,border:l,format:c}}getRule(e,t){const o=MV.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((o=>o.condition(e,t)));return o&&this.direction&&o.generateRule(e,t,this.direction)}createGenerator(e){const t=[],o=[],s=this.getters.getActiveSheetId();for(const t of e){const{col:e,row:i}=Fo(t),n=this.getters.getCell({sheetId:s,col:e,row:i});o.push({col:e,row:i,cell:n,sheetId:s})}const i=o.map((e=>e.cell));for(const e of o){let o={type:"COPY_MODIFIER"};if(e&&e.cell){o=this.getRule(e.cell,i)||o}const s=this.getters.getCellBorder(e)||void 0;t.push({data:{...e,border:s},rule:o})}return new zV(t,this.getters,this.direction)}saveZone(e,t,o,s){this.autofillZone={top:e,bottom:t,left:o,right:s}}getDirection(e,t){const o=this.getters.getSelectedZone(),s={up:{number:o.top-t,value:"up"},down:{number:t-o.bottom,value:"down"},left:{number:o.left-e,value:"left"},right:{number:e-o.right,value:"right"}};if(1===Object.values(s).map((e=>e.number>0?1:0)).reduce(((e,t)=>e+t)))return Object.values(s).find((e=>e.number>0?1:0)).value;const i=s.up.number>0?"up":"down",n=s.left.number>0?"left":"right";return Math.abs(s[i].number)>=Math.abs(s[n].number)?s[i].value:s[n].value}autofillMerge(e,t){const{originCol:o,originRow:s,col:i,row:n}=t,r={sheetId:e,col:i,row:n},a={sheetId:e,col:o,row:s};if(this.getters.isInMerge(r)&&!this.getters.isInMerge(a)){const t=this.getters.getMerge(r);t&&this.dispatch("REMOVE_MERGE",{sheetId:e,target:[t]})}const l=this.getters.getMerge(a);l?.left===o&&l?.top===s&&this.dispatch("ADD_MERGE",{sheetId:e,target:[{top:n,bottom:n+l.bottom-l.top,left:i,right:i+l.right-l.left}]})}drawLayer(e){if(!this.autofillZone)return;const{ctx:t,thinLineWidth:o}=e,{x:s,y:i,width:n,height:r}=this.getters.getVisibleRect(this.autofillZone);n>0&&r>0&&(t.strokeStyle="black",t.lineWidth=o,t.setLineDash([3]),t.strokeRect(s,i,n,r),t.setLineDash([]))}}).add("sort",class extends BV{allowDispatch(e){return"SORT_CELLS"===e.type?Er(e.col,e.row,e.zone)?this.checkValidations(e,this.checkMerge,this.checkMergeSizes,this.checkArrayFormulaInSortZone):"InvalidSortAnchor":"Success"}handle(e){if("SORT_CELLS"===e.type)this.sortZone(e.sheetId,e,e.zone,e.sortDirection,e.sortOptions||{})}checkMerge({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return"Success";return _r(t).some((({col:t,row:o})=>!this.getters.isInMerge({sheetId:e,col:t,row:o})))?"InvalidSortZone":"Success"}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return"Success";const o=this.getters.getMerges(e).filter((e=>xr(e,t))),s=Tr(o[0]),[i,n]=[s.numberOfCols,s.numberOfRows];return o.every((e=>{const[t,o]=[e.right-e.left+1,e.bottom-e.top+1];return t===i&&o===n}))?"Success":"InvalidSortZone"}checkArrayFormulaInSortZone({sheetId:e,zone:t}){return _r(t).some((({col:t,row:o})=>{const s=this.getters.getArrayFormulaSpreadingOn({sheetId:e,col:t,row:o});return s&&!mt(s,{sheetId:e,col:t,row:o})}))?"SortZoneWithArrayFormulas":"Success"}hasHeader(e,t){if(1===t[0].length)return!1;let o=t.map((t=>t.map((({col:t,row:o})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:o}).type))));return o[0][0]===_s.empty&&(o=o.slice(1)),!o.some((e=>e[0]===_s.empty))&&!!o.some((e=>e[1]!==_s.empty&&e[0]!==e[1]))}sortZone(e,t,o,s,i){const[n,r]=this.mainCellsSteps(e,o),a=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,l=Object.assign({},o);let c=this.mainCells(e,o);!i.sortHeaders&&this.hasHeader(e,c)&&(l.top+=r),c=this.mainCells(e,l);const h=function(e,t,o){const s=e.map(((e,t)=>({index:t,type:e.type,value:e.value})));return(o?s.map((e=>e.type===_s.empty?{...e,type:_s.number,value:0}:e)):s).sort(jp(t))}(c[a-l.left].map((e=>this.getters.getEvaluatedCell(e))),s,Boolean(i.emptyCellAsZero)),d=h.map((e=>e.index)),[u,g]=[c.length,c[0].length],p=[];for(let e=0;e<u;e++)for(let t=0;t<g;t++){const{col:o,row:s,sheetId:i}=c[e][d[t]],a=this.getters.getCell({sheetId:i,col:o,row:s}),h=l.left+e*n,u=l.top+t*r,g={sheetId:i,col:h,row:u,content:""};if(a){let e=a.content;if(a.isFormula){const t=this.getters.getCellPosition(a.id);e=this.getters.getTranslatedCellFormula(i,0,u-t.row,a.compiledFormula.tokens)}g.style=a.style,g.content=e,g.format=a.format}p.push(g)}p.forEach((e=>this.dispatch("UPDATE_CELL",e)))}mainCellsSteps(e,t){const o=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[o?o.right-o.left+1:1,o?o.bottom-o.top+1:1]}mainCells(e,t){const[o,s]=this.mainCellsSteps(e,t),i=[],n=je(t.left,t.right+1,o),r=je(t.top,t.bottom+1,s);for(const t of n){const o=[];i.push(o);for(const s of r)o.push({sheetId:e,col:t,row:s})}return i}}).add("automatic_sum",class extends BV{static getters=["getAutomaticSums"];handle(e){if("SUM_SELECTION"===e.type){const e=this.getters.getActiveSheetId(),{zones:t,anchor:o}=this.getters.getSelection();for(const s of t){const t=this.getAutomaticSums(e,s,o.cell);this.dispatchCellUpdates(e,t)}}}getAutomaticSums(e,t,o){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,o):this.sumData(e,t)}sumData(e,t){const o=this.dimensionsToSum(e,t),s=this.sumDimensions(e,t,o).filter((({zone:t})=>!this.getters.isEmpty(e,t)));return o.has("ROW")&&o.has("COL")&&s.push(this.sumTotal(t)),s}sumAdjacentData(e,t,o){const{col:s,row:i}=Er(o.col,o.row,t)?o:{col:t.left,row:t.top},n=this.findAdjacentData(e,s,i);return n?this.getters.isSingleCellOrMerge(e,t)||Ar(yr(n,t))?[{position:{col:s,row:i},zone:n}]:this.sumDimensions(e,yr(n,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,o){const s=this.getters.getSheet(e),i=this.getters.getMainCellPosition({sheetId:e,col:t,row:o}),n=this.findSuitableZoneToSum(s,i.col,i.row);if(n)return this.getters.expandZone(e,n)}findSuitableZoneToSum(e,t,o){const s=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:o-1}),i=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:o});if(this.isNumber(i)&&!this.isNumber(s))return this.findHorizontalZone(e,t,o);const n=this.findVerticalZone(e,t,o);if(this.isZoneValid(n))return n;const r=this.findHorizontalZone(e,t,o);return this.isZoneValid(r)?r:void 0}findVerticalZone(e,t,o){const s={top:0,bottom:o-1,left:t,right:t},i=this.reduceZoneStart(e,s,s.bottom);return{...s,top:i}}findHorizontalZone(e,t,o){const s={top:o,bottom:o,left:0,right:t-1},i=this.reduceZoneStart(e,s,s.right);return{...s,left:i}}reduceZoneStart(e,t,o){const s=this.getters.getEvaluatedCellsInZone(e.id,t),i=je(o,-1,-1),n=Ft(i.filter((e=>s[e]&&!s[e].isAutoSummable))),r=Ye(i.filter((e=>this.isNumber(s[e]))))[0]||[];return Ft(r)<n?1/0:Pt(r)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===_s.number&&!(e.format&&On(e.format))}isZoneValid(e){return e.bottom>=e.top&&e.right>=e.left}lastColIsEmpty(e,t){return this.getters.isEmpty(e,{...t,left:t.right})}lastRowIsEmpty(e,t){return this.getters.isEmpty(e,{...t,top:t.bottom})}dimensionsToSum(e,t){const o=new Set;return Ar(t)?(o.add(1===Tr(t).numberOfCols?"COL":"ROW"),o):(this.lastColIsEmpty(e,t)&&o.add("ROW"),this.lastRowIsEmpty(e,t)&&o.add("COL"),0===o.size&&o.add("COL"),o)}sumDimensions(e,t,o){return[...o.has("COL")?this.sumColumns(t,e):[],...o.has("ROW")?this.sumRows(t,e):[]]}sumTotal(e){const{bottom:t,right:o}=e;return{position:{col:o,row:t},zone:{...e,top:t,right:o-1}}}sumColumns(e,t){const o=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,o.bottom-1)},_r(o).map((t=>({position:t,zone:{...e,right:t.col,left:t.col}})))}sumRows(e,t){const o=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,o.right-1)},_r(o).map((t=>({position:t,zone:{...e,top:t.row,bottom:t.row}})))}dispatchCellUpdates(e,t){for(const o of t){const{col:t,row:s}=o.position;this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:s,content:`=SUM(${this.getters.zoneToXC(e,o.zone)})`})}}nextEmptyRow(e,t){let o=t.bottom+1;const{left:s,right:i}=t;for(;!this.getters.isEmpty(e,{bottom:o,top:o,left:s,right:i});)o++;return{...t,top:o,bottom:o}}nextEmptyCol(e,t){let o=t.right+1;const{top:s,bottom:i}=t;for(;!this.getters.isEmpty(e,{left:o,right:o,top:s,bottom:i});)o++;return{...t,left:o,right:o}}transpose(e){return new Set([...e.values()].map((e=>"COL"===e?"ROW":"COL")))}}).add("format",class extends BV{handle(e){switch(e.type){case"SET_DECIMAL":this.setDecimal(e.sheetId,e.target,e.step);break;case"SET_FORMATTING_WITH_PIVOT":this.setContextualFormat(e.sheetId,e.target,e.format)}}setContextualFormat(e,t,o){const s=[],i={};for(const o of nr(t))for(let t=o.left;t<=o.right;t++)for(let n=o.top;n<=o.bottom;n++){const o={sheetId:e,col:t,row:n},r=this.getters.getPivotCellFromPosition(o);if(this.isSpilledPivotValueFormula(o,r)){s.push(o);const e=this.getters.getPivotIdFromPosition(o)||"";i[e]??=new Set,i[e].add(r.measure)}}const n=nr(s.map(Mr));for(const e in i){const t=i[e],s=this.getters.getPivotCoreDefinition(e);this.dispatch("UPDATE_PIVOT",{pivotId:e,pivot:{...s,measures:s.measures.map((e=>t.has(e.id)?{...e,format:o}:e))}})}this.dispatch("SET_FORMATTING",{sheetId:e,target:n,format:""}),this.dispatch("SET_FORMATTING",{sheetId:e,target:nr(t,n),format:o})}isSpilledPivotValueFormula(e,t){const o=this.getters.getCell(e);return"VALUE"===t.type&&!o?.isFormula}setDecimal(e,t,o){const s={};for(const i of nr(t))for(const t of _r(i)){const i=this.getCellNumberFormat({sheetId:e,...t});if(void 0!==i){const e=qn(i,o);s[e]=s[e]||[],s[e].push(t)}}for(const t in s){const o=nr(s[t].map((e=>Mr(e))));this.setContextualFormat(e,o,t)}}getCellNumberFormat(e){for(const t of[e]){const e=this.getters.getEvaluatedCell(t);if(!(e.type!==_s.number||e.format&&On(e.format)))return e.format||Mn(e.value)}}}).add("insert_pivot",class extends BV{static getters=[];allowDispatch(e){if("DUPLICATE_PIVOT_IN_NEW_SHEET"===e.type){if(!this.getters.isExistingPivot(e.pivotId))return"PivotIdNotFound";if(!this.getters.getPivot(e.pivotId).isValid())return"PivotInError"}return"Success"}handle(e){switch(e.type){case"INSERT_NEW_PIVOT":this.insertNewPivot(e.pivotId,e.newSheetId);break;case"DUPLICATE_PIVOT_IN_NEW_SHEET":this.duplicatePivotInNewSheet(e.pivotId,e.newPivotId,e.newSheetId);break;case"INSERT_PIVOT_WITH_TABLE":this.insertPivotWithTable(e.sheetId,e.col,e.row,e.pivotId,e.table,e.pivotMode);break;case"SPLIT_PIVOT_FORMULA":this.splitPivotFormula(e.sheetId,e.col,e.row,e.pivotId)}}insertNewPivot(e,t){1===Lr(this.getters.getSelectedZone())&&this.selection.selectTableAroundSelection();const o=this.getters.getActiveSheetId();this.dispatch("ADD_PIVOT",{pivotId:e,pivot:{dataSet:{zone:this.getters.getSelectedZone(),sheetId:o},columns:[],rows:[],measures:[],name:Ho("New pivot"),type:"SPREADSHEET"}});const s=this.getters.getSheetIds().findIndex((e=>e===o))+1,i=this.getters.getPivotFormulaId(e);this.dispatch("CREATE_SHEET",{sheetId:t,name:Ho("Pivot #%(formulaId)s",{formulaId:i}),position:s}),this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:o,sheetIdTo:t});const n=this.getters.getPivot(e);this.insertPivotWithTable(t,0,0,e,n.getCollapsedTableStructure().export(),"dynamic")}duplicatePivotInNewSheet(e,t,o){this.dispatch("DUPLICATE_PIVOT",{pivotId:e,newPivotId:t,duplicatedPivotName:Ho("%s (copy)",this.getters.getPivotCoreDefinition(e).name)});const s=this.getters.getActiveSheetId(),i=this.getters.getSheetIds().indexOf(s)+1,n=this.getters.getPivotFormulaId(t),r=this.getters.getPivotName(t);if(this.dispatch("CREATE_SHEET",{sheetId:o,name:this.getPivotDuplicateSheetName(Ho("%(newPivotName)s (Pivot #%(formulaId)s)",{newPivotName:r,formulaId:n})),position:i}).isSuccessful){this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:s,sheetIdTo:o});const i=this.getters.getPivot(e);this.insertPivotWithTable(o,0,0,t,i.getCollapsedTableStructure().export(),"dynamic")}}getPivotDuplicateSheetName(e){const t=this.getters.getSheetIds().map((e=>this.getters.getSheetName(e)));return Vt(qe(e),t)}insertPivotWithTable(e,t,o,s,i,n){const{cols:r,rows:a,measures:l,fieldsType:c}=i,h=new qN(r,a,l,c||{}),d=h.columns.length-1;this.resizeSheet(e,t,o,h);const u=this.getters.getPivotFormulaId(s);let g;"dynamic"===n?(this.dispatch("UPDATE_CELL",{sheetId:e,col:t,row:o,content:`=PIVOT(${u})`}),g={left:t,right:t,top:o,bottom:o}):(this.dispatch("INSERT_PIVOT",{sheetId:e,col:t,row:o,pivotId:s,table:h.export()}),g={left:t,right:t+h.getNumberOfDataColumns(),top:o,bottom:o+d+h.rows.length}),this.dispatch("CREATE_TABLE",{tableType:n,sheetId:e,ranges:[this.getters.getRangeDataFromZone(e,g)],config:{...Ve,numberOfHeaders:d}})}resizeSheet(e,t,o,s){const i=s.getNumberOfDataColumns()+1,n=this.getters.getNumberCols(e),r=n-t;r<i&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:n-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-r,position:"after"});const a=s.columns.length+s.rows.length,l=this.getters.getNumberRows(e),c=l-o;c<a&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:l-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:a-c,position:"after"})}splitPivotFormula(e,t,o,s){const i=this.getters.getSpreadZone({sheetId:e,col:t,row:o});if(!i)return;const n=this.getters.getPivotFormulaId(s),r=new Map;for(let t=i.left;t<=i.right;t++)for(let o=i.top;o<=i.bottom;o++){const s={sheetId:e,col:t,row:o};r.set(s,this.getters.getPivotCellFromPosition(s))}for(const[e,t]of r)this.dispatch("UPDATE_CELL",{...e,content:$c(n,t)});const a=this.getters.getCoreTable({sheetId:e,col:t,row:o});if("dynamic"===a?.type){const s=Mr({col:t,row:o}),n=this.getters.getRangeDataFromZone(e,i);this.dispatch("UPDATE_TABLE",{sheetId:e,zone:s,newTableRange:n,tableType:"static"})}}}).add("pivot_presence",class extends BV{static getters=["getPivotPresenceTracker"];trackPresencePivotId;tracker;handle(e){switch(e.type){case"PIVOT_START_PRESENCE_TRACKING":this.tracker=new CL,this.trackPresencePivotId=e.pivotId;break;case"PIVOT_STOP_PRESENCE_TRACKING":this.trackPresencePivotId=void 0}}getPivotPresenceTracker(e){if(this.trackPresencePivotId===e){if(!this.tracker)throw new Error("Tracker not initialized");return this.tracker}}}).add("split_to_columns",class extends BV{static getters=["getAutomaticSeparator"];allowDispatch(e){return"SPLIT_TEXT_INTO_COLUMNS"===e.type?this.chainValidations(this.batchValidations(this.checkSingleColSelected,this.checkNonEmptySelector),this.batchValidations(this.checkNotOverwritingContent,this.checkSeparatorInSelection))(e):"Success"}handle(e){if("SPLIT_TEXT_INTO_COLUMNS"===e.type)this.splitIntoColumns(e)}getAutomaticSeparator(){const e=this.getters.getSelectedCells();for(const t of e)if(t.value&&t.type===_s.text){const e=this.getAutoSeparatorForString(t.value);if(e)return e}return" "}getAutoSeparatorForString(e){const t=[Ne,";",","," ","."];for(const o of t)if(e.includes(o))return o}splitIntoColumns({separator:e,addNewColumns:t}){const o=this.getters.getSelectedZone(),s=this.getters.getActiveSheetId(),i=this.getSplittedCols(o,e);t&&this.addColsToAvoidCollisions(o,i),this.removeMergesInSplitZone(o,i),this.addColumnsToNotOverflowSheet(o,i);for(let e=0;e<i.length;e++){const t=o.top+e,n=i[e],r=o.left,a=this.getters.getCell({sheetId:s,col:r,row:t});if(1!==n.length||n[0]!==a?.content)for(const[e,o]of n.entries())this.dispatch("UPDATE_CELL",{sheetId:s,col:r+e,row:t,content:Rl(o,this.getters.getLocale()),format:"",style:a?.style||null})}}getSplittedCols(e,t){if(!t)throw new Error("Separator cannot be empty");const o=this.getters.getActiveSheetId(),s=[];for(const i of je(e.top,e.bottom+1)){const n=this.getters.getEvaluatedCell({sheetId:o,col:e.left,row:i}).formattedValue;s.push(this.splitAndRemoveTrailingEmpty(n,t))}return s}splitAndRemoveTrailingEmpty(e,t){const o=e.split(t);for(;o.length>1&&""===o[o.length-1];)o.pop();return o}willSplittedColsOverwriteContent(e,t){const o=this.getters.getActiveSheetId();for(const s of je(e.top,e.bottom+1)){const i=t[s-e.top];for(let t=1;t<i.length;t++){const i=this.getters.getCell({sheetId:o,col:e.left+t,row:s});if(i&&i.content)return!0}}return!1}removeMergesInSplitZone(e,t){const o=this.getters.getActiveSheetId(),s=Math.max(...t.map((e=>e.length))),i={...e,right:e.left+s-1},n=this.getters.getMergesInZone(o,i);this.dispatch("REMOVE_MERGE",{sheetId:o,target:n})}addColsToAvoidCollisions(e,t){const o=this.getters.getActiveSheetId();let s=0;for(const i of je(e.top,e.bottom+1)){const n={sheetId:o,col:e.left,row:i},r=t[i-e.top],a=this.getColsToAddToAvoidCollision(n,r);s=Math.max(s,a)}s&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:e.left,sheetId:o,sheetName:this.getters.getSheetName(o),quantity:s,position:"after"})}getColsToAddToAvoidCollision(e,t){const o=t.length;for(let t=1;t<o;t++){const s=e.col+t,i=this.getters.getCell({...e,col:s});if(i&&i.content)return o-t}return 0}addColumnsToNotOverflowSheet(e,t){const o=this.getters.getActiveSheetId(),s=Math.max(...t.map((e=>e.length-1))),i=this.getters.getNumberCols(o)-1;e.left+s>i&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:i,sheetId:o,sheetName:this.getters.getSheetName(o),quantity:e.left+s-i,position:"after"})}checkSingleColSelected(){return this.getters.isSingleColSelected()?"Success":"MoreThanOneColumnSelected"}checkNonEmptySelector(e){return""===e.separator?"EmptySplitSeparator":"Success"}checkNotOverwritingContent(e){if(e.addNewColumns||e.force)return"Success";const t=this.getters.getSelectedZones()[0],o=this.getSplittedCols(t,e.separator);return this.willSplittedColsOverwriteContent(t,o)?"SplitWillOverwriteContent":"Success"}checkSeparatorInSelection({separator:e}){const t=this.getters.getSelectedCells();for(const o of t)if(o.formattedValue.includes(e))return"Success";return"NoSplitSeparatorInSelection"}}).add("collaborative",class extends BV{static getters=["getClientsToDisplay","getClient","getCurrentClient","getConnectedClients","isFullySynchronized"];static layers=["Selection"];colors=new bo(12);session;constructor(e){super(e),this.session=e.session}isPositionValid(e){return e.row<this.getters.getNumberRows(e.sheetId)&&e.col<this.getters.getNumberCols(e.sheetId)}getClient(e){return this.session.getClient(e)}getCurrentClient(){return this.session.getCurrentClient()}getConnectedClients(){return[...this.session.getConnectedClients()].map((e=>({...e,color:this.colors.get(e.id)})))}isFullySynchronized(){return this.session.isFullySynchronized()}getClientsToDisplay(){try{this.getters.getCurrentClient()}catch(e){if(e instanceof sL)return[];throw e}const e=this.getters.getActiveSheetId(),t=[];for(const o of this.getters.getConnectedClients())o.id!==this.getters.getCurrentClient().id&&o.position&&o.position.sheetId===e&&this.isPositionValid(o.position)&&t.push({...o,position:o.position});return t}drawLayer(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:o}=e,s=this.getters.getActiveSheetId();for(const e of this.getClientsToDisplay()){const{row:i,col:n}=e.position,r=this.getters.expandZone(s,{top:i,bottom:i,left:n,right:n}),{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(r);if(c<=0||h<=0)continue;const d=e.color;t.fillStyle=`${d}10`,t.lineWidth=4*o,t.strokeStyle=d,t.globalCompositeOperation="multiply",t.fillRect(a,l,c,h),t.globalCompositeOperation="source-over",t.strokeRect(a,l,c,h),t.font=`bold ${me+1}px ${fe}`}}}).add("history",class extends BV{static getters=["canUndo","canRedo"];undoStack=[];redoStack=[];session;constructor(e){super(e),this.session=e.session,this.session.on("new-local-state-update",this,this.onNewLocalStateUpdate),this.session.on("snapshot",this,(()=>{this.undoStack=[],this.redoStack=[]}))}allowDispatch(e){switch(e.type){case"REQUEST_UNDO":if(!this.canUndo())return"EmptyUndoStack";break;case"REQUEST_REDO":if(!this.canRedo())return"EmptyRedoStack"}return"Success"}handle(e){switch(e.type){case"REQUEST_UNDO":case"REQUEST_REDO":this.requestHistoryChange("REQUEST_UNDO"===e.type?"UNDO":"REDO")}}finalize(){}requestHistoryChange(e){const t="UNDO"===e?this.undoStack.pop():this.redoStack.pop();if(t)"UNDO"===e?(this.session.undo(t),this.redoStack.push(t)):(this.session.redo(t),this.undoStack.push(t));else{const e=this.getPossibleRevisionToRepeat();if(!e)return;const t=SL(e,this.getters);if(!t)return;if(!Array.isArray(t))return void this.dispatch(t.type,t);for(const e of t)this.dispatch(e.type,e)}}canUndo(){return this.undoStack.length>0}canRedo(){if(this.redoStack.length>0)return!0;const e=this.getPossibleRevisionToRepeat();return!(!(t=e)||!t.rootCommand||"object"!=typeof t.rootCommand)&&(Hs(t.rootCommand)?fL.contains(t.rootCommand.type):vL.contains(t.rootCommand.type));var t}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}getPossibleRevisionToRepeat(){return this.session.getLastLocalNonEmptyRevision()}}).add("data_cleanup",class extends BV{allowDispatch(e){return"REMOVE_DUPLICATES"===e.type?this.checkValidations(e,this.chainValidations(this.checkSingleRangeSelected,this.checkNoMergeInZone,this.checkRangeContainsValues,this.checkColumnsIncludedInZone),this.chainValidations(this.checkNoColumnProvided,this.checkColumnsAreUnique)):"Success"}handle(e){switch(e.type){case"REMOVE_DUPLICATES":this.removeDuplicates(e.columns,e.hasHeader);break;case"TRIM_WHITESPACE":this.trimWhitespace()}}removeDuplicates(e,t){const o=this.getters.getActiveSheetId(),s=this.getters.getSelectedZone();t&&(s.top+=1);const i=this.getUniqueRowsIndexes(o,s.top,s.bottom,e),n=i.length;if(n===Tr(s).numberOfRows)return void this.notifyRowsRemovedAndRemaining(0,n);const r=i.map((e=>({left:s.left,top:e,right:s.right,bottom:e}))),a=new Jc(this.getters,this.dispatch),l=a.copy(Qa(o,r),!1);if(!l)return;this.dispatch("CLEAR_CELLS",{target:[s],sheetId:o});const c={left:s.left,top:s.top,right:s.left,bottom:s.top};a.paste({zones:[c],sheetId:o},l,{isCutOperation:!1});const h={left:s.left,top:s.top-(t?1:0),right:s.right,bottom:s.top+n-1};this.selection.selectZone({cell:{col:h.left,row:h.top},zone:h});const d=s.bottom-s.top+1-n;this.notifyRowsRemovedAndRemaining(d,n)}getUniqueRowsIndexes(e,t,o,s){const i=new Map;for(const n of je(t,o+1)){const t=s.map((t=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).value));!Object.values(i).some((e=>mt(e,t)))&&(i[n]=t)}return Object.keys(i).map((e=>parseInt(e)))}notifyRowsRemovedAndRemaining(e,t){this.ui.notifyUI({type:"info",text:Ho("%s duplicate rows found and removed.\n%s unique rows remain.",e.toString(),t.toString()),sticky:!1})}checkSingleRangeSelected(){return 1!==this.getters.getSelectedZones().length?"MoreThanOneRangeSelected":"Success"}checkNoMergeInZone(){const e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZone();return this.getters.getMergesInZone(e,t).length>0?"WillRemoveExistingMerge":"Success"}checkRangeContainsValues(e){const t=this.getters.getActiveSheetId(),o=this.getters.getSelectedZone();e.hasHeader&&(o.top+=1);return this.getters.getEvaluatedCellsInZone(t,o).every((e=>"empty"===e.type))?"EmptyTarget":"Success"}checkNoColumnProvided(e){return 0===e.columns.length?"NoColumnsProvided":"Success"}checkColumnsIncludedInZone(e){const t=this.getters.getSelectedZone();return e.columns.some((e=>e<t.left||e>t.right))?"ColumnsNotIncludedInZone":"Success"}checkColumnsAreUnique(e){return e.columns.length!==new Set(e.columns).size?"DuplicatesColumnsSelected":"Success"}trimWhitespace(){const e=nr(this.getters.getSelectedZones()),t=this.getters.getActiveSheetId();let o=0;for(const{col:s,row:i}of e.map(_r).flat()){const e=this.getters.getCell({col:s,row:i,sheetId:t});if(!e)continue;const n=Dt(e.content);n!==e.content&&(o+=1,this.dispatch("UPDATE_CELL",{sheetId:t,col:s,row:i,content:n}))}const s=o?Ho("Trimmed whitespace from %s cells.",o):Ho("No selected cells had whitespace trimmed.");this.ui.notifyUI({type:"info",text:s,sticky:!1})}}).add("table_autofill",class extends BV{handle(e){if("AUTOFILL_TABLE_COLUMN"===e.type){const t=this.getters.getCoreTable(e),o=this.getters.getCell(e);if(!t?.config.automaticAutofill||"dynamic"===t.type||!o?.isFormula)return;const{col:s,row:i}=e,n=function(e,t){const o=t.numberOfHeaders,s={...e,top:e.top+o};return s.top<=s.bottom?s:void 0}(t.range.zone,t.config);if(n&&Er(s,i,n)){const t=e.autofillRowStart??n.top,o=e.autofillRowEnd??n.bottom,s={...n,top:t,bottom:o};this.autofillTableZone(e,s)}}}autofillTableZone(e,t){if(t.top===t.bottom)return;const{col:o,row:s,sheetId:i}=e;for(let e=t.top;e<=t.bottom;e++)if(e!==s&&this.getters.getEvaluatedCell({col:o,row:e,sheetId:i}).type!==_s.empty)return;const n={zone:this.getters.getSelectedZone(),cell:this.getters.getActivePosition()};this.selection.selectCell(o,s),this.dispatch("AUTOFILL_SELECT",{col:o,row:t.bottom}),this.dispatch("AUTOFILL"),this.selection.selectCell(o,s),this.dispatch("AUTOFILL_SELECT",{col:o,row:t.top}),this.dispatch("AUTOFILL"),this.selection.selectZone(n)}}).add("table_ui_resize",class extends BV{allowDispatch(e){if("RESIZE_TABLE"===e.type){const t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return"TableNotFound";const o=t.range.zone,s=this.getters.getRangeFromRangeData(e.newTableRange).zone;return s.top!==o.top||s.left!==o.left?"InvalidTableResize":this.canDispatch("UPDATE_TABLE",{...e}).reasons}return"Success"}handle(e){switch(e.type){case"RESIZE_TABLE":{const t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(this.dispatch("UPDATE_TABLE",{...e}),!t)return;const o=this.getters.getRangeFromRangeData(e.newTableRange).zone;if(this.selection.selectCell(o.right,o.bottom),!t.config.automaticAutofill)return;const s=t.range.zone;if(o.bottom>=s.bottom){for(let t=o.left;t<=o.right;t++){const i={col:t,row:s.bottom,sheetId:e.sheetId};this.getters.getCell(i)?.content.startsWith("=")&&this.dispatch("AUTOFILL_TABLE_COLUMN",{...i,autofillRowStart:s.bottom,autofillRowEnd:o.bottom})}break}}}}}).add("datavalidation_insert",class extends BV{handle(e){if("ADD_DATA_VALIDATION_RULE"===e.type)if("isBoolean"===e.rule.criterion.type){const t=e.ranges.map((e=>this.getters.getRangeFromRangeData(e)));for(const e of wa(t)){const t=this.getters.getCell(e),o=this.getters.getEvaluatedCell(e);if(t?.content)if(t?.content&&o.type===_s.empty){let o;if(t.content.startsWith("=")){const s=this.getters.evaluateFormula(e.sheetId,t.content);o=(js(s)?s[0][0]:s)?.toString()}else o=t.content;o&&Ke(o)||this.dispatch("UPDATE_CELL",{...e,content:"FALSE"})}else o.type!==_s.boolean&&this.dispatch("UPDATE_CELL",{...e,content:"FALSE"});else this.dispatch("UPDATE_CELL",{...e,content:"FALSE"})}}}}).add("checkbox_toggle",class extends BV{static getters=["hasBooleanValidationInZones"];handle(e){if("TOGGLE_CHECKBOX"===e.type)this.toggleCheckbox(e.sheetId,e.target)}hasBooleanValidationInZones(e){const t=this.getters.getActiveSheetId();for(const o of e)for(let e=o.left;e<=o.right;e++)for(let s=o.top;s<=o.bottom;s++)if(this.getters.isCellValidCheckbox({col:e,row:s,sheetId:t}))return!0;return!1}toggleCheckbox(e,t){for(const o of t)for(let t=o.left;t<=o.right;t++)for(let s=o.top;s<=o.bottom;s++){const o={col:t,row:s,sheetId:e};if(this.getters.isCellValidCheckbox(o)){const e=this.getters.getEvaluatedCell(o).value?"FALSE":"TRUE";this.dispatch("UPDATE_CELL",{...o,content:e})}}}}).add("geo_features",class extends BV{static getters=["getGeoJsonFeatures","geoFeatureNameToId","getGeoChartAvailableRegions"];geoJsonService;geoJsonCache={};constructor(e){super(e),this.geoJsonService=e.external.geoJsonService}getGeoChartAvailableRegions(){return this.geoJsonService?this.geoJsonService.getAvailableRegions()||[]:(console.error("No geoJsonService provided to the model"),[])}getGeoJsonFeatures(e){if(!this.geoJsonService)return void console.error("No geoJsonService provided to the model");const t=this.geoJsonCache[e];return t instanceof Promise?void 0:void 0!==t?t??void 0:void(this.geoJsonCache[e]=new Promise((async t=>{const o=await(this.geoJsonService?.getTopoJson(e));this.geoJsonCache[e]=this.convertToGeoJson(o),this.dispatch("EVALUATE_CHARTS"),t()})))}geoFeatureNameToId(e,t){if(this.geoJsonService)return this.geoJsonService.geoFeatureNameToId(e,t);console.error("No geoJsonService provided to the model")}convertToGeoJson(e){if(!e)return null;if("Topology"===e.type){const t=window.ChartGeo.topojson.feature(e,Object.values(e.objects)[0]);return"FeatureCollection"===t.type?t.features:[t]}if("FeatureCollection"===e.type)return e.features;throw new Error("Invalid TopoJSON")}}),RL=(new n).add("selection",class extends BV{static layers=["Selection"];static getters=["getActiveSheet","getActiveSheetId","getActiveSheetName","getActiveCell","getActiveCols","getActiveRows","getCurrentStyle","getSelectedZones","getSelectedZone","getSelectedCells","getSelectedFigureId","getSelection","getActivePosition","getSheetPosition","isSingleColSelected","getElementsFromSelection","tryGetActiveSheetId","isGridSelectionActive","getSelectecUnboundedZone"];gridSelection={anchor:{cell:{col:0,row:0},zone:{top:0,left:0,bottom:0,right:0}},zones:[{top:0,left:0,bottom:0,right:0}]};selectedFigureId=null;sheetsData={};moveClient;isUnbounded;activeSheet=null;constructor(e){super(e),this.moveClient=e.moveClient,this.isUnbounded=!1}allowDispatch(e){switch(e.type){case"ACTIVATE_SHEET":try{if(!this.getters.getSheet(e.sheetIdTo).isVisible)return"SheetIsHidden";break}catch(e){return"InvalidSheetId"}case"MOVE_COLUMNS_ROWS":return this.isMoveElementAllowed(e)}return"Success"}handleEvent(e){const t=e.anchor;let o=[];switch(this.isUnbounded=e.options?.unbounded||!1,e.mode){case"overrideSelection":o=[t.zone];break;case"updateAnchor":o=[...this.gridSelection.zones];const s=o.findIndex((t=>Ir(t,e.previousAnchor.zone)));s>=0&&(o[s]=t.zone);break;case"newAnchor":o=[...this.gridSelection.zones,t.zone]}this.setSelectionMixin(e.anchor,o),this.selection.resetDefaultAnchor(this,ze(this.gridSelection.anchor));const{col:s,row:i}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:s,row:i}),this.selectedFigureId=null}handle(e){switch(e.type){case"ACTIVATE_SHEET":this.selectedFigureId=null;break;case"DELETE_FIGURE":this.selectedFigureId===e.figureId&&(this.selectedFigureId=null);break;case"DELETE_SHEET":this.selectedFigureId&&this.getters.getFigure(e.sheetId,this.selectedFigureId)&&(this.selectedFigureId=null)}switch(e.type){case"START":const t=this.getters.getVisibleSheetIds()[0];this.activateSheet(t,t);const{col:o,row:s}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(o,s),this.selection.registerAsDefault(this,this.gridSelection.anchor,{handleEvent:this.handleEvent.bind(this)}),this.moveClient({sheetId:t,col:0,row:0});break;case"ACTIVATE_SHEET":this.activateSheet(e.sheetIdFrom,e.sheetIdTo);break;case"REMOVE_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);const{col:o,row:s}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:o,row:s})}break}case"ADD_COLUMNS_ROWS":{const t=this.getters.getActiveSheetId();if(e.sheetId===t){this.onAddElements(e);const{col:o,row:s}=this.gridSelection.anchor.cell;this.moveClient({sheetId:t,col:o,row:s})}break}case"MOVE_COLUMNS_ROWS":e.sheetId===this.getActiveSheetId()&&this.onMoveElements(e);break;case"SELECT_FIGURE":this.selectedFigureId=e.figureId;break;case"ACTIVATE_NEXT_SHEET":this.activateNextSheet("right");break;case"ACTIVATE_PREVIOUS_SHEET":this.activateNextSheet("left");break;case"HIDE_SHEET":e.sheetId===this.getActiveSheetId()&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e.sheetId,sheetIdTo:this.getters.getVisibleSheetIds()[0]});break;case"UNDO":case"REDO":case"DELETE_SHEET":const i=Object.keys(this.sheetsData).filter((e=>!this.getters.tryGetSheet(e)));for(const e of i)delete this.sheetsData[e];for(const e in this.sheetsData){const t=this.clipSelection(e,this.sheetsData[e].gridSelection);this.sheetsData[e]={gridSelection:ze(t)}}this.fallbackToVisibleSheet();const n=this.getters.getActiveSheetId();this.gridSelection.zones=this.gridSelection.zones.map((e=>this.getters.expandZone(n,e))),this.gridSelection.anchor.zone=this.getters.expandZone(n,this.gridSelection.anchor.zone),this.setSelectionMixin(this.gridSelection.anchor,this.gridSelection.zones),this.selectedFigureId=null}}finalize(){this.fallbackToVisibleSheet(),this.selection.resetDefaultAnchor(this,ze(this.gridSelection.anchor))}isGridSelectionActive(){return this.selection.isListening(this)}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}getActiveSheetName(){return this.activeSheet.name}tryGetActiveSheetId(){return this.activeSheet?.id}getActiveCell(){return this.getters.getEvaluatedCell(this.getActivePosition())}getActiveCols(){const e=new Set;for(const t of this.gridSelection.zones)if(0===t.top&&t.bottom===this.getters.getNumberRows(this.getters.getActiveSheetId())-1)for(let o=t.left;o<=t.right;o++)e.add(o);return e}getActiveRows(){const e=new Set,t=this.getters.getActiveSheetId();for(const o of this.gridSelection.zones)if(0===o.left&&o.right===this.getters.getNumberCols(t)-1)for(let t=o.top;t<=o.bottom;t++)e.add(t);return e}getCurrentStyle(){const e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId();return this.getters.getCellStyle({sheetId:t,col:e.left,row:e.top})}getSelectedZones(){return ze(this.gridSelection.zones)}getSelectedZone(){return ze(this.gridSelection.anchor.zone)}getSelectecUnboundedZone(){return ze(this.isUnbounded?this.getters.getUnboundedZone(this.activeSheet.id,this.gridSelection.anchor.zone):this.gridSelection.anchor.zone)}getSelection(){return ze(this.gridSelection)}getSelectedCells(){const e=this.getters.getActiveSheetId(),t=[];for(const o of this.gridSelection.zones)t.push(...this.getters.getEvaluatedCellsInZone(e,o));return t}getSelectedFigureId(){return this.selectedFigureId}getActivePosition(){return this.getters.getMainCellPosition({sheetId:this.getActiveSheetId(),col:this.gridSelection.anchor.cell.col,row:this.gridSelection.anchor.cell.row})}getSheetPosition(e){if(e===this.getters.getActiveSheetId())return this.getActivePosition();{const t=this.sheetsData[e];return t?{sheetId:e,col:t.gridSelection.anchor.cell.col,row:t.gridSelection.anchor.cell.row}:this.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0})}}isSingleColSelected(){const e=this.getters.getSelectedZones();return 1===e.length&&e[0].left===e[0].right}getElementsFromSelection(e){if("COL"===e&&0===this.getters.getActiveCols().size)return[];if("ROW"===e&&0===this.getters.getActiveRows().size)return[];const t=this.getters.getSelectedZones();let o=[];const s="COL"===e?"left":"top",i="COL"===e?"right":"bottom";for(const e of t){const t=Array.from({length:e[i]-e[s]+1},((t,o)=>e[s]+o));o=o.concat(t)}return[...new Set(o)].sort()}activateSheet(e,t){if(this.setActiveSheet(t),this.sheetsData[e]={gridSelection:ze(this.gridSelection)},t in this.sheetsData)Object.assign(this,this.sheetsData[t]),this.selection.resetDefaultAnchor(this,ze(this.gridSelection.anchor));else{const{col:e,row:o}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(e,o)}const{col:o,row:s}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.activeSheet.id,col:o,row:s})}setSelectionMixin(e,t){const{anchor:o,zones:s}=this.clipSelection(this.getters.getActiveSheetId(),{anchor:e,zones:t});this.gridSelection.anchor=o,this.gridSelection.zones=function(e){return e.reverse().filter(((e,t,o)=>t===o.findIndex((t=>t.top===e.top&&t.bottom===e.bottom&&t.left===e.left&&t.right===e.right)))).reverse()}(s)}selectCell(e,t){const o=this.getters.getActiveSheetId(),s=this.getters.expandZone(o,{left:e,right:e,top:t,bottom:t});this.setSelectionMixin({zone:s,cell:{col:e,row:t}},[s])}setActiveSheet(e){this.activeSheet=this.getters.getSheet(e)}activateNextSheet(e){const t=this.getters.getSheetIds(),o=(t.findIndex((e=>e===this.activeSheet.id))+("left"===e?t.length-1:1))%t.length;this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.getActiveSheetId(),sheetIdTo:t[o]})}onColumnsRemoved(e){const{cell:t,zone:o}=this.gridSelection.anchor,s=Sr(o,"left",[...e.elements]);let i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=Sr(i,"left",[...e.elements]);const n={cell:{col:i.left,row:i.top},zone:s},r=this.gridSelection.zones.map((t=>Sr(t,"left",[...e.elements])));this.setSelectionMixin(n,r)}onRowsRemoved(e){const{cell:t,zone:o}=this.gridSelection.anchor,s=Sr(o,"top",[...e.elements]);let i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=Sr(i,"top",[...e.elements]);const n={cell:{col:i.left,row:i.top},zone:s},r=this.gridSelection.zones.map((t=>Sr(t,"top",[...e.elements])));this.setSelectionMixin(n,r)}onAddElements(e){const t="COL"===e.dimension?"left":"top",o=br(this.gridSelection.anchor.zone,t,e.base,e.position,e.quantity),s=this.gridSelection.zones.map((o=>br(o,t,e.base,e.position,e.quantity))),i={cell:{col:o.left,row:o.top},zone:o};this.setSelectionMixin(i,s)}onMoveElements(e){const t=e.elements.length,o=this.getFiguresUpdates(e);this.dispatch("ADD_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,sheetName:e.sheetName,base:e.base,quantity:t,position:e.position});const s="COL"===e.dimension,i=e.elements[0],n=e.elements[t-1],r=e.base<i,a=r&&s?t:0,l=r&&!s?t:0,c=r?e.elements.map((e=>e+t)):e.elements,h={};for(const t of c)h[t]=this.getters.getHeaderSize(e.sheetId,e.dimension,t);const d=[{left:s?i+a:0,right:s?n+a:this.getters.getNumberCols(e.sheetId)-1,top:s?0:i+l,bottom:s?this.getters.getNumberRows(e.sheetId)-1:n+l}],u=this.getActiveSheetId(),g=r?e.base:e.base+1,p=[{left:s?g:0,right:s?g+t-1:this.getters.getNumberCols(e.sheetId)-1,top:s?0:g,bottom:s?this.getters.getNumberRows(e.sheetId)-1:g+t-1}];for(const e of eh.cellHandlers.getAll()){const t=new e(this.getters,this.dispatch),o=t.copy(Qa(u,d),!1,"shiftCells");o&&t.paste({zones:p,sheetId:u},o,{isCutOperation:!0})}const m=p[0],f=m.left,v=m.top;this.setSelectionMixin({zone:m,cell:{col:f,row:v}},[m]);let b=r?e.base:e.base+1;const S={};for(const t of c){const o=h[t];o!==this.getters.getHeaderSize(e.sheetId,e.dimension,b)&&(S[o]??=[],S[o].push(b)),b+=1}for(const t in S)this.dispatch("RESIZE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,size:parseInt(t,10),elements:S[t]});this.dispatch("REMOVE_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,sheetName:e.sheetName,elements:c}),this.applyFigureUpdates(o)}getFiguresUpdates(e){const t=[],o={},s=e.elements[0]<e.base?e.base-e.elements.length+1:e.base;for(let t=0;t<e.elements.length;t++)o[e.elements[t]]=s+t;for(const s of this.getters.getFigures(e.sheetId))"COL"===e.dimension&&s.col in o&&t.push({type:"UPDATE_FIGURE",sheetId:e.sheetId,figureId:s.id,col:o[s.col],row:s.row}),"ROW"===e.dimension&&s.row in o&&t.push({type:"UPDATE_FIGURE",sheetId:e.sheetId,figureId:s.id,row:o[s.row],col:s.col});return t}applyFigureUpdates(e){for(const t of e)this.dispatch(t.type,{...t})}isMoveElementAllowed(e){const t="COL"===e.dimension,o=e.elements[0],s=e.elements[e.elements.length-1],i=e.sheetId,n=t?this.getters.doesColumnsHaveCommonMerges:this.getters.doesRowsHaveCommonMerges;if(n(i,o-1,o)||n(i,s,s+1)||n(i,e.base-1,e.base))return"WillRemoveExistingMerge";const r=[e.base,...e.elements],a=t?this.getters.getNumberCols(i):this.getters.getNumberRows(i);return r.some((e=>e<0||e>=a))?"InvalidHeaderIndex":t||this.isTableRowMoveAllowed(i,e.elements)?"Success":"CannotMoveTableHeader"}isTableRowMoveAllowed(e,t){const o=this.getters.getCoreTables(e);if(0===o.length)return!0;const s=new Set(t);return o.every((({range:{zone:e},config:o})=>{const{top:i,bottom:n}=e;if(0===o.numberOfHeaders)return!0;const r=i+o.numberOfHeaders-1;if(!t.some((e=>e>=i&&e<=r)))return!0;return je(i,n+1).every((e=>s.has(e)))}))}fallbackToVisibleSheet(){if(!this.getters.tryGetSheet(this.getters.getActiveSheetId())){const e=this.getters.getVisibleSheetIds();if(this.activeSheet=this.getters.getSheet(e[0]),this.activeSheet.id in this.sheetsData){const{anchor:e}=this.clipSelection(this.activeSheet.id,this.sheetsData[this.activeSheet.id].gridSelection);this.selectCell(e.cell.col,e.cell.row)}else this.selectCell(0,0);const{col:t,row:o}=this.gridSelection.anchor.cell;this.moveClient({sheetId:this.getters.getActiveSheetId(),col:t,row:o})}}clipSelection(e,t){const o=this.getters.getNumberCols(e)-1,s=this.getters.getNumberRows(e)-1;return{zones:t.zones.map((e=>({left:Ze(e.left,0,o),right:Ze(e.right,0,o),top:Ze(e.top,0,s),bottom:Ze(e.bottom,0,s)}))),anchor:{cell:{col:Ze(t.anchor.cell.col,0,o),row:Ze(t.anchor.cell.row,0,s)},zone:{left:Ze(t.anchor.zone.left,0,o),right:Ze(t.anchor.zone.right,0,o),top:Ze(t.anchor.zone.top,0,s),bottom:Ze(t.anchor.zone.bottom,0,s)}}}}drawLayer(e){if(this.getters.isDashboard())return;const{ctx:t,thinLineWidth:o}=e,s=this.getSelectedZones();t.fillStyle="#f3f7fe";const i=1===s.length&&s[0].left===s[0].right&&s[0].top===s[0].bottom;t.fillStyle=i?"#f3f7fe":"#e9f0ff",t.strokeStyle=p,t.lineWidth=1.5*o;for(const e of s){const{x:o,y:s,width:i,height:n}=this.getters.getVisibleRect(e);t.globalCompositeOperation="multiply",t.fillRect(o,s,i,n),t.globalCompositeOperation="source-over",t.strokeRect(o,s,i,n)}t.globalCompositeOperation="source-over";const n=this.getActivePosition();let r;t.strokeStyle=p,t.lineWidth=3*o,r=this.getters.isInMerge(n)?this.getters.getMerge(n):Mr(n);const{x:a,y:l,width:c,height:h}=this.getters.getVisibleRect(r);c>0&&h>0&&t.strokeRect(a,l,c,h)}}).add("evaluation_filter",class extends BV{static getters=["getFilterValue","getFilterHiddenValues","getFilterCriterionValue","getFirstTableInSelection","isRowFiltered","isFilterActive"];filterValues={};hiddenRows={};isEvaluationDirty=!1;allowDispatch(e){if("UPDATE_FILTER"===e.type)if(!this.getters.getFilterId(e))return"FilterNotFound";return"Success"}handle(e){switch(e.type){case"UNDO":case"REDO":case"UPDATE_CELL":case"EVALUATE_CELLS":case"ACTIVATE_SHEET":case"REMOVE_TABLE":case"ADD_COLUMNS_ROWS":case"REMOVE_COLUMNS_ROWS":case"UPDATE_TABLE":this.isEvaluationDirty=!0;break;case"START":for(const e of this.getters.getSheetIds())this.filterValues[e]={};break;case"CREATE_SHEET":this.filterValues[e.sheetId]={};break;case"HIDE_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"GROUP_HEADERS":case"UNGROUP_HEADERS":case"FOLD_HEADER_GROUP":case"UNFOLD_HEADER_GROUP":case"FOLD_ALL_HEADER_GROUPS":case"UNFOLD_ALL_HEADER_GROUPS":case"FOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_HEADER_GROUPS_IN_ZONE":this.updateHiddenRows(e.sheetId);break;case"UPDATE_FILTER":this.updateFilter(e),this.updateHiddenRows(e.sheetId);break;case"DUPLICATE_SHEET":this.filterValues[e.sheetIdTo]=ze(this.filterValues[e.sheetId])}}finalize(){if(this.isEvaluationDirty){for(const e of this.getters.getSheetIds())this.updateHiddenRows(e);this.isEvaluationDirty=!1}}isRowFiltered(e,t){return!!this.hiddenRows[e]?.has(t)}getFilterValue(e){const t=this.getters.getFilterId(e),o=e.sheetId;return t?this.filterValues[o]?.[t]:void 0}getFilterHiddenValues(e){const t=this.getters.getFilterId(e),o=e.sheetId;if(!t||!this.filterValues[o])return[];const s=this.filterValues[o][t]||[];return"values"===s.filterType?s.hiddenValues:[]}getFilterCriterionValue(e){const t=this.getters.getFilterId(e),o=e.sheetId;if(!t||!this.filterValues[o])return wL;const s=this.filterValues[o][t];return s&&"criterion"===s.filterType?s:wL}isFilterActive(e){const t=this.getters.getFilterId(e);if(!t)return!1;const o=e.sheetId,s=this.filterValues[o]?.[t];return!!s&&("values"===s.filterType?s.hiddenValues.length>0:"none"!==s.type)}getFirstTableInSelection(){const e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZones();return this.getters.getTablesOverlappingZones(e,t)[0]}updateFilter({col:e,row:t,value:o,sheetId:s}){const i=this.getters.getFilterId({sheetId:s,col:e,row:t});i&&(this.filterValues[s]||(this.filterValues[s]={}),this.filterValues[s][i]=o)}updateHiddenRows(e){const t=this.getters.getFilters(e).sort(((e,t)=>e.rangeWithHeaders.zone.top-t.rangeWithHeaders.zone.top)),o=new Set;for(const s of t){const t=this.filterValues[e]?.[s.id],i=s.filteredRange?.zone;if(t&&i&&!o.has(s.rangeWithHeaders.zone.top)&&!this.getters.isRowHiddenByUser(e,s.rangeWithHeaders.zone.top))if("values"===t.filterType){const n=t.hiddenValues?.map(qa);if(!n)continue;const r=new Set(n);for(let t=i.top;t<=i.bottom;t++){const i=this.getCellValueAsString(e,s.col,t);r.has(i)&&o.add(t)}}else{if("none"===t.type)continue;const n=eE.get(t.type),r=t.values.map((t=>t.startsWith("=")?this.getters.evaluateFormula(e,t)??"":Kn(t,qs)));if(r.some(oc))continue;const a={type:t.type,values:r.map(ec),dateValue:t.dateValue};for(let t=i.top;t<=i.bottom;t++){const i={sheetId:e,col:s.col,row:t},r=this.getters.getEvaluatedCell(i).value??"";n.isValueValid(r,a,this.getters,e)||o.add(t)}}}this.hiddenRows[e]=o}getCellValueAsString(e,t,o){return this.getters.getEvaluatedCell({sheetId:e,col:t,row:o}).formattedValue.toLowerCase()}exportForExcel(e){for(const t of e.sheets){const e=t.id;for(const o of t.tables){const s=ur(o.range),i=[],n=[];for(const o of je(0,Tr(s).numberOfCols)){const r={sheetId:t.id,col:s.left+o,row:s.top},a=this.getFilterHiddenValues(r),l=this.getters.getFilter(r),c=l?.filteredRange?_r(l.filteredRange.zone).map((t=>this.getters.getEvaluatedCell({sheetId:e,...t}).formattedValue)):[];if(a.length){const e=c.filter((e=>e)).filter((e=>!a.includes(e)));i.push({colId:o,displayedValues:[...new Set(e)],displayBlanks:!a.includes("")&&c.some((e=>!e))})}const h=this.getters.getEvaluatedCell(r).formattedValue,d=this.getUniqueColNameForExcel(o,h,n);n.push(d);const u=Po(r.col,r.row);t.cells[u]=d,t.cellValues[u]=d}o.filters=i}}}getUniqueColNameForExcel(e,t,o){return t||(t=`Column${e}`),Vt(t,o,{compute:(e,o)=>t+String(o),start:2})}}).add("header_visibility_ui",class extends BV{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,o){return"COL"===t?this.isColHidden(e,o):this.isRowHidden(e,o)}getNextVisibleCellPosition({sheetId:e,col:t,row:o}){return{sheetId:e,col:this.findVisibleHeader(e,"COL",t,this.getters.getNumberCols(e)-1),row:this.findVisibleHeader(e,"ROW",o,this.getters.getNumberRows(e)-1)}}findVisibleHeader(e,t,o,s){if(o<=s)for(let i=o;i<=s;i++)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i;if(o>s)for(let i=o;i>=s;i--)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}findLastVisibleColRowIndex(e,t,{last:o,first:s}){return je(o,s,-1).find((o=>!this.isHeaderHidden(e,t,o)))||s}findFirstVisibleColRowIndex(e,t){const o=this.getters.getNumberHeaders(e,t);for(let s=0;s<o;s++){if("COL"===t&&!this.isColHidden(e,s))return s;if("ROW"===t&&!this.isRowHidden(e,s))return s}}exportForExcel(e){for(const t of e.sheets)for(const[e,o]of Object.entries(t.rows))o.isHidden=this.isRowHidden(t.id,Number(e))}}).add("cell_computed_style",class extends BV{static getters=["getCellComputedBorder","getCellComputedStyle"];styles={};borders={};handle(e){if(Fs.has(e.type)||"UPDATE_CELL"===e.type||"SET_FORMATTING"===e.type||"ADD_DATA_VALIDATION_RULE"===e.type||"REMOVE_DATA_VALIDATION_RULE"===e.type||"EVALUATE_CELLS"===e.type)return this.styles={},void(this.borders={});rL(e)?"sheetId"in e?(delete this.styles[e.sheetId],delete this.borders[e.sheetId]):(this.styles={},this.borders={}):Ns.has(e.type)?this.styles={}:ks.has(e.type)&&(this.borders={})}getCellComputedBorder(e){const{sheetId:t,row:o,col:s}=e;return void 0!==this.borders[t]?.[o]?.[s]||(this.borders[t]||(this.borders[t]={}),this.borders[t][o]||(this.borders[t][o]={}),this.borders[t][o][s]||(this.borders[t][o][s]=this.computeCellBorder(e))),this.borders[t][o][s]}getCellComputedStyle(e){const{sheetId:t,row:o,col:s}=e;return void 0!==this.styles[t]?.[o]?.[s]||(this.styles[t]||(this.styles[t]={}),this.styles[t][o]||(this.styles[t][o]={}),this.styles[t][o][s]||(this.styles[t][o][s]=this.computeCellStyle(e))),this.styles[t][o][s]}computeCellBorder(e){const t=this.getters.getCellBorder(e)||{},o={...bt(this.getters.getCellTableBorder(e)||{}),...bt(t)};return ct(o)?null:o}computeCellStyle(e){const t=this.getters.getCell(e),o=this.getters.getCellConditionalFormatStyle(e),s=this.getters.getCellTableStyle(e),i=this.getters.getDataValidationCellStyle(e),n={...bt(s),...bt(i),...bt(t?.style),...bt(o)};return this.getters.getEvaluatedCell(e).link&&!n.textColor&&(n.textColor=b),n}}).add("table_computed_style",class extends BV{static getters=["getCellTableStyle","getCellTableBorder"];tableStyles={};handle(e){Fs.has(e.type)||"UPDATE_CELL"===e.type&&("content"in e||"format"in e)||"EVALUATE_CELLS"===e.type?this.tableStyles={}:rL(e)&&("sheetId"in e?delete this.tableStyles[e.sheetId]:this.tableStyles={})}finalize(){for(const e of this.getters.getSheetIds()){this.tableStyles[e]||(this.tableStyles[e]={});for(const t of this.getters.getTables(e))this.tableStyles[e][t.id]||(this.tableStyles[e][t.id]=this.computeTableStyle(e,t))}}getCellTableStyle(e){const t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().styles[e.col]?.[e.row]}getCellTableBorder(e){const t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().borders[e.col]?.[e.row]}computeTableStyle(e,t){return ut((()=>{const{config:o,numberOfCols:s,numberOfRows:i}=this.getTableRuntimeConfig(e,t),n=w_(o,this.getters.getTableStyle(t.config.styleId),s,i),r=this.getTableMapping(e,t),a={borders:{},styles:{}};for(let e=0;e<s;e++){const t=r.colMapping[e];a.borders[t]={},a.styles[t]={};for(let o=0;o<i;o++){const s=r.rowMapping[o];a.borders[t][s]=n.borders[e][o],a.styles[t][s]=n.styles[e][o]}}return a}))}getTableRuntimeConfig(e,t){const o=t.range.zone,s={...t.config};let i=o.right-o.left+1,n=o.bottom-o.top+1;for(let i=o.top;i<=o.bottom;i++)this.getters.isRowHidden(e,i)&&(n--,i-o.top<t.config.numberOfHeaders&&(s.numberOfHeaders--,s.numberOfHeaders<0&&(s.numberOfHeaders=0)),i===o.bottom&&(s.totalRow=!1));for(let t=o.left;t<=o.right;t++)this.getters.isColHidden(e,t)&&(i--,t===o.left&&(s.firstColumn=!1),t===o.right&&(s.lastColumn=!1));return{config:s,numberOfCols:i,numberOfRows:n}}getTableMapping(e,t){const o={},s={};let i=0,n=0;const r=t.range.zone;for(let t=r.left;t<=r.right;t++)if(!this.getters.isColHidden(e,t)){o[i]=t,i++;for(let t=r.top;t<=r.bottom;t++)this.getters.isRowHidden(e,t)||(s[n]=t,n++)}return{colMapping:o,rowMapping:s}}}).add("header_positions",class extends BV{static getters=["getColDimensions","getRowDimensions","getColRowOffset"];headerPositions={};isDirty=!0;handle(e){switch(Fs.has(e.type)&&(this.headerPositions={},this.isDirty=!0),e.type){case"START":for(const e of this.getters.getSheetIds())this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e);break;case"UPDATE_CELL":case"UPDATE_FILTER":case"UPDATE_TABLE":case"REMOVE_TABLE":this.headerPositions={},this.isDirty=!0;break;case"REMOVE_COLUMNS_ROWS":case"RESIZE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"FOLD_HEADER_GROUP":case"UNFOLD_HEADER_GROUP":case"FOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_ALL_HEADER_GROUPS":case"FOLD_ALL_HEADER_GROUPS":case"UNGROUP_HEADERS":case"GROUP_HEADERS":case"CREATE_SHEET":this.getters.tryGetSheet(e.sheetId)&&(this.headerPositions[e.sheetId]=this.computeHeaderPositionsOfSheet(e.sheetId));break;case"DUPLICATE_SHEET":this.headerPositions[e.sheetIdTo]=ze(this.headerPositions[e.sheetId])}}finalize(){for(const e of this.getters.getSheetIds())!this.isDirty&&this.headerPositions[e]||(this.headerPositions[e]=this.computeHeaderPositionsOfSheet(e));this.isDirty=!1}getColDimensions(e,t){const o=this.headerPositions[e].COL[t],s=this.getters.getColSize(e,t);return{start:o,size:s,end:o+(this.getters.isColHidden(e,t)?0:s)}}getRowDimensions(e,t){const o=this.headerPositions[e].ROW[t],s=this.getters.getRowSize(e,t);return{start:o,size:s,end:o+(this.getters.isRowHidden(e,t)?0:s)}}getColRowOffset(e,t,o,s=this.getters.getActiveSheetId()){const i=this.headerPositions[s][e][t];return this.headerPositions[s][e][o]-i}computeHeaderPositionsOfSheet(e){return{COL:this.computePositions(e,"COL"),ROW:this.computePositions(e,"ROW")}}computePositions(e,t){const o={};let s=0;for(let i=0;i<this.getters.getNumberHeaders(e,t)+1;i++)o[i]=s,this.getters.isHeaderHidden(e,t,i)||(s+=this.getters.getHeaderSize(e,t,i));return o}}).add("viewport",class extends BV{static getters=["getColIndex","getRowIndex","getActiveMainViewport","getSheetViewDimension","getSheetViewDimensionWithHeaders","getMainViewportRect","isVisibleInViewport","getEdgeScrollCol","getEdgeScrollRow","getVisibleFigures","getVisibleRect","getVisibleRectWithoutHeaders","getVisibleCellPositions","getColRowOffsetInViewport","getMainViewportCoordinates","getActiveSheetScrollInfo","getSheetViewVisibleCols","getSheetViewVisibleRows","getFrozenSheetViewRatio","isPixelPositionVisible","getColDimensionsInViewport","getRowDimensionsInViewport","getAllActiveViewportsZonesAndRect","getRect","getFigureUI","getPositionAnchorOffset","getGridOffset"];viewports={};sheetViewWidth=Me();sheetViewHeight=Me();gridOffsetX=0;gridOffsetY=0;sheetsWithDirtyViewports=new Set;shouldAdjustViewports=!1;allowDispatch(e){switch(e.type){case"SET_VIEWPORT_OFFSET":return this.chainValidations(this.checkScrollingDirection,this.checkIfViewportsWillChange)(e);case"RESIZE_SHEETVIEW":return this.chainValidations(this.checkValuesAreDifferent,this.checkPositiveDimension)(e);default:return"Success"}}handleEvent(e){const t=this.getters.getActiveSheetId();if(e.options.scrollIntoView){let{col:o,row:s}=Pr(e.previousAnchor.zone,e.anchor.zone);if("updateAnchor"===e.mode){const i=e.previousAnchor.zone,n=e.anchor.zone,{top:r,bottom:a,left:l,right:c}=this.getMainInternalViewport(t);i.left===n.left&&i.right===n.right&&(o=l>o||o>c?l:o),i.top===n.top&&i.bottom===n.bottom&&(s=r>s||s>a?r:s)}o=Math.min(o,this.getters.getNumberCols(t)-1),s=Math.min(s,this.getters.getNumberRows(t)-1),this.sheetsWithDirtyViewports.has(t)||this.refreshViewport(this.getters.getActiveSheetId(),{col:o,row:s})}}handle(e){if(Fs.has(e.type))for(const e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);switch(e.type){case"START":this.selection.observe(this,{handleEvent:this.handleEvent.bind(this)}),this.resetViewports(this.getters.getActiveSheetId());break;case"UNDO":case"REDO":this.cleanViewports();for(const e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);this.shouldAdjustViewports=!0;break;case"RESIZE_SHEETVIEW":this.resizeSheetView(e.height,e.width,e.gridOffsetX,e.gridOffsetY);break;case"SET_VIEWPORT_OFFSET":this.setSheetViewOffset(e.offsetX,e.offsetY);break;case"SHIFT_VIEWPORT_DOWN":const t=this.getters.getActiveSheetId(),{top:o,viewportHeight:s,offsetCorrectionY:i}=this.getMainInternalViewport(t),n=this.getters.getRowDimensions(t,o);this.shiftVertically(n.start+s-i);break;case"SHIFT_VIEWPORT_UP":{const e=this.getters.getActiveSheetId(),{top:t,viewportHeight:o,offsetCorrectionY:s}=this.getMainInternalViewport(e),i=this.getters.getRowDimensions(e,t);this.shiftVertically(i.end-s-o);break}case"REMOVE_TABLE":case"UPDATE_TABLE":case"UPDATE_FILTER":case"UNFREEZE_ROWS":case"UNFREEZE_COLUMNS":case"FREEZE_COLUMNS":case"FREEZE_ROWS":case"UNFREEZE_COLUMNS_ROWS":case"REMOVE_COLUMNS_ROWS":case"RESIZE_COLUMNS_ROWS":case"HIDE_COLUMNS_ROWS":case"ADD_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"UNGROUP_HEADERS":case"GROUP_HEADERS":case"FOLD_HEADER_GROUP":case"UNFOLD_HEADER_GROUP":case"FOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_HEADER_GROUPS_IN_ZONE":case"UNFOLD_ALL_HEADER_GROUPS":case"FOLD_ALL_HEADER_GROUPS":this.sheetsWithDirtyViewports.add(e.sheetId);break;case"UPDATE_CELL":if("content"in e||"format"in e||void 0!==e.style?.fontSize)for(const e of this.getters.getSheetIds())this.sheetsWithDirtyViewports.add(e);break;case"DELETE_SHEET":this.cleanViewports(),this.sheetsWithDirtyViewports.delete(e.sheetId);break;case"ACTIVATE_SHEET":this.sheetsWithDirtyViewports.add(e.sheetIdTo);break;case"SCROLL_TO_CELL":this.refreshViewport(this.getters.getActiveSheetId(),{col:e.col,row:e.row})}}finalize(){for(const e of this.sheetsWithDirtyViewports)if(this.resetViewports(e),this.shouldAdjustViewports){const t=this.getters.getSheetPosition(e);this.getSubViewports(e).forEach((e=>{e.adjustPosition(t)}))}this.sheetsWithDirtyViewports=new Set,this.shouldAdjustViewports=!1,this.setViewports()}setViewports(){const e=this.getters.getSheetIds();for(const t of e)this.viewports[t]?.bottomRight||this.resetViewports(t)}getColIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map((t=>t.getColIndex(e))))}getRowIndex(e){const t=this.getters.getActiveSheetId();return Math.max(...this.getSubViewports(t).map((t=>t.getRowIndex(e))))}getSheetViewDimensionWithHeaders(){return{width:this.sheetViewWidth+this.gridOffsetX,height:this.sheetViewHeight+this.gridOffsetY}}getSheetViewDimension(){return{width:this.sheetViewWidth,height:this.sheetViewHeight}}getGridOffset(){return{x:this.gridOffsetX,y:this.gridOffsetY}}getActiveMainViewport(){const e=this.getters.getActiveSheetId();return this.getMainViewport(e)}getActiveSheetScrollInfo(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e);return{scrollX:t.offsetX,scrollY:t.offsetY}}getSheetViewVisibleCols(){const e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map((e=>je(e.left,e.right+1))).flat())].filter((t=>t>=0&&!this.getters.isHeaderHidden(e,"COL",t)))}getSheetViewVisibleRows(){const e=this.getters.getActiveSheetId(),t=this.getSubViewports(e);return[...new Set(t.map((e=>je(e.top,e.bottom+1))).flat())].filter((t=>t>=0&&!this.getters.isHeaderHidden(e,"ROW",t)))}getVisibleCellPositions(){const e=this.getSheetViewVisibleCols(),t=this.getSheetViewVisibleRows(),o=this.getters.getActiveSheetId(),s=[];for(const i of e)for(const e of t){const t={sheetId:o,col:i,row:e},n=this.getters.getMainCellPosition(t);n.row===e&&n.col===i&&s.push(t)}return s}getMainViewportRect(){const e=this.getters.getActiveSheetId(),t=this.getMainInternalViewport(e),{xSplit:o,ySplit:s}=this.getters.getPaneDivisions(e),{width:i,height:n}=t.getMaxSize();return{x:this.getters.getColDimensions(e,o).start,y:this.getters.getRowDimensions(e,s).start,width:i,height:n}}getMaximumSheetOffset(){const e=this.getters.getActiveSheetId(),{width:t,height:o}=this.getMainViewportRect(),s=this.getMainInternalViewport(e);return{maxOffsetX:Math.max(0,t-s.viewportWidth),maxOffsetY:Math.max(0,o-s.viewportHeight)}}getColRowOffsetInViewport(e,t,o){if(o<t)return-this.getColRowOffsetInViewport(e,o,t);const s=this.getters.getActiveSheetId(),i="COL"===e?this.getters.getSheetViewVisibleCols():this.getters.getSheetViewVisibleRows(),n=i.findIndex((e=>t>=e));let r=i.findIndex((e=>o<=e));r=-1===r?i.length:r;const a=i.slice(n,r);let l=0;for(const t of a)l+=this.getters.getHeaderSize(s,e,t);return l}isVisibleInViewport({sheetId:e,col:t,row:o}){return this.getSubViewports(e).some((e=>e.isVisible(t,o)))}getEdgeScrollCol(e,t,o){let s=!1,i=0,n=0;const{xSplit:r}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{width:a}=this.getSheetViewDimension(),{x:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollX;return e>a?(s=!0,n=jr(e-a),i=1):e<l&&o>=l&&c>0?(s=!0,n=jr(l-e),i=-1):r&&t<l&&e>l&&(s=!0,n=jr(e),i="reset"),{canEdgeScroll:s,direction:i,delay:n}}getEdgeScrollRow(e,t,o){let s=!1,i=0,n=0;const{ySplit:r}=this.getters.getPaneDivisions(this.getters.getActiveSheetId()),{height:a}=this.getSheetViewDimension(),{y:l}=this.getMainViewportCoordinates(),c=this.getActiveSheetScrollInfo().scrollY;return e>a?(s=!0,n=jr(e-a),i=1):e<l&&o>=l&&c>0?(s=!0,n=jr(l-e),i=-1):r&&t<l&&e>l&&(s=!0,n=jr(e),i="reset"),{canEdgeScroll:s,direction:i,delay:n}}getVisibleRect(e){const t=this.getVisibleRectWithoutHeaders(e);return{...t,x:t.x+this.gridOffsetX,y:t.y+this.gridOffsetY}}getVisibleRectWithoutHeaders(e){const t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,(t=>t.getVisibleRect(e)))}getRect(e){const t=this.getters.getActiveSheetId(),o=this.mapViewportsToRect(t,(t=>t.getFullRect(e)));return{...o,x:o.x+this.gridOffsetX,y:o.y+this.gridOffsetY}}getRectWithoutHeaders(e){const t=this.getters.getActiveSheetId();return this.mapViewportsToRect(t,(t=>t.getFullRect(e)))}getMainViewportCoordinates(){const e=this.getters.getActiveSheetId(),{xSplit:t,ySplit:o}=this.getters.getPaneDivisions(e);return{x:this.getters.getColDimensions(e,t).start,y:this.getters.getRowDimensions(e,o).start}}getColDimensionsInViewport(e,t){const{top:o}=this.getMainInternalViewport(e),s={left:t,right:t,top:o,bottom:o},{x:i,width:n}=this.getVisibleRect(s),r=i-this.gridOffsetX;return{start:r,size:n,end:r+n}}getRowDimensionsInViewport(e,t){const{left:o}=this.getMainInternalViewport(e),s={left:0,right:o,top:t,bottom:t},{y:i,height:n}=this.getVisibleRect(s),r=i-this.gridOffsetY;return{start:r,size:n,end:r+n}}getAllActiveViewportsZonesAndRect(){const e=this.getters.getActiveSheetId();return this.getSubViewports(e).map((e=>({zone:e,rect:{x:e.offsetCorrectionX+this.gridOffsetX,y:e.offsetCorrectionY+this.gridOffsetY,...e.getMaxSize()}})))}ensureMainViewportExist(e){this.viewports[e]||this.resetViewports(e)}getSubViewports(e){return this.ensureMainViewportExist(e),Object.values(this.viewports[e]).filter(lt)}checkPositiveDimension(e){return e.width<0||e.height<0?"InvalidViewportSize":"Success"}checkValuesAreDifferent(e){const{height:t,width:o}=this.getSheetViewDimension();return e.gridOffsetX===this.gridOffsetX&&e.gridOffsetY===this.gridOffsetY&&e.width===o&&e.height===t?"ValuesNotChanged":"Success"}checkScrollingDirection({offsetX:e,offsetY:t}){const o=this.getMainInternalViewport(this.getters.getActiveSheetId());return!o.canScrollHorizontally&&e>0||!o.canScrollVertically&&t>0?"InvalidScrollingDirection":"Success"}checkIfViewportsWillChange({offsetX:e,offsetY:t}){const o=this.getters.getActiveSheetId(),{maxOffsetX:s,maxOffsetY:i}=this.getMaximumSheetOffset();return this.getSubViewports(o).some((o=>o.willNewOffsetScrollViewport(Ze(e,0,s),Ze(t,0,i))))?"Success":"ViewportScrollLimitsReached"}getMainViewport(e){const t=this.getMainInternalViewport(e);return{top:t.top,left:t.left,bottom:t.bottom,right:t.right}}getMainInternalViewport(e){return this.ensureMainViewportExist(e),this.viewports[e].bottomRight}cleanViewports(){const e={};for(const t of this.getters.getSheetIds())e[t]=this.viewports[t];this.viewports=e}resizeSheetView(e,t,o=0,s=0){this.sheetViewHeight=e,this.sheetViewWidth=t,this.gridOffsetX=o,this.gridOffsetY=s,this.recomputeViewports()}recomputeViewports(){for(const e of this.getters.getSheetIds())this.resetViewports(e)}setSheetViewOffset(e,t){const o=this.getters.getActiveSheetId(),{maxOffsetX:s,maxOffsetY:i}=this.getMaximumSheetOffset();this.getSubViewports(o).forEach((o=>o.setViewportOffset(Ze(e,0,s),Ze(t,0,i))))}getViewportOffset(e){return{x:this.viewports[e]?.bottomRight.offsetX||0,y:this.viewports[e]?.bottomRight.offsetY||0}}resetViewports(e){if(!this.getters.tryGetSheet(e))return;const{xSplit:t,ySplit:o}=this.getters.getPaneDivisions(e),s=this.getters.getNumberCols(e),i=this.getters.getNumberRows(e),n=Math.min(this.getters.getColRowOffset("COL",0,t,e),this.sheetViewWidth),r=Math.min(this.getters.getColRowOffset("ROW",0,o,e),this.sheetViewHeight),a=Math.max(this.sheetViewWidth-n,0),l=Math.max(this.sheetViewHeight-r,0),{xRatio:c,yRatio:h}=this.getFrozenSheetViewRatio(e),d=c<1,u=h<1,g=this.getViewportOffset(e),p={topLeft:o&&t&&new IL(this.getters,e,{left:0,right:t-1,top:0,bottom:o-1},{width:n,height:r},{canScrollHorizontally:!1,canScrollVertically:!1},{x:0,y:0})||void 0,topRight:o&&new IL(this.getters,e,{left:t,right:s-1,top:0,bottom:o-1},{width:a,height:r},{canScrollHorizontally:d,canScrollVertically:!1},{x:d?g.x:0,y:0})||void 0,bottomLeft:t&&new IL(this.getters,e,{left:0,right:t-1,top:o,bottom:i-1},{width:n,height:l},{canScrollHorizontally:!1,canScrollVertically:u},{x:0,y:u?g.y:0})||void 0,bottomRight:new IL(this.getters,e,{left:t,right:s-1,top:o,bottom:i-1},{width:a,height:l},{canScrollHorizontally:d,canScrollVertically:u},{x:d?g.x:0,y:u?g.y:0})};this.viewports[e]=p}refreshViewport(e,t){this.getSubViewports(e).forEach((e=>{e.adjustViewportZone(),e.adjustPosition(t)}))}shiftVertically(e){const t=this.getters.getActiveSheetId(),{top:o}=this.getMainInternalViewport(t),{scrollX:s}=this.getActiveSheetScrollInfo();this.setSheetViewOffset(s,e);const{anchor:i}=this.getters.getSelection();if(i.cell.row>=this.getters.getPaneDivisions(t).ySplit){const e=this.getMainInternalViewport(t).top-o;this.selection.selectCell(i.cell.col,i.cell.row+e)}}getColIndexLeftOfMainViewport(e){if(e>=0)return-1;const t=this.getters.getActiveSheetId();let o=this.getActiveMainViewport().left,s=-this.getActiveSheetScrollInfo().scrollX-this.getters.getColRowOffset("COL",o,0);for(;e<s;o--)s-=this.getters.getColSize(t,o-1);return Math.max(o,0)}getRowIndexTopOfMainViewport(e){if(e>=0)return-1;const t=this.getters.getActiveSheetId();let o=this.getActiveMainViewport().top,s=-this.getActiveSheetScrollInfo().scrollY-this.getters.getColRowOffset("ROW",o,0);for(;e<s;o--)s-=this.getters.getRowSize(t,o-1);return Math.max(o,0)}getVisibleFigures(){const e=this.getters.getActiveSheetId(),t=[],o=this.getters.getFigures(e),{scrollX:s,scrollY:i}=this.getters.getActiveSheetScrollInfo(),{x:n,y:r}=this.getMainViewportCoordinates(),{width:a,height:l}=this.getters.getSheetViewDimensionWithHeaders();for(const c of o){const o=this.getFigureUI(e,c),{x:h,y:d}=o;h>=n&&(h+c.width<s+n||h>a+s+n)||(d>=r&&(d+c.height<i+r||d>l+i+r)||t.push(o))}return t}getFigureUI(e,t){const o=t.offset.x+this.getters.getColDimensions(e,t.col).start,s=t.offset.y+this.getters.getRowDimensions(e,t.row).start;return{...t,x:o,y:s}}getPositionAnchorOffset(e){const{scrollX:t,scrollY:o}=this.getters.getActiveSheetScrollInfo(),s=e.x-t,i=e.y-o,n=s>=0?this.getColIndex(s):this.getColIndexLeftOfMainViewport(s),r=i>=0?this.getRowIndex(i):this.getRowIndexTopOfMainViewport(i),{x:a,y:l}=this.getRect(Mr({col:n,row:r}));return{col:n,row:r,offset:{x:Math.max(s-a+this.gridOffsetX,0),y:Math.max(i-l+this.gridOffsetY,0)}}}isPixelPositionVisible(e){const{scrollX:t,scrollY:o}=this.getters.getActiveSheetScrollInfo(),{x:s,y:i}=this.getters.getMainViewportCoordinates(),{width:n,height:r}=this.getters.getSheetViewDimension();return!(e.x>=s&&(e.x<s+t||e.x>n+t+s))&&!(e.y>=i&&(e.y<i+o||e.y>r+o+i))}getFrozenSheetViewRatio(e){const{xSplit:t,ySplit:o}=this.getters.getPaneDivisions(e),s=this.getters.getColDimensions(e,t).start,i=this.getters.getRowDimensions(e,o).start;return{xRatio:s/(this.sheetViewWidth+this.gridOffsetX),yRatio:i/(this.sheetViewHeight+this.gridOffsetY)}}mapViewportsToRect(e,t){let o=1/0,s=1/0,i=0,n=0,r=!1;for(const a of this.getSubViewports(e)){const e=t(a);e&&(r=!0,o=Math.min(o,e.x),s=Math.min(s,e.y),i=Math.max(i,e.x+e.width),n=Math.max(n,e.y+e.height))}return r?{x:o,y:s,width:i-o,height:n-s}:{x:0,y:0,width:0,height:0}}}).add("clipboard",class extends BV{static layers=["Clipboard"];static getters=["getClipboardTextAndImageContent","getClipboardId","getClipboardTextContent","isCutOperation"];status="invisible";originSheetId;copiedData;_isCutOperation=!1;clipboardId=(new Ka).uuidv4();fileStore;uuidGenerator;constructor(e){super(e),this.fileStore=e.external.fileStore,this.uuidGenerator=new Ka}allowDispatch(e){switch(e.type){case"CUT":const t=this.getters.getSelectedZones();return this.isCutAllowedOn(t);case"PASTE_FROM_OS_CLIPBOARD":{const t=this.convertTextToClipboardData(e.clipboardContent.text??""),o=e.pasteOption;return this.isPasteAllowed(e.target,t,{pasteOption:o,isCutOperation:!1})}case"PASTE":{if(!this.copiedData)return"EmptyClipboard";const t=e.pasteOption;return this.isPasteAllowed(e.target,this.copiedData,{pasteOption:t,isCutOperation:this._isCutOperation})}case"COPY_PASTE_CELLS_ABOVE":{const e=this.getters.getSelectedZones();if(e.length>1||0===e[0].top&&0===e[0].bottom)return"InvalidCopyPasteSelection";break}case"COPY_PASTE_CELLS_ON_LEFT":{const e=this.getters.getSelectedZones();if(e.length>1||0===e[0].left&&0===e[0].right)return"InvalidCopyPasteSelection";break}case"INSERT_CELL":{const{cut:t,paste:o}=this.getInsertCellsTargets(e.zone,e.shiftDimension),s=this.copy(t,"shiftCells");return this.isPasteAllowed(o,s,{isCutOperation:!0})}case"DELETE_CELL":{const{cut:t,paste:o}=this.getDeleteCellsTargets(e.zone,e.shiftDimension),s=this.copy(t,"shiftCells");return this.isPasteAllowed(o,s,{isCutOperation:!0})}}return"Success"}handle(e){switch(e.type){case"COPY":case"CUT":const t=this.getters.getSelectedZones();this.status="visible",this.originSheetId=this.getters.getActiveSheetId(),this._isCutOperation="CUT"===e.type,this.copiedData=this.copy(t);break;case"PASTE_FROM_OS_CLIPBOARD":{this._isCutOperation=!1;const t=e.clipboardContent.data;if(e.clipboardContent.imageData){const t=this.getters.getActiveSheetId(),o=this.uuidGenerator.uuidv4(),s=e.clipboardContent.imageData,i=px(this.getters,s.size);this.dispatch("CREATE_IMAGE",{definition:s,size:i,col:e.target[0].left,row:e.target[0].top,offset:{x:0,y:0},sheetId:t,figureId:o})}this.copiedData=t||this.convertTextToClipboardData(e.clipboardContent.text??"");const o=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:o,selectTarget:!0,isCutOperation:!1}),this.status="invisible",this.copiedData=void 0;break}case"PASTE":{const t=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:t,selectTarget:!0,isCutOperation:this._isCutOperation}),this.status="invisible",this._isCutOperation&&(this.copiedData=void 0,this._isCutOperation=!1);break}case"COPY_PASTE_CELLS_ABOVE":{const e=this.getters.getSelectedZone(),t=e.top!==e.bottom,o={...e,bottom:t?e.top:e.top-1,top:t?e.top:e.top-1};this.originSheetId=this.getters.getActiveSheetId();const s=this.copy([o]);this.paste([e],s,{isCutOperation:!1,selectTarget:!0})}break;case"COPY_PASTE_CELLS_ON_LEFT":{const e=this.getters.getSelectedZone(),t=e.left!==e.right,o={...e,right:t?e.left:e.left-1,left:t?e.left:e.left-1};this.originSheetId=this.getters.getActiveSheetId();const s=this.copy([o]);this.paste([e],s,{isCutOperation:!1,selectTarget:!0})}break;case"CLEAN_CLIPBOARD_HIGHLIGHT":this.status="invisible";break;case"DELETE_CELL":{const{cut:t,paste:o}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!pr(t[0])){this.dispatch("CLEAR_CELLS",{target:[e.zone],sheetId:this.getters.getActiveSheetId()});break}const s=this.copy(t,"shiftCells");this.paste(o,s,{isCutOperation:!0});break}case"INSERT_CELL":{const{cut:t,paste:o}=this.getInsertCellsTargets(e.zone,e.shiftDimension),s=this.copy(t,"shiftCells");this.paste(o,s,{isCutOperation:!0});break}case"ADD_COLUMNS_ROWS":if(this.status="invisible",!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;this.isColRowDirtyingClipboard("before"===e.position?e.base:e.base+1,e.dimension)&&(this.copiedData=void 0);break;case"REMOVE_COLUMNS_ROWS":if(this.status="invisible",!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;for(const t of e.elements){if(this.isColRowDirtyingClipboard(t,e.dimension)){this.copiedData=void 0;break}}this.status="invisible";break;case"REPEAT_PASTE":this.paste(e.target,this.copiedData,{isCutOperation:!1,pasteOption:e.pasteOption,selectTarget:!0});break;case"DELETE_SHEET":if(!this._isCutOperation)return;this.originSheetId===e.sheetId&&(this.copiedData=void 0,this.status="invisible");break;default:Hs(e)&&(this.status="invisible")}}convertTextToClipboardData(e){const t=this.selectClipboardHandlers({figureId:!0}).concat(this.selectClipboardHandlers({})),o={};for(const{handlerName:s,handler:i}of t){const t=i.convertTextToClipboardData(e);o[s]=t;const n=["sheetId","cells","zones","figureId"];for(const e of n)t&&e in t&&(o[e]=t[e])}return o}selectClipboardHandlers(e){const t="figureId"in e?eh.figureHandlers:eh.cellHandlers;return t.getKeys().map((e=>({handlerName:e,handler:new(t.get(e))(this.getters,this.dispatch)})))}isCutAllowedOn(e){const t=this.getClipboardData(e);for(const{handler:e}of this.selectClipboardHandlers(t)){const o=e.isCutAllowed(t);if("Success"!==o)return o}return"Success"}isPasteAllowed(e,t,o){for(const{handler:s}of this.selectClipboardHandlers(t)){const i=s.isPasteAllowed(this.getters.getActiveSheetId(),e,t,{...o});if("Success"!==i)return i}return"Success"}isColRowDirtyingClipboard(e,t){if(!this.copiedData||!this.copiedData.zones)return!1;const{zones:o}=this.copiedData;for(const s of o){if("COL"===t&&e<=s.right)return!0;if("ROW"===t&&e<=s.bottom)return!0}return!1}copy(e,t="copyPaste"){const o={},s=this.getClipboardData(e);for(const{handlerName:e,handler:i}of this.selectClipboardHandlers(s)){const n=i.copy(s,this._isCutOperation,t);o[e]=n;const r=["sheetId","cells","zones","figureId"];for(const e of r)n&&e in n&&(o[e]=n[e])}return o}paste(e,t,o){if(!t)return;const s=this.getters.getActiveSheetId(),i=this.selectClipboardHandlers(t),{target:n,zone:r,selectedZones:a}=sl(s,e,t,i,o);void 0!==r&&this.addMissingDimensions(s,r.right-r.left+1,r.bottom-r.top+1,r.left,r.top),ol(i,t,n,o),o?.selectTarget&&il(this.selection,e,a)}addMissingDimensions(e,t,o,s,i){const n=o+i-this.getters.getNumberRows(e);n>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"ROW",base:this.getters.getNumberRows(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:n,position:"after"});const r=t+s-this.getters.getNumberCols(e);r>0&&this.dispatch("ADD_COLUMNS_ROWS",{dimension:"COL",base:this.getters.getNumberCols(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:r,position:"after"})}getClipboardTextContent(){return this.getPlainTextContent()}getClipboardId(){return this.clipboardId}async getClipboardTextAndImageContent(){const e=await this.getImageContent(),t=e?.type,o={[Os.PlainText]:this.getPlainTextContent(),[Os.Html]:await this.getHTMLContent()};return t&&e&&(o[t]=e),o}getSheetData(){const e={version:hD(),clipboardId:this.clipboardId};return this.copiedData&&"figureId"in this.copiedData?e:{...e,...this.copiedData}}getPlainTextContent(){return this.copiedData?.cells&&this.copiedData.cells.map((e=>e.map((e=>this.getters.shouldShowFormulas()&&e?.tokens?.length?e?.content||"":e.evaluatedCell?.formattedValue||"")).join("\t"))).join("\n")||"\t"}async getHTMLContent(){let e="";const t=this.copiedData?.cells;if(t)if(1===t.length&&1===t[0].length)e=`${this.getters.getCellText(t[0][0].position)}`;else{if(!t[0][0])return"";{let o='<table border="1" style="border-collapse:collapse">';for(const e of t){o+="<tr>";for(const t of e){if(!t)continue;o+=`<td style="${xh(Ih(this.getters.getCellComputedStyle(t.position)))}">`+bx(this.getters.getCellText(t.position))+"</td>"}o+="</tr>"}o+="</table>",e=o}}else if(this.copiedData?.figureId){const t=this.copiedData.figureId,o=this.getters.getFigureSheetId(t);e="image"===this.getters.getFigure(o,t).tag?await this.craftImageHTML(t):"\t"}else e="\t";return`<div data-osheet-clipboard='${bx(JSON.stringify(this.getSheetData()))}'>${e}</div>`}readFileAsDataURL(e){return new Promise((t=>{const o=new FileReader;o.onload=()=>t(o.result),o.readAsDataURL(e)}))}async craftImageHTML(e){if(!this.fileStore)return"\t";const t=this.getters.getImage(e).path,o=await(this.fileStore?.getFile(t))||null;if(o){return`<img src="${bx(await this.readFileAsDataURL(o))}" />`}return"\t"}async getImageContent(){const e=this.copiedData?.figureId;if(!e)return;const t=this.getters.getFigureSheetId(e);let o;if("image"===this.getters.getFigure(t,e).tag){if(!this.fileStore)return;const t=this.getters.getImage(e).path;if(o=await(this.fileStore?.getFile(t)),"image/png"!==o.type){if(o.size>yL)return void this.ui.notifyUI({text:Ho("The file you are trying to copy is too large (>%sMB).\nIt will not be added to your OS clipboard.\nYou can download it directly instead.",Math.round(5)),sticky:!1,type:"warning"});o=await async function(e){return new Promise(((t,o)=>{const s=new Image;s.addEventListener("load",(()=>{const e=document.createElement("canvas");e.width=s.width,e.height=s.height;const o=e.getContext("2d");o?.drawImage(s,0,0),e.toBlob(t,"image/png")})),s.addEventListener("error",o),s.src=e}))}(t)}}return o?o instanceof File?o:new File([o],"image.png",{type:"image/png"}):void 0}isCutOperation(){return this._isCutOperation??!1}getDeleteCellsTargets(e,t){const o=this.getters.getActiveSheetId();let s;return s="COL"===t?{...e,left:e.right+1,right:this.getters.getNumberCols(o)-1}:{...e,top:e.bottom+1,bottom:this.getters.getNumberRows(o)-1},{cut:[s],paste:[e]}}getInsertCellsTargets(e,t){const o=this.getters.getActiveSheetId();let s,i;return"COL"===t?(s={...e,right:this.getters.getNumberCols(o)-1},i={...e,left:e.right+1,right:e.right+1}):(s={...e,bottom:this.getters.getNumberRows(o)-1},i={...e,top:e.bottom+1,bottom:this.getters.getNumberRows(o)-1}),{cut:[s],paste:[i]}}getClipboardData(e){const t=this.getters.getActiveSheetId(),o=this.getters.getSelectedFigureId();if(o)return{figureId:o,sheetId:t};const s=Qa(t,e);return this._isCutOperation||(s.rowsIndexes=s.rowsIndexes.filter((e=>!this.getters.isRowFiltered(t,e)))),s}drawLayer(e){if("visible"!==this.status||!this.copiedData)return;const{sheetId:t,zones:o}=this.copiedData;if(t!==this.getters.getActiveSheetId()||!o||!o.length)return;const{ctx:s,thinLineWidth:i}=e;s.setLineDash([8,5]),s.strokeStyle=p,s.lineWidth=3.3*i;for(const e of o){const{x:t,y:o,width:i,height:n}=this.getters.getVisibleRect(e);i>0&&n>0&&s.strokeRect(t,o,i,n)}}}),TL=(new n).add("evaluation",class extends $k{static getters=["evaluateFormula","evaluateFormulaResult","evaluateCompiledFormula","getCorrespondingFormulaCell","getRangeFormattedValues","getRangeValues","getRangeFormats","getEvaluatedCell","getEvaluatedCells","getEvaluatedCellsInZone","getEvaluatedCellsPositions","getSpreadZone","getArrayFormulaSpreadingOn","isEmpty"];shouldRebuildDependenciesGraph=!0;evaluator;positionsToUpdate=[];constructor(e){super(e),this.evaluator=new yV(e.custom,this.getters)}beforeHandle(e){(Fs.has(e.type)||Ms.has(e.type))&&(this.shouldRebuildDependenciesGraph=!0)}handle(e){switch(e.type){case"UPDATE_CELL":if(!("content"in e)&&!("format"in e)||this.shouldRebuildDependenciesGraph)return;const t={sheetId:e.sheetId,row:e.row,col:e.col};this.positionsToUpdate.push(t),"content"in e&&this.evaluator.updateDependencies(t);break;case"EVALUATE_CELLS":this.evaluator.evaluateAllCells()}}finalize(){this.shouldRebuildDependenciesGraph?(this.evaluator.buildDependencyGraph(),this.evaluator.evaluateAllCells(),this.shouldRebuildDependenciesGraph=!1):this.positionsToUpdate.length&&this.evaluator.evaluateCells(this.positionsToUpdate),this.positionsToUpdate=[]}evaluateFormula(e,t){const o=this.evaluateFormulaResult(e,t);return js(o)?ki(o,(e=>e.value)):o.value}evaluateFormulaResult(e,t){return this.evaluator.evaluateFormulaResult(e,t)}evaluateCompiledFormula(e,t,o){return this.evaluator.evaluateCompiledFormula(e,t,o)}getRangeFormattedValues(e){return void 0===this.getters.tryGetSheet(e.sheetId)?[]:this.mapVisiblePositions(e,(e=>this.getters.getEvaluatedCell(e).formattedValue))}getRangeValues(e){return void 0===this.getters.tryGetSheet(e.sheetId)?[]:this.mapVisiblePositions(e,(e=>this.getters.getEvaluatedCell(e).value))}getRangeFormats(e){const t=this.getters.tryGetSheet(e.sheetId);return void 0===t?[]:this.getters.getEvaluatedCellsInZone(t.id,e.zone).map((e=>e.format))}getEvaluatedCell(e){return this.evaluator.getEvaluatedCell(e)}getEvaluatedCells(e){return this.evaluator.getEvaluatedPositionsInSheet(e).map((e=>this.getEvaluatedCell(e)))}getEvaluatedCellsPositions(e){return this.evaluator.getEvaluatedPositionsInSheet(e)}getEvaluatedCellsInZone(e,t){return _r(t).map((({col:t,row:o})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:o})))}getSpreadZone(e,t={ignoreSpillError:!1}){return this.evaluator.getSpreadZone(e,t)}getArrayFormulaSpreadingOn(e){return this.evaluator.getArrayFormulaSpreadingOn(e)}isEmpty(e,t){return _r(t).map((({col:t,row:o})=>this.getEvaluatedCell({sheetId:e,col:t,row:o}))).every((e=>e.type===_s.empty))}mapVisiblePositions(e,t){const{sheetId:o,zone:s}=e;return _r(s).reduce(((e,s)=>{const{col:i,row:n}=s;return this.getters.isColHidden(o,i)||this.getters.isRowHidden(o,n)||e.push(t({sheetId:o,...s})),e}),[])}exportForExcel(e){for(const t of e.sheets)t.cellValues={},t.formulaSpillRanges={};for(const t of this.evaluator.getEvaluatedPositions()){const o=this.evaluator.getEvaluatedCell(t),s=Po(t.col,t.row),i=o.value;let n,r=!1,a=!0;const l=e.sheets.find((e=>e.id===t.sheetId)),c=this.getCorrespondingFormulaCell(t);if(c){const h=this.getters.getCell(t);if(a=$S(c.compiledFormula.tokens),r=a&&h?.content===c.content,!a&&""!==i){n=(i??"").toString();const t=o.format;if(t){const o=Gr(t,e.formats);l.formats[s]=o}}}const h=l.cells[s];let d;d=a&&r&&c instanceof kk?c.contentWithFixedReferences:a?h:n,l.cells[s]=d,l.cellValues[s]="error"!==o.type?i:void 0;const u=this.getSpreadZone(t);u&&(l.formulaSpillRanges[s]=this.getters.getRangeString(this.getters.getRangeFromZone(t.sheetId,u),t.sheetId))}}getCorrespondingFormulaCell(e){const t=this.getters.getCell(e);if(t&&t.isFormula)return t.compiledFormula.isBadExpression?void 0:t;if(t&&t.content)return;const o=this.getArrayFormulaSpreadingOn(e);if(void 0===o)return;const s=this.getters.getCell(o);return s?.isFormula?s:void 0}}).add("evaluation_chart",class extends $k{static getters=["getChartRuntime","getStyleOfSingleCellChart"];charts={};createRuntimeChart=lx(this.getters);handle(e){if(Fs.has(e.type)||Ns.has(e.type)||Ps.has(e.type))for(const e in this.charts)this.charts[e]=void 0;switch(e.type){case"UPDATE_CHART":case"CREATE_CHART":case"DELETE_FIGURE":this.charts[e.figureId]=void 0;break;case"DELETE_SHEET":for(const e in this.charts)this.getters.isChartDefined(e)||(this.charts[e]=void 0)}}getChartRuntime(e){if(!this.charts[e]){const t=this.getters.getChart(e);if(!t)throw new Error(`No chart for the given id: ${e}`);this.charts[e]=this.createRuntimeChart(t)}return this.charts[e]}getStyleOfSingleCellChart(e,t){if(e)return{background:e,fontColor:rC(e)};if(!t)return{background:m,fontColor:rC(m)};const o=t.zone.left,s=t.zone.top,i=t.sheetId,n=this.getters.getCellComputedStyle({sheetId:i,col:o,row:s}),r=n.fillColor||m;return{background:r,fontColor:n.textColor||rC(r)}}exportForExcel(e){for(const t of e.sheets){t.images||(t.images=[]);const e=this.getters.getFigures(t.id),o=[];for(const s of e){if(!s||"chart"!==s.tag)continue;const e=s.id,i=this.getters.getChart(e)?.getDefinitionForExcel();if(i)o.push({...s,data:i});else{if(!this.getters.getChart(e))continue;const o=this.getters.getChartType(e),i=Wy(this.getters.getChartRuntime(e),s,o);i&&t.images.push({...s,tag:"image",data:{mimetype:"image/png",path:i,size:{width:s.width,height:s.height}}})}}t.charts=o}}}).add("evaluation_cf",class extends $k{static getters=["getConditionalIcon","getCellConditionalFormatStyle","getConditionalDataBar"];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(Fs.has(e.type)||Ns.has(e.type)||"UPDATE_CELL"===e.type&&("content"in e||"format"in e))&&(this.isStale=!0)}finalize(){if(this.isStale){for(const e of this.getters.getSheetIds())this.computedStyles[e]=ut((()=>this.getComputedStyles(e))),this.computedIcons[e]=ut((()=>this.getComputedIcons(e))),this.computedDataBars[e]=ut((()=>this.getComputedDataBars(e)));this.isStale=!1}}getCellConditionalFormatStyle(e){const{sheetId:t,col:o,row:s}=e,i=this.computedStyles[t]();return i&&i[o]?.[s]}getConditionalIcon({sheetId:e,col:t,row:o}){const s=this.computedIcons[e]();return s&&s[t]?.[o]}getConditionalDataBar({sheetId:e,col:t,row:o}){const s=this.computedDataBars[e]();return s&&s[t]?.[o]}getComputedStyles(e){const t={};for(const o of this.getters.getConditionalFormats(e).reverse())switch(o.rule.type){case"ColorScaleRule":for(const s of o.ranges)this.applyColorScale(e,s,o.rule,t);break;case"CellIsRule":const s=o.rule.values.map((e=>e.startsWith("=")?HS(e):void 0));for(const i of o.ranges){const n=this.getters.getRangeFromSheetXC(e,i).zone;for(let i=n.top;i<=n.bottom;i++)for(let r=n.left;r<=n.right;r++){const a={sheetId:e,col:r,row:i},l=o.rule.values.map(((t,o)=>{const a=s[o];return a?this.getters.getTranslatedCellFormula(e,r-n.left,i-n.top,a.tokens):t}));this.getRuleResultForTarget(a,{...o.rule,values:l})&&(t[r]||(t[r]=[]),t[r][i]=Object.assign(t[r]?.[i]||{},o.rule.style))}}}return t}getComputedIcons(e){const t={};for(const o of this.getters.getConditionalFormats(e).reverse())if("IconSetRule"===o.rule.type)for(const s of o.ranges)this.applyIcon(e,s,o.rule,t);return t}getComputedDataBars(e){const t={};for(const o of this.getters.getConditionalFormats(e).reverse())if("DataBarRule"===o.rule.type)for(const s of o.ranges)this.applyDataBar(e,s,o.rule,t);return t}parsePoint(e,t,o,s){const i=this.getters.getEvaluatedCellsInZone(e,this.getters.getRangeFromSheetXC(e,t).zone).filter((e=>e.type===_s.number)).map((e=>e.value));switch(o.type){case"value":return"max"===s?Ft(i):Pt(i);case"number":return Number(o.value);case"percentage":const t=Pt(i);return t+(Ft(i)-t)*Number(o.value)/100;case"percentile":return Ds(i,Number(o.value)/100,!0);case"formula":const n=o.value&&this.getters.evaluateFormula(e,o.value);return"number"==typeof n?n:null;default:return null}}applyIcon(e,t,o,s){const i=this.parsePoint(e,t,o.lowerInflectionPoint),n=this.parsePoint(e,t,o.upperInflectionPoint);if(null===i||null===n||i>n)return;const r=this.getters.getRangeFromSheetXC(e,t).zone,a=[o.icons.upper,o.icons.middle,o.icons.lower];for(let t=r.top;t<=r.bottom;t++)for(let l=r.left;l<=r.right;l++){const r=this.getters.getEvaluatedCell({sheetId:e,col:l,row:t});if(r.type!==_s.number)continue;const c=this.computeIcon(r.value,n,o.upperInflectionPoint.operator,i,o.lowerInflectionPoint.operator,a);s[l]||(s[l]=[]),s[l][t]=c}}computeIcon(e,t,o,s,i,n){return"ge"===o&&e>=t||"gt"===o&&e>t?n[0]:"ge"===i&&e>=s||"gt"===i&&e>s?n[1]:n[2]}applyDataBar(e,t,o,s){const i=this.getters.getRangeFromSheetXC(e,o.rangeValues||t),n=Ft(this.getters.getEvaluatedCellsInZone(e,i.zone).filter((e=>e.type===_s.number)).map((e=>e.value)));if(n<=0)return;const r=o.color,a=this.getters.getRangeFromSheetXC(e,t).zone,l=i.zone;for(let t=a.top;t<=a.bottom;t++)for(let o=a.left;o<=a.right;o++){const i=o-a.left+l.left,c=t-a.top+l.top,h=this.getters.getEvaluatedCell({sheetId:e,col:i,row:c});!Er(i,c,l)||h.type!==_s.number||h.value<=0||(s[o]||(s[o]=[]),s[o][t]={color:zt(r),percentage:100*h.value/n})}}applyColorScale(e,t,o,s){const i=this.parsePoint(e,t,o.minimum,"min"),n=o.midpoint?this.parsePoint(e,t,o.midpoint):null,r=this.parsePoint(e,t,o.maximum,"max");if(null===i||null===r||i>=r||n&&(i>=n||n>=r))return;const a=this.getters.getRangeFromSheetXC(e,t).zone,l=[{value:i,color:o.minimum.color}];o.midpoint&&n&&l.push({value:n,color:o.midpoint.color}),l.push({value:r,color:o.maximum.color});const c=So(l);for(let t=a.top;t<=a.bottom;t++)for(let o=a.left;o<=a.right;o++){const n=this.getters.getEvaluatedCell({sheetId:e,col:o,row:t});if(n.type===_s.number){const e=Ze(n.value,i,r);s[o]||(s[o]=[]),s[o][t]=s[o]?.[t]||{},s[o][t].fillColor=c(e)}}}getRuleResultForTarget(e,t){const o=this.getters.getEvaluatedCell(e);if(o.type===_s.error)return!1;const{sheetId:s}=e,i=eE.get(t.operator),n=t.values.map((e=>e.startsWith("=")?this.getters.evaluateFormula(s,e)??"":Kn(e,qs)));if(n.some(oc))return!1;const r={type:t.operator,values:n.map(ec)};return i.isValueValid(o.value??"",r,this.getters,s)}}).add("row_size",class extends $k{static getters=["getRowSize","getHeaderSize","getMaxAnchorOffset"];tallestCellInRow={};ctx=document.createElement("canvas").getContext("2d");beforeHandle(e){if("ADD_COLUMNS_ROWS"===e.type){if("COL"===e.dimension)return;const t=pt(e.position,e.base),o=Array(e.quantity).fill(void 0),s=Tt(this.tallestCellInRow[e.sheetId],o,t);this.history.update("tallestCellInRow",e.sheetId,s)}}handle(e){switch(e.type){case"START":for(const e of this.getters.getSheetIds())this.initializeSheet(e);break;case"CREATE_SHEET":this.initializeSheet(e.sheetId);break;case"DUPLICATE_SHEET":{const t=ze(this.tallestCellInRow[e.sheetId]);this.history.update("tallestCellInRow",e.sheetIdTo,t);break}case"DELETE_SHEET":const t={...this.tallestCellInRow};delete t[e.sheetId],this.history.update("tallestCellInRow",t);break;case"REMOVE_COLUMNS_ROWS":{if("COL"===e.dimension)return;const t=Rt(this.tallestCellInRow[e.sheetId],e.elements);this.history.update("tallestCellInRow",e.sheetId,t);break}case"RESIZE_COLUMNS_ROWS":{const t=e.sheetId;if("ROW"===e.dimension)for(const o of e.elements){const e=this.getRowTallestCell(t,o);this.history.update("tallestCellInRow",t,o,e)}else for(const o of je(0,this.getters.getNumberRows(t)))for(const s of e.elements)this.updateRowSizeForCellChange(t,o,s)}break;case"UPDATE_CELL":this.updateRowSizeForCellChange(e.sheetId,e.row,e.col);break;case"ADD_MERGE":case"REMOVE_MERGE":for(const t of e.target)for(const o of _r(t))this.updateRowSizeForCellChange(e.sheetId,o.row,o.col)}}getRowSize(e,t){return Math.round(this.getters.getUserRowSize(e,t)??this.tallestCellInRow[e][t]?.size??ie)}getMaxAnchorOffset(e,t,o){let{numberOfRows:s,numberOfCols:i}=this.getters.getSheetSize(e),n=0;for(;n<t&&s>0;s--)n+=this.getRowSize(e,s-1);let r=0;for(;r<o&&i>0;i--)r+=this.getters.getColSize(e,i-1);return{col:i,row:s,offset:{x:r-o,y:n-t}}}getHeaderSize(e,t,o){return this.getters.isHeaderHidden(e,t,o)?0:"ROW"===t?this.getRowSize(e,o):this.getters.getColSize(e,o)}updateRowSizeForCellChange(e,t,o){const s=this.tallestCellInRow[e]?.[t];if(s?.cell.col===o){const o=this.getRowTallestCell(e,t);this.history.update("tallestCellInRow",e,t,o)}const i=this.getCellHeight({sheetId:e,col:o,row:t});if(!(i<=ie)&&(!s&&i>ie||s&&i>s.size)){const s={cell:{sheetId:e,col:o,row:t},size:i};this.history.update("tallestCellInRow",e,t,s)}}initializeSheet(e){const t=[];for(let o=0;o<this.getters.getNumberRows(e);o++){const s=this.getRowTallestCell(e,o);t.push(s)}this.history.update("tallestCellInRow",e,t)}getCellHeight(e){if(this.isInMultiRowMerge(e))return ie;const t=this.getters.getCell(e),o=this.getters.getColSize(e.sheetId,e.col);return function(e,t,o){return t&&(t.isFormula||t.content)?Ma(e,t.isFormula?"":t.content,t.style,o):ie}(this.ctx,t,o)}isInMultiRowMerge(e){const t=this.getters.getMerge(e);return!!t&&t.bottom!==t.top}getRowTallestCell(e,t){if(void 0!==this.getters.getUserRowSize(e,t))return;const o=this.getters.getRowCells(e,t);let s,i=0;for(let e=0;e<o.length;e++){const t=this.getters.getCellById(o[e]);if(!t)continue;const n=this.getters.getCellPosition(t.id),r=this.getCellHeight(n);r>i&&r>ie&&(i=r,s={cell:n,size:r})}return s&&s.size>ie?s:void 0}}).add("data_validation_ui",class extends $k{static getters=["getDataValidationInvalidCriterionValueMessage","getInvalidDataValidationMessage","getValidationResultForCellValue","getDataValidationRangeValues","isCellValidCheckbox","getDataValidationCellStyle","getDataValidationChipStyle","isDataValidationInvalid"];validationResults={};handle(e){if(Fs.has(e.type)||"EVALUATE_CELLS"===e.type||"UPDATE_CELL"===e.type&&("content"in e||"format"in e))this.validationResults={};else switch(e.type){case"ADD_DATA_VALIDATION_RULE":case"REMOVE_DATA_VALIDATION_RULE":delete this.validationResults[e.sheetId]}}isDataValidationInvalid(e){return!this.getValidationResultForCell(e).isValid}getDataValidationCellStyle(e){if(!this.hasChip(e))return this.getDataValidationStyle(e)}getDataValidationChipStyle(e){if(this.hasChip(e))return this.getDataValidationStyle(e)??{fillColor:F}}getInvalidDataValidationMessage(e){const t=this.getValidationResultForCell(e);return t.isValid?void 0:t.error}getDataValidationInvalidCriterionValueMessage(e,t){const o=eE.get(e);return t.startsWith("=")?"onlyLiterals"===o.allowedValues?Ho("The value must not be a formula"):this.isValidFormula(t)?void 0:tw.CriterionError.validFormula:"onlyFormulas"===o.allowedValues?Ho("The value must be a formula"):o.isCriterionValueValid(t)?void 0:o.criterionValueErrorString}getDataValidationRangeValues(e,t){const o=this.getters.getRangeFromSheetXC(e,String(t.values[0])),s=[],i=new Set;for(const e of _r(o.zone)){const t=this.getters.getEvaluatedCell({...e,sheetId:o.sheetId});t.formattedValue&&!i.has(t.formattedValue)&&(i.add(t.formattedValue),s.push({label:t.formattedValue,value:t.value?.toString()||""}))}return s}isCellValidCheckbox(e){if(!this.getters.isMainCellPosition(e))return!1;const t=this.getters.getValidationRuleForCell(e);return!(!t||"isBoolean"!==t.criterion.type)&&this.getValidationResultForCell(e).isValid}getValidationResultForCellValue(e,t){const o=this.getters.getValidationRuleForCell(t);if(!o)return RV;const s=this.getRuleErrorForCellValue(e,t,o);return s?{error:s,rule:o,isValid:!1}:RV}hasChip(e){const t=this.getters.getValidationRuleForCell(e);return("isValueInList"===t?.criterion.type||"isValueInRange"===t?.criterion.type)&&"chip"===t.criterion.displayStyle}getDataValidationStyle(e){const t=this.getters.getValidationRuleForCell(e);if(!t||this.isDataValidationInvalid(e))return;const o=this.getters.getEvaluatedCell(e),s=this.getValueColor(t,o.value);if(!s)return;return{fillColor:s,textColor:no(s)}}getValueColor(e,t){if("isValueInList"===e.criterion.type||"isValueInRange"===e.criterion.type)for(const o in e.criterion.colors)if(o.toLowerCase()===String(t).toLowerCase())return e.criterion.colors[o]}isValidFormula(e){return!HS(e).isBadExpression}getValidationResultForCell(e){const{col:t,row:o,sheetId:s}=e;return this.validationResults[s]||(this.validationResults[s]=this.computeSheetValidationResults(s)),this.validationResults[s][t]?.[o]?.()||RV}computeSheetValidationResults(e){const t={},o=this.getters.getDataValidationRules(e).map((e=>e.ranges));for(const e of wa(o.flat())){const{col:o,row:s}=e;t[o]||(t[o]=[]),t[o][s]=ut((()=>{const t=this.getters.getEvaluatedCell(e);return t.type===_s.empty?RV:this.getValidationResultForCellValue(t.value,e)}))}return t}getRuleErrorForCellValue(e,t,o){const{sheetId:s}=t,i=o.criterion,n=eE.get(i.type),r=this.getCellOffsetInRule(t,o),a=this.getEvaluatedCriterionValues(s,r,i);if(a.some(oc))return;const l={...i,values:a.map(ec)};return n.isValueValid(e,l,this.getters,s)?void 0:n.getErrorString(l,this.getters,s)}getCellOffsetInRule(e,t){const o=t.ranges.find((t=>Er(e.col,e.row,t.zone)));if(!o)throw new Error("The cell is not in any range of the rule");return{col:e.col-o.zone.left,row:e.row-o.zone.top}}getEvaluatedCriterionValues(e,t,o){return o.values.map((o=>{if(!o.startsWith("="))return Kn(o,qs);const s=HS(o),i=this.getters.getTranslatedCellFormula(e,t.col,t.row,s.tokens);return this.getters.evaluateFormula(e,i)}))}}).add("dynamic_tables",class extends $k{static getters=["canCreateDynamicTableOnZones","doesZonesContainFilter","getFilter","getFilters","getTable","getTables","getTablesOverlappingZones","getFilterId","getFilterHeaders","isFilterHeader"];tables={};handle(e){if(Fs.has(e.type)||"UPDATE_CELL"===e.type&&("content"in e||"format"in e)||"EVALUATE_CELLS"===e.type)this.tables={};else switch(e.type){case"CREATE_TABLE":case"REMOVE_TABLE":case"UPDATE_TABLE":case"DELETE_CONTENT":this.tables={}}}finalize(){for(const e of this.getters.getSheetIds())this.tables[e]||(this.tables[e]=this.computeTables(e))}computeTables(e){const t=[],o=this.getters.getCoreTables(e);for(const e of o)"dynamic"!==e.type&&t.push(e);const s=[...t];for(const i of o){if("dynamic"!==i.type)continue;const o=this.coreTableToTable(e,i);let n=o.range.zone;for(const e of s)xr(n,e.range.zone)&&(n={...n,right:e.range.zone.left-1});t.push({...o,range:this.getters.getRangeFromZone(e,n)})}return t}getFilters(e){return this.getTables(e).filter((e=>e.config.hasFilters)).map((e=>e.filters)).flat()}getTables(e){return this.tables[e]||[]}getFilter(e){const t=this.getTable(e);if(t&&t.config.hasFilters)return t.filters.find((t=>t.col===e.col))}getFilterId(e){return this.getFilter(e)?.id}getTable({sheetId:e,col:t,row:o}){return this.getTables(e).find((e=>Er(t,o,e.range.zone)))}getTablesOverlappingZones(e,t){return this.getTables(e).filter((e=>t.some((t=>xr(e.range.zone,t)))))}doesZonesContainFilter(e,t){return this.getTablesOverlappingZones(e,t).some((e=>e.config.hasFilters))}getFilterHeaders(e){const t=[];for(const o of this.getTables(e)){if(!o.config.hasFilters)continue;const s=o.range.zone,i=s.top;for(let o=s.left;o<=s.right;o++)t.push({sheetId:e,col:o,row:i})}return t}isFilterHeader({sheetId:e,col:t,row:o}){return this.getFilterHeaders(e).some((e=>e.col===t&&e.row===o))}canCreateDynamicTableOnZones(e,t){if(!Ur(t))return!1;const o=yr(...t),s={col:o.left,row:o.top,sheetId:e},i=this.getters.getArrayFormulaSpreadingOn(s);if(!i)return!1;if(mt(i,s)&&1===Lr(o))return!0;return mt(o,this.getters.getSpreadZone(i))}coreTableToTable(e,t){if("dynamic"!==t.type)return t;const o=t.range.zone,s={sheetId:e,col:o.left,row:o.top},i=this.getters.getSpreadZone(s)??t.range.zone,n=this.getters.getRangeFromZone(e,i),r=this.getDynamicTableFilters(e,t,i);return{id:t.id,range:n,filters:r,config:t.config}}getDynamicTableFilters(e,t,o){const s=[],{top:i,bottom:n,left:r,right:a}=o;for(let o=r;o<=a;o++){const a=o-r,l={left:o,right:o,top:i,bottom:n},c=C_(this.getDynamicTableFilterId(t.id,a),this.getters.getRangeFromZone(e,l),t.config,this.getters.getRangeFromZone);s.push(c)}return s}getDynamicTableFilterId(e,t){return e+"_"+t}exportForExcel(e){for(const t of e.sheets)for(const e of t.tables){const o=ur(e.range),s={sheetId:t.id,col:o.left,row:o.top},i=this.getters.getCoreTable(s),n=this.getTable(s);"dynamic"===i?.type&&n&&(e.range=fr(n.range.zone))}}}).add("custom_colors",class extends $k{customColors={};shouldUpdateColors=!0;static getters=["getCustomColors"];constructor(e){super(e),this.tryToAddColors(e.customColors??[])}handle(e){switch(e.type){case"START":for(const e of this.getters.getSheetIds())for(const t of this.getters.getChartIds(e))this.tryToAddColors(this.getChartColors(t));break;case"UPDATE_CHART":case"CREATE_CHART":this.tryToAddColors(this.getChartColors(e.figureId));break;case"UPDATE_CELL":case"ADD_CONDITIONAL_FORMAT":case"SET_BORDER":case"SET_ZONE_BORDERS":case"SET_FORMATTING":case"CREATE_TABLE":case"UPDATE_TABLE":this.history.update("shouldUpdateColors",!0)}}finalize(){this.shouldUpdateColors&&(this.history.update("shouldUpdateColors",!1),this.tryToAddColors(this.computeCustomColors()))}getCustomColors(){return function(e){const t=[{leadColor:Zt(255,0,0),colors:[]},{leadColor:Zt(255,128,0),colors:[]},{leadColor:Zt(128,128,0),colors:[]},{leadColor:Zt(128,255,0),colors:[]},{leadColor:Zt(0,255,0),colors:[]},{leadColor:Zt(0,255,128),colors:[]},{leadColor:Zt(0,255,255),colors:[]},{leadColor:Zt(0,127,255),colors:[]},{leadColor:Zt(0,0,255),colors:[]},{leadColor:Zt(127,0,255),colors:[]},{leadColor:Zt(128,0,128),colors:[]},{leadColor:Zt(255,0,128),colors:[]}];for(const o of e.map(Xt)){let e=500,s=0;t.forEach(((t,i)=>{const n=(r=o,a=t.leadColor,Math.sqrt(Math.pow(r.r-a.r,2)+Math.pow(r.g-a.g,2)+Math.pow(r.b-a.b,2)));var r,a;e>n&&(e=n,s=i)})),t[s].colors.push(o)}return t.map((e=>e.colors.sort(((e,t)=>Jt(e).s-Jt(t).s)))).flat().map(Yt)}(Object.keys(this.customColors))}computeCustomColors(){let e=[];for(const t of this.getters.getSheetIds())e=e.concat(this.getColorsFromCells(t),this.getFormattingColors(t),this.getTableColors(t));return[...new Set([...e])]}getColorsFromCells(e){const t=Object.values(this.getters.getCells(e)),o=new Set;for(const e of t)e.style?.textColor&&o.add(e.style.textColor),e.style?.fillColor&&o.add(e.style.fillColor);for(const t of this.getters.getBordersColors(e))o.add(t);return[...o]}getFormattingColors(e){const t=this.getters.getConditionalFormats(e),o=[];for(const e of t){const t=e.rule;"CellIsRule"===t.type?(o.push(t.style.textColor),o.push(t.style.fillColor)):"ColorScaleRule"===t.type&&(o.push(zt(t.minimum.color)),o.push(t.midpoint?zt(t.midpoint.color):void 0),o.push(zt(t.maximum.color)))}return o.filter(lt)}getChartColors(e){const t=this.getters.getChart(e);if(void 0===t)return[];return[...JSON.stringify(t.getDefinition()).matchAll(EV)].map((e=>e[1]))}getTableColors(e){return this.getters.getTables(e).flatMap((e=>{const t=e.config,o=this.getters.getTableStyle(t.styleId);return[this.getTableStyleElementColors(o.wholeTable),t.numberOfHeaders>0?this.getTableStyleElementColors(o.headerRow):[],t.totalRow?this.getTableStyleElementColors(o.totalRow):[],t.bandedColumns?this.getTableStyleElementColors(o.firstColumnStripe):[],t.bandedColumns?this.getTableStyleElementColors(o.secondColumnStripe):[],t.bandedRows?this.getTableStyleElementColors(o.firstRowStripe):[],t.bandedRows?this.getTableStyleElementColors(o.secondRowStripe):[],t.firstColumn?this.getTableStyleElementColors(o.firstColumn):[],t.lastColumn?this.getTableStyleElementColors(o.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(lt):[]}tryToAddColors(e){for(const t of e){if(!Wt(t))continue;const e=Gt(t);t&&!ee.includes(e)&&this.history.update("customColors",e,!0)}}}).add("pivot_ui",class extends $k{static getters=["getPivot","getFirstPivotFunction","getPivotIdFromPosition","getPivotCellFromPosition","generateNewCalculatedMeasureName","isPivotUnused","isSpillPivotFormula"];pivots={};unusedPivots;custom;constructor(e){super(e),this.custom=e.custom}beforeHandle(e){if("START"===e.type)for(const e of this.getters.getPivotIds())this.setupPivot(e)}handle(e){if(Fs.has(e.type))for(const e of this.getters.getPivotIds())ik.get(this.getters.getPivotCoreDefinition(e).type).externalData||this.setupPivot(e,{recreate:!0});switch(e.type){case"REFRESH_PIVOT":this.refreshPivot(e.id);break;case"ADD_PIVOT":this.setupPivot(e.pivotId);break;case"DUPLICATE_PIVOT":this.setupPivot(e.newPivotId);break;case"UPDATE_PIVOT":this.setupPivot(e.pivotId,{recreate:!0});break;case"DELETE_SHEET":case"UPDATE_CELL":this.unusedPivots=void 0;break;case"UNDO":case"REDO":{this.unusedPivots=void 0;const t=e.commands.filter(FV);for(const e of t){const t=e.pivotId;this.getters.isExistingPivot(t)&&this.setupPivot(t,{recreate:!0})}break}case"UPDATE_LOCALE":!function(){for(const e in ok)ok[e].set.clear(),ok[e].values={}}()}}getPivotIdFromPosition(e){const t=this.getters.getCorrespondingFormulaCell(e);if(t&&t.isFormula){const o=this.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(o){const e=o.args[0]?.toString();return e&&this.getters.getPivotId(e)}}}isSpillPivotFormula(e){const t=this.getters.getCorrespondingFormulaCell(e);if(t&&t.isFormula){const o=this.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);return"PIVOT"===o?.functionName}return!1}getFirstPivotFunction(e,t){const o=BN(t);if(!o)return;const{functionName:s,args:i}=o;return{functionName:s,args:i.map((t=>{if("EMPTY"===t.type)return;if("STRING"===t.type||"BOOLEAN"===t.type||"NUMBER"===t.type)return t.value;const o=gv(t);return this.getters.evaluateFormula(e,o)}))}}getPivotCellFromPosition(e){const t=this.getters.getCorrespondingFormulaCell(e);if(!t||!t.isFormula||0===zN(t.compiledFormula.tokens))return ZN;const o=this.getters.getCellPosition(t.id),s=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(!s)return ZN;let{functionName:i,args:n}=s;const r=n[0];if(!r)return ZN;const a=this.getters.getPivotId(r.toString());if(!a)return ZN;const l=this.getPivot(a);if(!l.isValid())return ZN;if("PIVOT"===i&&!t.content.replaceAll(" ","").toUpperCase().startsWith("=PIVOT"))return ZN;if("PIVOT"===i){const t=ec(n[2]),s=void 0===t||Ei(t),i=ec(n[3]),r=ec(n[5]),a=void 0===r||Ei(r),c={displayColumnHeaders:void 0===i||Ei(i),displayTotals:s,displayMeasuresRow:a},h=l.getCollapsedTableStructure().getPivotCells(c),d=e.col-o.col,u=e.row-o.row;return h[d][u]}try{const t=e.row-o.row,s=e.col-o.col;if(n=n.map((e=>js(e)?e[s][t]:e)),"PIVOT.HEADER"===i&&"measure"===n.at(-2)){return{type:"MEASURE_HEADER",domain:l.parseArgsToPivotDomain(n.slice(1,-2).map((e=>({value:e})))),measure:n.at(-1)?.toString()||""}}if("PIVOT.HEADER"===i){const e=l.parseArgsToPivotDomain(n.slice(1).map((e=>({value:e}))));return{type:"HEADER",domain:e,dimension:NO(l,e).colDomain.length?"COL":"ROW"}}const[r,...a]=n.slice(1);return{type:"VALUE",domain:l.parseArgsToPivotDomain(a.map((e=>({value:e})))),measure:r?.toString()||""}}catch(e){return ZN}}generateNewCalculatedMeasureName(e){const t=e.map((e=>e.fieldName));return Vt(Ho("Calculated measure 1"),t,{compute:(e,t)=>Ho("Calculated measure %s",t)})}getPivot(e){if(!this.getters.isExistingPivot(e))throw new Error(`pivot ${e} not found`);return this.pivots[e]}isPivotUnused(e){return this._getUnusedPivots().includes(e)}refreshPivot(e){this.getters.getPivot(e).init({reload:!0})}setupPivot(e,{recreate:t}={recreate:!1}){const o=this.getters.getPivotCoreDefinition(e);if(e in this.pivots)t&&this.pivots[e].onDefinitionChange(o);else{const t=_V(ik.get(o.type).ui);this.pivots[e]=new t(this.custom,{definition:o,getters:this.getters})}}_getUnusedPivots(){if(void 0!==this.unusedPivots)return this.unusedPivots;const e=new Set(this.getters.getPivotIds());for(const t of this.getters.getSheetIds())for(const o in this.getters.getCells(t)){const t=this.getters.getCellPosition(o),s=this.getPivotIdFromPosition(t);if(s&&(e.delete(s),!e.size))return this.unusedPivots=[],[]}return this.unusedPivots=[...e],this.unusedPivots}}).add("cell_icon",class extends $k{static getters=["doesCellHaveGridIcon","getCellIcons","getCellIconRect"];cellIconsCache={};handle(e){"SET_VIEWPORT_OFFSET"!==e.type&&(this.cellIconsCache={})}getCellIcons(e){return this.cellIconsCache[e.sheetId]||(this.cellIconsCache[e.sheetId]={}),this.cellIconsCache[e.sheetId][e.col]||(this.cellIconsCache[e.sheetId][e.col]={}),this.cellIconsCache[e.sheetId][e.col][e.row]||(this.cellIconsCache[e.sheetId][e.col][e.row]=this.computeCellIcons(e)),this.cellIconsCache[e.sheetId][e.col][e.row]}getCellIconRect(e,t){const o=e.position,s=this.getters.getCell(o);return{x:this.getIconHorizontalPosition(t,e.horizontalAlign,e),y:this.getters.computeTextYCoordinate(t,e.size,s?.style?.verticalAlign),width:e.size,height:e.size}}getIconHorizontalPosition(e,t,o){const s=e.x,i=e.x+e.width;switch(t){case"right":return i-o.margin-o.size;case"left":return s+o.margin;default:const e=Math.floor((i-s-o.size)/2);return i-o.size-e}}computeCellIcons(e){const t={left:void 0,right:void 0,center:void 0},o=TV.getAll();for(const s of o){const o=s(this.getters,e);o&&(!t[o.horizontalAlign]||o.priority>t[o.horizontalAlign].priority)&&(t[o.horizontalAlign]=o)}if(t.center&&(t.left||t.right)){const e=Math.max(t.left?.priority||0,t.right?.priority||0);t.center.priority<e?t.center=void 0:(t.left=void 0,t.right=void 0)}return Object.values(t).filter(lt)}doesCellHaveGridIcon(e){return Boolean(this.getCellIcons(e).length)}});mE.add("dataValidation",{displayAllOnInitialContent:!0,canBeToggled:!1,getProposals(e,t){if(Lt(t))return[];if(!this.composer.currentEditedCell)return[];const o=this.composer.currentEditedCell,s=this.getters.getValidationRuleForCell(o);if(!s||"isValueInList"!==s.criterion.type&&"isValueInRange"!==s.criterion.type)return[];const i=this.composer.currentEditedCell.sheetId,n="isValueInRange"===s.criterion.type?this.getters.getDataValidationRangeValues(i,s.criterion):s.criterion.values.map((e=>({label:e,value:e})));if(!("chip"===s.criterion.displayStyle))return n.map((e=>({text:e.value,fuzzySearchKey:e.label,htmlContent:[{value:e.label}]})));const r=s.criterion.colors;return n.map((e=>{const t=r?.[e.value];return{text:e.value,htmlContent:[{value:e.label,color:t?no(t):void 0,backgroundColor:t||F,classes:["badge rounded-pill fs-6 fw-normal w-100 mt-1 text-start"]}],fuzzySearchKey:e.label}}))},selectProposal(e,t){this.composer.setCurrentContent(t),this.composer.stopEdition()}}),mE.add("functions",{sequence:100,autoSelectFirstProposal:!0,maxDisplayedProposals:10,getProposals(e){if("SYMBOL"!==e.type)return[];const t=e.value;if(!Lt(this.composer.currentContent))return[];const o=Object.entries(RS.content).filter((([e,{hidden:t}])=>!t)).map((([e,{description:o}])=>({text:e,description:o,htmlContent:EN(t,e,E,"o-semi-bold")}))).sort(((e,t)=>e.text.length-t.text.length||e.text.localeCompare(t.text)));return o},selectProposal(e,t){let o=e.end,s=e.end;["SYMBOL","FUNCTION"].includes(e.type)&&(o=e.start);const i=this.composer.currentTokens;t+="(";const n=i.map((e=>e.start)).indexOf(e.start);if(n+1<i.length){const e=i[n+1];"LEFT_PAREN"===e?.type&&s++}this.composer.changeComposerCursorSelection(o,s),this.composer.replaceComposerCursorSelection(t)}}),mE.add("pivot_ids",{sequence:50,autoSelectFirstProposal:!0,getProposals(e){const t=e.functionContext;if(!t||!["PIVOT.VALUE","PIVOT.HEADER","PIVOT"].includes(t.parent.toUpperCase())||0!==t.argPosition)return;const o=this.getters.getPivotIds();return o.includes(e.value)?void 0:o.map((e=>{const t=this.getters.getPivotCoreDefinition(e),o=`${this.getters.getPivotFormulaId(e)}`;return{text:o,description:t.name,htmlContent:[{value:o,color:wE.NUMBER}],fuzzySearchKey:o+t.name,alwaysExpanded:!0}})).filter(lt)},selectProposal:HN}),mE.add("pivot_measures",{sequence:50,autoSelectFirstProposal:!0,getProposals(e){const t=e.functionContext;if("PIVOT.VALUE"!==t?.parent.toUpperCase()||1!==t.argPosition)return[];const o=UN(e),s=this.getters.getPivotId(o);if(!s||!this.getters.isExistingPivot(s))return[];const i=this.getters.getPivot(s);return i.init(),i.isValid()?i.definition.measures.map((e=>{if("__count"===e.fieldName){const e='"__count"';return{text:e,description:Ho("Count"),htmlContent:[{value:e,color:wE.STRING}],fuzzySearchKey:Ho("Count")+e}}return function(e){const t=`"${e.id}"`,o=e.displayName+e.fieldName+t;return{text:t,description:e.displayName,htmlContent:[{value:t,color:wE.STRING}],fuzzySearchKey:o}}(e)})).filter(lt):[]},selectProposal:LN}),mE.add("pivot_group_fields",{sequence:50,autoSelectFirstProposal:!0,getProposals(e){const t=e.functionContext;if(!t||!function(e){const t=e.functionContext;return"PIVOT.VALUE"===t?.parent.toUpperCase()&&t.argPosition>=2&&t.argPosition%2==0}(e)&&!function(e){const t=e.functionContext;return"PIVOT.HEADER"===t?.parent.toUpperCase()&&t.argPosition>=1&&t.argPosition%2==1}(e))return;const o=UN(e),s=this.getters.getPivotId(o);if(!s||!this.getters.isExistingPivot(s))return;const i=this.getters.getPivot(s);i.init();const n=i.getFields(),{columns:r,rows:a}=i.definition;let l=t.args;"PIVOT.VALUE"===t?.parent.toUpperCase()?(l=l.filter(((e,t)=>t%2==0)),l=l.slice(1,t.argPosition)):l=l.filter(((e,t)=>t%2==1));const c=l.map((e=>e?.value)).filter(lt),h=r.map((e=>e.nameWithGranularity)),d=a.map((e=>e.nameWithGranularity)),u=[];let g=["ARG_SEPARATOR","SPACE"].includes(e.type)?c.at(-1):c.at(-2);const p=Ok.get(i.type);if(p&&g?.startsWith("#")&&(g=g.slice(1)),void 0===g&&(u.push(h[0]),u.push(d[0])),d.includes(g)){const e=d[d.indexOf(g)+1];u.push(e),u.push(h[0])}if(h.includes(g)){const e=h[h.indexOf(g)+1];u.push(e)}const m=u.filter(lt);return m.map((e=>{const[t,o]=e.split(":"),s=n[t];return s?VN(s,o):void 0})).concat(m.map((e=>{if(!p)return;const t=e.split(":")[0],o=n[t];if(!o)return;const s=`"#${e}"`;return{text:s,description:Ho("%s (positional)",o.string)+(o.help?` (${o.help})`:""),htmlContent:[{value:s,color:wE.STRING}],fuzzySearchKey:o.string+s}}))).filter(lt)},selectProposal:LN}),mE.add("pivot_group_values",{sequence:50,autoSelectFirstProposal:!0,getProposals(e){const t=e.functionContext;if(!t||!e||!function(e){const t=e.functionContext;return"PIVOT.VALUE"===t?.parent.toUpperCase()&&t.argPosition>=2&&t.argPosition%2==1}(e)&&!function(e){const t=e.functionContext;return"PIVOT.HEADER"===t?.parent.toUpperCase()&&t.argPosition>=1&&t.argPosition%2==0}(e))return;const o=UN(e),s=this.getters.getPivotId(o);if(!s||!this.getters.isExistingPivot(s))return;const i=this.getters.getPivot(s);if(!i.isValid())return;const n=t.argPosition,r=e.functionContext?.args[n-1]?.value;if(!r)return;let a;try{a=i.definition.getDimension(r)}catch(e){return}return"month_number"===a.granularity?Object.values(yn).map(((e,t)=>({text:`${t+1}`,fuzzySearchKey:e.toString(),description:e.toString(),htmlContent:[{value:`${t+1}`,color:wE.NUMBER}]}))):"quarter_number"===a.granularity?[1,2,3,4].map((e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:Ho("Quarter %s",e),htmlContent:[{value:`${e}`,color:wE.NUMBER}]}))):"day_of_month"===a.granularity?je(1,32).map((e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:wE.NUMBER}]}))):"iso_week_number"===a.granularity?je(0,54).map((e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:wE.NUMBER}]}))):"day_of_week"===a.granularity?je(1,8).map((e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:wE.NUMBER}]}))):"hour_number"===a.granularity?je(0,24).map((e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:wE.NUMBER}]}))):"minute_number"===a.granularity?je(0,60).map((e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:wE.NUMBER}]}))):"second_number"===a.granularity?je(0,60).map((e=>({text:`${e}`,fuzzySearchKey:`${e}`,description:"",htmlContent:[{value:`${e}`,color:wE.NUMBER}]}))):i.getPossibleFieldValues(a).map((({value:e,label:t})=>{const o="string"==typeof e,s=o?`"${e}"`:e.toString(),i=t===e?"":t;return{text:s,description:i,htmlContent:[{value:s,color:o?wE.STRING:wE.NUMBER}],fuzzySearchKey:s+i}}))},selectProposal:LN}),mE.add("sheet_names",{sequence:150,autoSelectFirstProposal:!0,getProposals(e){return"SYMBOL"===e.type||"UNKNOWN"===e.type&&e.value.startsWith("'")?this.getters.getSheetIds().map((e=>{const t=We(this.getters.getSheetName(e));return{text:t,fuzzySearchKey:t.startsWith("'")?t:"'"+t}})):[]},selectProposal(e,t){const o=e.start,s=e.end;this.composer.changeComposerCursorSelection(o,s),this.composer.replaceComposerCursorSelection(t+"!")}});const AL=new n;AL.add("link",{condition:(e,t)=>!!t.getEvaluatedCell(e).link,execute:(e,t,o)=>Zo(t.model.getters.getEvaluatedCell(e).link,t,o),title:(e,t)=>{const o=t.getEvaluatedCell(e).link;return o?o.isExternal?Ho("Go to url: %(url)s",{url:o.url}):Ho("Go to %(label)s",{label:o.label}):""},sequence:5});const DL=(new n).add("ADD_COLUMNS_ROWS",(function(e){const t=[];let o=e.base;"after"===e.position&&o++;for(let s=0;s<e.quantity;s++)t.push(s+o);return[{type:"REMOVE_COLUMNS_ROWS",dimension:e.dimension,elements:t,sheetId:e.sheetId,sheetName:e.sheetName}]})).add("REMOVE_COLUMNS_ROWS",(function(e){const t=[],o=[...e.elements].sort(((e,t)=>e-t));for(const s of Ye(o)){const o=0===s[0]?0:s[0]-1,i=0===s[0]?"before":"after";t.push({type:"ADD_COLUMNS_ROWS",dimension:e.dimension,quantity:s.length,base:o,sheetId:e.sheetId,sheetName:e.sheetName,position:i})}return t})).add("ADD_MERGE",(function(e){return[{type:"REMOVE_MERGE",sheetId:e.sheetId,target:e.target}]})).add("REMOVE_MERGE",(function(e){return[{type:"ADD_MERGE",sheetId:e.sheetId,target:e.target}]})).add("CREATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetId,sheetName:e.name}]})).add("DELETE_SHEET",(function(e){return[{type:"CREATE_SHEET",sheetId:e.sheetId,position:1,name:e.sheetName}]})).add("DUPLICATE_SHEET",(function(e){return[{type:"DELETE_SHEET",sheetId:e.sheetIdTo,sheetName:""}]})).add("CREATE_FIGURE",(function(e){return[{type:"DELETE_FIGURE",figureId:e.figureId,sheetId:e.sheetId}]})).add("CREATE_CHART",(function(e){return[{type:"DELETE_FIGURE",figureId:e.figureId,sheetId:e.sheetId}]})).add("HIDE_COLUMNS_ROWS",(function(e){return[{type:"UNHIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]})).add("UNHIDE_COLUMNS_ROWS",(function(e){return[{type:"HIDE_COLUMNS_ROWS",sheetId:e.sheetId,dimension:e.dimension,elements:e.elements}]})).add("CREATE_TABLE_STYLE",(function(e){return[{type:"REMOVE_TABLE_STYLE",tableStyleId:e.tableStyleId}]})).add("ADD_PIVOT",(function(e){return[{type:"REMOVE_PIVOT",pivotId:e.pivotId}]})).add("RENAME_SHEET",(function(e){return[{type:"RENAME_SHEET",sheetId:e.sheetId,oldName:e.newName,newName:e.oldName}]}));for(const e of Ls.values())DL.contains(e)||DL.add(e,_L);function _L(e){return[e]}const OL=new n;OL.add("format_number_automatic",{...pF,id:"format_number_automatic",sequence:10}).add("format_number_plain_text",{...mF,id:"format_number_plain_text",sequence:15,separator:!0}).add("format_number_number",{...fF,id:"format_number_number",sequence:20}).add("format_number_percent",{...bF,id:"format_number_percent",sequence:30,separator:!0}).add("format_number_currency",{...SF,id:"format_number_currency",sequence:40}).add("format_number_accounting",{...yF,id:"format_number_accounting",sequence:45}).add("format_number_currency_rounded",{...CF,id:"format_number_currency_rounded",sequence:50}).add("format_custom_currency",{...IF,id:"format_custom_currency",sequence:60,separator:!0}).add("format_number_date",{...xF,id:"format_number_date",sequence:70}).add("format_number_time",{...EF,id:"format_number_time",sequence:80}).add("format_number_date_time",{...RF,id:"format_number_date_time",sequence:90}).add("format_number_duration",{...TF,id:"format_number_duration",sequence:100,separator:!0}).add("more_formats",{..._F,id:"more_formats",sequence:120});const FL=Et((e=>On(e)?"date":e.includes("[$")?"currency":"number")),PL={name:Ho("More formats"),icon:"o-spreadsheet-Icon.NUMBER_FORMATS",children:[e=>{const t=function(e){const t=new Set(OL.getAll().map((t=>"function"==typeof t.format?t.format(e):t.format))),o=new Map;for(const s of e.model.getters.getSheetIds()){const i=e.model.getters.getEvaluatedCells(s);for(const e in i){const s=i[e];if(s.format&&!o.has(s.format)&&!t.has(s.format)){const e=FL(s.format);"date"!==e&&"currency"!==e||o.set(s.format,gF({descriptionValue:"currency"===e?1e3:wF,format:s.format,name:s.format}))}}}return[...o.values()]}(e).map((e=>({...e,sequence:110})));return t.length>0&&(t[t.length-1].separator=!0),o([...OL.getAll(),...t])}]};const ML=new vR;ML.add("file",{name:Ho("File"),sequence:10}).addChild("settings",["file"],{name:Ho("Settings"),sequence:200,execute:e=>e.openSidePanel("Settings"),isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.COG"}).add("edit",{name:Ho("Edit"),sequence:20}).addChild("undo",["edit"],{...__,sequence:10}).addChild("redo",["edit"],{...O_,sequence:20,separator:!0}).addChild("copy",["edit"],{...F_,sequence:30}).addChild("cut",["edit"],{...P_,sequence:40}).addChild("paste",["edit"],{...M_,sequence:50}).addChild("paste_special",["edit"],{...N_,sequence:60,separator:!0}).addChild("paste_special_value",["edit","paste_special"],{...k_,sequence:10}).addChild("paste_special_format",["edit","paste_special"],{...V_,sequence:20}).addChild("edit_table",["edit"],{...X_,isVisible:VD,sequence:60}).addChild("find_and_replace",["edit"],{...L_,sequence:65,separator:!0}).addChild("delete",["edit"],{name:Ho("Delete"),icon:"o-spreadsheet-Icon.TRASH",sequence:70}).addChild("edit_delete_cell_values",["edit","delete"],{...H_,sequence:10}).addChild("edit_delete_row",["edit","delete"],{...U_,sequence:20}).addChild("edit_delete_column",["edit","delete"],{...$_,sequence:30}).addChild("edit_delete_cell_shift_up",["edit","delete"],{...Z_,sequence:40}).addChild("edit_delete_cell_shift_left",["edit","delete"],{...j_,sequence:50}).addChild("edit_unhide_columns",["edit"],{...jD,sequence:80}).addChild("edit_unhide_rows",["edit"],{...KD,sequence:80}).add("view",{name:Ho("View"),sequence:30}).addChild("unfreeze_panes",["view"],{...JD,sequence:4}).addChild("freeze_panes",["view"],{...QD,sequence:5}).addChild("unfreeze_rows",["view","freeze_panes"],{...e_,sequence:5}).addChild("freeze_first_row",["view","freeze_panes"],{...t_,sequence:10}).addChild("freeze_second_row",["view","freeze_panes"],{...o_,sequence:15}).addChild("freeze_current_row",["view","freeze_panes"],{...s_,sequence:20,separator:!0}).addChild("unfreeze_columns",["view","freeze_panes"],{...i_,sequence:25}).addChild("freeze_first_col",["view","freeze_panes"],{...n_,sequence:30}).addChild("freeze_second_col",["view","freeze_panes"],{...r_,sequence:35}).addChild("freeze_current_col",["view","freeze_panes"],{...a_,sequence:40}).addChild("group_headers",["view"],{name:Ho("Group"),sequence:15,separator:!0,icon:"o-spreadsheet-Icon.PLUS_IN_BOX",isVisible:HD}).addChild("group_columns",["view","group_headers"],{...d_,sequence:5}).addChild("ungroup_columns",["view","group_headers"],{...g_,isVisible:e=>v_(e,"COL"),sequence:10}).addChild("group_rows",["view","group_headers"],{...u_,sequence:15}).addChild("ungroup_rows",["view","group_headers"],{...p_,isVisible:e=>v_(e,"ROW"),sequence:20}).addChild("show",["view"],{name:Ho("Show"),sequence:1,icon:"o-spreadsheet-Icon.SHOW"}).addChild("view_gridlines",["view","show"],{...l_,sequence:5}).addChild("view_formulas",["view","show"],{...h_,sequence:10}).addChild("view_irregularity_map",["view"],{...c_,sequence:40,separator:!0}).add("insert",{name:Ho("Insert"),sequence:40}).addChild("insert_row",["insert"],{...eO,sequence:10}).addChild("insert_row_before",["insert","insert_row"],{...oO,sequence:10}).addChild("insert_row_after",["insert","insert_row"],{...nO,sequence:20}).addChild("insert_column",["insert"],{...rO,sequence:20}).addChild("insert_column_before",["insert","insert_column"],{...lO,sequence:10}).addChild("insert_column_after",["insert","insert_column"],{...dO,sequence:20}).addChild("insert_cell",["insert"],{...uO,sequence:30}).addChild("insert_cell_down",["insert","insert_cell"],{...gO,name:Ho("Shift down"),sequence:10}).addChild("insert_cell_right",["insert","insert_cell"],{...pO,name:Ho("Shift right"),sequence:20}).addChild("insert_sheet",["insert"],{...DO,sequence:40,separator:!0}).addChild("insert_chart",["insert"],{...mO,sequence:50}).addChild("insert_pivot",["insert"],{...fO,sequence:52}).addChild("insert_image",["insert"],{...vO,sequence:55}).addChild("insert_table",["insert"],{...bO,sequence:57}).addChild("insert_function",["insert"],{...SO,sequence:60}).addChild("insert_function_sum",["insert","insert_function"],{...CO,sequence:0}).addChild("insert_function_average",["insert","insert_function"],{...yO,sequence:10}).addChild("insert_function_count",["insert","insert_function"],{...wO,sequence:20}).addChild("insert_function_max",["insert","insert_function"],{...IO,sequence:30}).addChild("insert_function_min",["insert","insert_function"],{...xO,sequence:40,separator:!0}).addChild("categorie_function_all",["insert","insert_function"],{...EO,sequence:50}).addChild("categories_function_list",["insert","insert_function"],(()=>{const e=RS.content;return[...new Set(RS.getAll().filter((e=>!e.hidden)).map((e=>e.category)))].filter(lt).sort().map(((t,o)=>{const s=Object.keys(e).filter((o=>e[o].category===t&&!e[o].hidden));return{name:t,children:_O(s)}}))})).addChild("insert_link",["insert"],{...RO,separator:!0,sequence:70}).addChild("insert_checkbox",["insert"],{...TO,sequence:80}).addChild("insert_dropdown",["insert"],{...AO,separator:!0,sequence:90}).add("format",{name:Ho("Format"),sequence:50}).addChild("format_number",["format"],{...PL,name:Ho("Number"),sequence:10,separator:!0}).addChild("format_bold",["format"],{...zF,sequence:20}).addChild("format_italic",["format"],{...$F,sequence:30}).addChild("format_underline",["format"],{...GF,sequence:40}).addChild("format_strikethrough",["format"],{...WF,sequence:50,separator:!0}).addChild("format_font_size",["format"],{...qF,sequence:60,separator:!0}).addChild("format_alignment",["format"],{...ZF,sequence:70}).addChild("format_alignment_left",["format","format_alignment"],{...YF,sequence:10}).addChild("format_alignment_center",["format","format_alignment"],{...XF,sequence:20}).addChild("format_alignment_right",["format","format_alignment"],{...KF,sequence:30,separator:!0}).addChild("format_alignment_top",["format","format_alignment"],{...QF,sequence:40}).addChild("format_alignment_middle",["format","format_alignment"],{...eP,sequence:50}).addChild("format_alignment_bottom",["format","format_alignment"],{...tP,sequence:60,separator:!0}).addChild("format_wrapping",["format"],{...oP,sequence:80,separator:!0}).addChild("format_wrapping_overflow",["format","format_wrapping"],{...iP,sequence:10}).addChild("format_wrapping_wrap",["format","format_wrapping"],{...nP,sequence:20}).addChild("format_wrapping_clip",["format","format_wrapping"],{...rP,sequence:30}).addChild("format_cf",["format"],{...aP,sequence:90,separator:!0}).addChild("format_clearFormat",["format"],{...lP,sequence:100,separator:!0}).add("data",{name:Ho("Data"),sequence:60}).addChild("sort_range",["data"],{...oF,sequence:10,separator:!0}).addChild("sort_ascending",["data","sort_range"],{...sF,sequence:10}).addChild("sort_descending",["data","sort_range"],{...aF,sequence:20}).addChild("data_cleanup",["data"],{...iF,sequence:15}).addChild("remove_duplicates",["data","data_cleanup"],{...nF,sequence:10}).addChild("trim_whitespace",["data","data_cleanup"],{...rF,sequence:20}).addChild("split_to_columns",["data"],{...hF,sequence:20}).addChild("data_validation",["data"],{name:Ho("Data Validation"),execute:e=>{e.openSidePanel("DataValidation")},isEnabled:e=>!e.isSmall,icon:"o-spreadsheet-Icon.DATA_VALIDATION",sequence:30,separator:!0}).addChild("add_remove_data_filter",["data"],{...lF,sequence:40,separator:!0}).addChild("pivot_data_sources",["data"],(e=>{const t=e.model.getters.getPivotIds().length;return e.model.getters.getPivotIds().map(((o,s)=>{const i={get highlights(){return wN(e.model.getters,o)}};return{id:`item_pivot_${e.model.getters.getPivotFormulaId(o)}`,name:e.model.getters.getPivotDisplayName(o),sequence:50+s/t,isReadonlyAllowed:!0,execute:e=>e.openSidePanel("PivotSidePanel",{pivotId:o}),isEnabled:e=>!e.isSmall,onStartHover:e=>e.getStore(vE).register(i),onStopHover:e=>e.getStore(vE).unRegister(i),icon:"o-spreadsheet-Icon.PIVOT",separator:s===e.model.getters.getPivotIds().length-1,secondaryIcon:e=>e.model.getters.isPivotUnused(o)?"o-spreadsheet-Icon.UNUSED_PIVOT_WARNING":void 0}}))})).addChild("reinsert_dynamic_pivot",["data"],dF).addChild("reinsert_static_pivot",["data"],uF);const NL=new class extends n{mapping={};uuidGenerator=new Ka;replace(e,t){const o={...t,id:this.uuidGenerator.uuidv4()};return super.replace(e,o)}getAllOrdered(){return this.getAll().sort(((e,t)=>e.sequence-t.sequence))}};class kL{listeners=[];async sendMessage(e){for(const{callback:t}of this.listeners)t(e)}onNewMessage(e,t){this.listeners.push({id:e,callback:t})}leave(e){this.listeners=this.listeners.filter((t=>t.id!==e))}}class VL{fileStore;constructor(e){this.fileStore=e}async requestImage(){const e=await this.userImageUpload(),t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}async uploadFile(e){const t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}userImageUpload(){return new Promise(((e,t)=>{const o=document.createElement("input");o.setAttribute("type","file"),o.setAttribute("accept","image/*"),o.addEventListener("change",(async()=>{null===o.files||1!==o.files.length?t():e(o.files[0])})),o.click()}))}getImageOriginalSize(e){return new Promise(((t,o)=>{const s=new Image;s.addEventListener("load",(()=>{const e={width:s.width,height:s.height};t(e)})),s.addEventListener("error",o),s.src=e}))}}const LL=[{transform:"scale(0)"},{transform:"scale(0.8)",offset:.33},{opacity:"0",transform:"scale(1)",offset:1}];yh`
|
|
1875
1875
|
.o-ripple {
|
|
1876
1876
|
z-index: 1;
|
|
1877
1877
|
}
|
|
@@ -3340,4 +3340,4 @@
|
|
|
3340
3340
|
<tableParts count="${e.tables.length}">
|
|
3341
3341
|
${Ix(a)}
|
|
3342
3342
|
</tableParts>
|
|
3343
|
-
`}var FU;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(FU||(FU={}));function PU(e,t={}){const o=ze(t);return o.type=e,o}const MU={},NU={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:te,HEADER_WIDTH:oe,DESKTOP_BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:se,DEFAULT_CELL_HEIGHT:ie,SCROLLBAR_WIDTH:ne},kU={autoCompleteProviders:mE,autofillModifiersRegistry:PV,autofillRulesRegistry:MV,cellMenuRegistry:tF,colMenuRegistry:gP,errorTypes:oi,linkMenuRegistry:bR,functionRegistry:RS,featurePluginRegistry:EL,iconsOnCellRegistry:TV,statefulUIPluginRegistry:RL,coreViewsPluginRegistry:TL,corePluginRegistry:xL,rowMenuRegistry:SP,sidePanelRegistry:wk,figureRegistry:Gx,chartSidePanelComponentRegistry:JM,chartComponentRegistry:ix,chartRegistry:sx,chartSubtypeRegistry:rx,topbarMenuRegistry:ML,topbarComponentRegistry:NL,clickableCellRegistry:AL,otRegistry:$V,inverseCommandRegistry:DL,urlRegistry:zo,cellPopoverRegistry:Zx,numberFormatMenuRegistry:OL,repeatLocalCommandTransformRegistry:vL,repeatCommandTransformRegistry:fL,clipboardHandlersRegistries:eh,pivotRegistry:ik,pivotTimeAdapterRegistry:vc,pivotSidePanelRegistry:lk,pivotNormalizationValueRegistry:jc,supportedPivotPositionalFormulaRegistry:Ok,pivotToFunctionValueRegistry:Yc,migrationStepRegistry:lD,chartJsExtensionRegistry:Eh},VU={arg:Qh,isEvaluationError:gi,toBoolean:Ei,toJsDate:Ri,toNumber:fi,toString:wi,toNormalizedPivotValue:Gc,toFunctionPivotValue:qc,toXC:Po,toZone:ur,toUnboundedZone:dr,toCartesian:Fo,numberToLetters:wo,lettersToNumber:Io,UuidGenerator:Ka,formatValue:In,createCurrencyFormat:Vn,ColorGenerator:fo,computeTextWidth:Va,createEmptyWorkbookData:SD,createEmptySheet:bD,createEmptyExcelSheet:CD,rgbaToHex:Yt,colorToRGBA:Xt,positionToZone:Mr,isDefined:lt,isMatrix:js,lazy:ut,genericRepeat:bL,createAction:i,createActions:o,transformRangeData:oh,deepEquals:mt,overlap:xr,union:yr,isInside:Er,deepCopy:ze,expandZoneOnInsertion:vr,reduceZoneOnDeletion:Cr,unquote:Ge,getMaxObjectId:kc,getFunctionsFromTokens:GS,getFirstPivotFunction:BN,getNumberOfPivotFunctions:zN,parseDimension:Hc,isDateOrDatetimeField:Uc,makeFieldProposal:VN,insertTokenAfterArgSeparator:LN,insertTokenAfterLeftParenthesis:HN,mergeContiguousZones:Br,getPivotHighlights:wN,pivotTimeAdapter:bc,UNDO_REDO_PIVOT_COMMANDS:OV,createPivotFormula:$c,areDomainArgsFieldsValid:zc,splitReference:ra,sanitizeSheetName:qe,getUniqueText:Vt,isNumber:Rs,isDateTime:cs},LU={isMarkdownLink:et,parseMarkdownLink:st,markdownLink:ot,openLink:Zo,urlRepresentation:qo},HU={Checkbox:oR,Section:BE,RoundColorPicker:zE,ChartDataSeries:cM,ChartErrorSection:hM,ChartLabelRange:dM,ChartTitle:SM,ChartPanel:tN,ChartFigure:zx,ChartJsComponent:jC,Grid:_k,GridOverlay:GP,ScorecardChart:cy,LineConfigPanel:LM,BarConfigPanel:gM,PieChartDesignPanel:BM,GenericChartConfigPanel:uM,ChartWithAxisDesignPanel:TM,LineChartDesignPanel:HM,GaugeChartConfigPanel:OM,GaugeChartDesignPanel:FM,ScorecardChartConfigPanel:$M,ScorecardChartDesignPanel:GM,GeoChartDesignPanel:kM,RadarChartDesignPanel:zM,WaterfallChartDesignPanel:KM,ComboChartDesignPanel:DM,FunnelChartDesignPanel:_M,ChartTypePicker:QM,FigureComponent:Wx,MenuPopover:Ux,Popover:kx,SelectionInput:XE,ValidationMessages:kP,AddDimensionButton:RN,PivotDimensionGranularity:_N,PivotDimensionOrder:ON,PivotDimension:DN,PivotLayoutConfigurator:MN,PivotHTMLRenderer:Pk,PivotDeferUpdate:IN,PivotTitleSection:NN,CogWheelMenu:AN,TextInput:TN,SidePanelCollapsible:Jx,RadioSelection:yM,GeoChartRegionSelectSection:PM,ChartDashboardMenu:Bx,FullScreenChart:Fk},UU={useDragAndDropListItems:$E,useHighlights:iN,useHighlightsOnHover:sN},BU={useStoreProvider:ah,DependencyContainer:ih,CellPopoverStore:jx,ComposerFocusStore:bh,CellComposerStore:AP,FindAndReplaceStore:fN,HighlightStore:vE,DelayedHoveredCellStore:qx,HoveredTableStore:BP,ModelStore:gh,NotificationStore:bE,RendererStore:mh,SelectionInputStore:YE,SpreadsheetStore:fh,useStore:lh,useLocalStore:ch,SidePanelStore:Rk,PivotSidePanelStore:rk,PivotMeasureDisplayPanelStore:CN,ClientFocusStore:yP,GridRenderer:JP};const zU={DEFAULT_LOCALE:qs,HIGHLIGHT_COLOR:a,PIVOT_TABLE_CONFIG:Ve,ChartTerms:Yy},$U={...ux,...xI};e.AbstractCellClipboardHandler=rl,e.AbstractChart=YC,e.AbstractFigureClipboardHandler=Qc,e.CellErrorType=ti,e.ClientDisconnectedError=sL,e.CorePlugin=Nk,e.CoreViewPlugin=$k,e.DispatchResult=Us,e.EvaluationError=si,e.LocalTransportService=kL,e.Model=class extends sh{corePlugins=[];statefulUIPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;coreViewPluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},o={},s=[],i=new Ka,n=!1){const r=performance.now();console.debug("##### Model creation #####"),super(),ko===Mo&&Vo===No&&(Vo=()=>!0),s=fD(e,s);const a=gD(e,n);this.state=new _H,this.uuidGenerator=i,this.config=this.setupConfig(o),this.session=this.setupSession(a.revisionId),this.coreGetters={},this.range=new Bk(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.coreGetters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.coreGetters.getRangeData=this.range.getRangeData.bind(this.range),this.coreGetters.getRangeDataFromXc=this.range.getRangeDataFromXc.bind(this.range),this.coreGetters.getRangeDataFromZone=this.range.getRangeDataFromZone.bind(this.range),this.coreGetters.getRangeFromRangeData=this.range.getRangeFromRangeData.bind(this.range),this.coreGetters.getRangeFromZone=this.range.getRangeFromZone.bind(this.range),this.coreGetters.recomputeRanges=this.range.recomputeRanges.bind(this.range),this.coreGetters.isRangeValid=this.range.isRangeValid.bind(this.range),this.coreGetters.extendRange=this.range.extendRange.bind(this.range),this.coreGetters.getRangesUnion=this.range.getRangesUnion.bind(this.range),this.coreGetters.removeRangesSheetPrefix=this.range.removeRangesSheetPrefix.bind(this.range),this.coreGetters.adaptFormulaStringDependencies=this.range.adaptFormulaStringDependencies.bind(this.range),this.coreGetters.copyFormulaStringForSheet=this.range.copyFormulaStringForSheet.bind(this.range),this.getters={isReadonly:()=>"readonly"===this.config.mode||"dashboard"===this.config.mode,isDashboard:()=>"dashboard"===this.config.mode},this.selection=new AH(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.coreViewPluginConfig=this.setupCoreViewPluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(const e of xL.getAll())this.setupCorePlugin(e,a);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(s);for(const e of TL.getAll()){const t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(const e of RL.getAll()){const t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(const e of EL.getAll()){const t=this.setupUiPlugin(e);this.handlers.push(t),this.uiHandlers.push(t)}if(this.dispatch("START"),this.selection.observe(this,{handleEvent:()=>this.trigger("update")}),this.setupSessionEvents(),this.joinSession(),o.snapshotRequested||e["[Content_Types].xml"]&&!this.getters.isReadonly()){const e=performance.now();console.debug("Snapshot requested"),this.session.snapshot(this.exportData()),this.garbageCollectExternalResources(),console.debug("Snapshot taken in",performance.now()-e,"ms")}t.markRaw(this),console.debug("Model created in",performance.now()-r,"ms"),console.debug("######")}joinSession(){this.session.join(this.config.client)}async leaveSession(){const e=this.getters.isReadonly()?void 0:ut((()=>this.exportData()));await this.session.leave(e)}setupUiPlugin(e){const t=new e(this.uiPluginConfig);for(const o of e.getters){if(!(o in t))throw new Error(`Invalid getter name: ${o} for plugin ${t.constructor}`);if(o in this.getters)throw new Error(`Getter "${o}" is already defined.`);this.getters[o]=t[o].bind(t)}for(const o of e.layers)this.renderers[o]||(this.renderers[o]=[]),this.renderers[o].push(t);return t}setupCoreViewPlugin(e){const t=new e(this.coreViewPluginConfig);for(const o of e.getters){if(!(o in t))throw new Error(`Invalid getter name: ${o} for plugin ${t.constructor}`);if(o in this.getters)throw new Error(`Getter "${o}" is already defined.`);this.getters[o]=t[o].bind(t)}return t}setupCorePlugin(e,t){const o=new e(this.corePluginConfig);for(const t of e.getters){if(!(t in o))throw new Error(`Invalid getter name: ${t} for plugin ${o.constructor}`);if(t in this.coreGetters)throw new Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=o[t].bind(o)}o.import(t),this.corePlugins.push(o),this.coreHandlers.push(o),this.handlers.push(o)}onRemoteRevisionReceived({commands:e}){for(const t of e){const e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new iL(EH({initialRevisionId:e,recordChanges:this.state.recordChanges.bind(this.state),dispatch:e=>{this.checkDispatchAllowed(e).isSuccessful?(this.isReplayingCommand=!0,this.dispatchToHandlers(this.coreHandlers,e),this.isReplayingCommand=!1):this.dispatchToHandlers(this.coreHandlers,{type:"UNDO",commands:[e]})}}),this.config.transportService,e)}setupSessionEvents(){this.session.on("remote-revision-received",this,this.onRemoteRevisionReceived),this.session.on("revision-undone",this,(({commands:e})=>{this.dispatchFromCorePlugin("UNDO",{commands:e}),this.finalize()})),this.session.on("revision-redone",this,(({commands:e})=>{this.dispatchFromCorePlugin("REDO",{commands:e}),this.finalize()})),this.session.on("unexpected-revision-id",this,(()=>this.trigger("unexpected-revision-id"))),this.session.on("collaborative-event-received",this,(()=>{this.trigger("update")}))}setupConfig(e){const t=e.client||{id:this.uuidGenerator.smallUuid(),name:Ho("Anonymous").toString()},o=e.transportService||new kL;return{...e,mode:e.mode||"normal",custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:o,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger("notify-ui",e),raiseBlockingErrorUI:e=>this.trigger("raise-error-ui",{text:e}),customColors:e.customColors||[]}}setupExternalConfig(e){const t=e.loadLocales||(()=>Promise.resolve(Ws));return{...e,loadLocales:t}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,canDispatch:this.canDispatch,custom:this.config.custom,external:this.config.external}}setupCoreViewPluginConfig(){return{getters:this.getters,stateObserver:this.state,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,canDispatch:this.canDispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}checkDispatchAllowed(e){const t=Hs(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return t.some((e=>"Success"!==e))?new Us(t.flat()):Us.Success}checkDispatchAllowedCoreCommand(e){const t=this.corePlugins.map((t=>t.allowDispatch(e)));return t.push(this.range.allowDispatch(e)),t}checkDispatchAllowedLocalCommand(e){return this.uiHandlers.map((t=>t.allowDispatch(e)))}finalize(){this.status=3;for(const e of this.handlers)e.finalize();this.status=0,this.trigger("command-finalized")}canDispatch=(e,t)=>this.checkDispatchAllowed(PU(e,t));dispatch=(e,t)=>{const o=PU(e,t),s=this.status;if(this.getters.isReadonly()&&(i=o,!Vs.has(i.type)))return new Us("Readonly");var i;if(!this.session.canApplyOptimisticUpdate())return new Us("WaitingSessionConfirmation");switch(s){case 0:const t=this.checkDispatchAllowed(o);if(!t.isSuccessful)return this.trigger("update"),t;this.status=1;const{changes:s,commands:i}=this.state.recordChanges((()=>{const t=performance.now();Hs(o)&&this.state.addCommand(o),this.dispatchToHandlers(this.handlers,o),this.finalize();const s=performance.now()-t;s>5&&console.debug(e,s,"ms")}));this.session.save(o,i,s),this.status=0,this.trigger("update");break;case 1:if(Hs(o)){const e=this.checkDispatchAllowed(o);if(!e.isSuccessful)return e;this.state.addCommand(o)}this.dispatchToHandlers(this.handlers,o);break;case 3:throw new Error("Cannot dispatch commands in the finalize state");case 2:if(Hs(o))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,o)}return Us.Success};dispatchFromCorePlugin=(e,t)=>{const o=PU(e,t),s=this.status;this.status=2;const i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,o),this.status=s,Us.Success};dispatchToHandlers(e,t){const o=Hs(t);for(const s of e)!o&&s instanceof Nk||s.beforeHandle(t);for(const s of e)!o&&s instanceof Nk||s.handle(t);this.trigger("command-dispatched",t)}drawLayer(e,t){const o=this.renderers[t];if(o)for(const s of o)e.ctx.save(),s.drawLayer(e,t),e.ctx.restore()}exportData(){let e=SD();for(const t of this.handlers)t instanceof Nk&&t.export(e);return e.revisionId=this.session.getRevisionId()||Se,e=ze(e),e}updateMode(e){this.config.mode=e,this.trigger("update")}exportXLSX(){this.dispatch("EVALUATE_CELLS");let e={...SD(),sheets:[CD(uD,"Sheet1")]};for(const t of this.handlers)t instanceof Mk&&t.exportForExcel(e);return e=ze(e),_U(e)}garbageCollectExternalResources(){for(const e of this.corePlugins)e.garbageCollectExternalResources()}},e.PivotRuntimeDefinition=$N,e.Registry=n,e.Revision=oL,e.SPREADSHEET_DIMENSIONS=NU,e.Spreadsheet=vH,e.SpreadsheetPivotTable=qN,e.UIPlugin=BV,e.__info__=MU,e.addFunction=function e(t,o){return RS.add(t,o),{addFunction:(t,o)=>e(t,o)}},e.addRenderingLayer=function(e,t){if(Xs[e])throw new Error(`Layer ${e} already exists`);Xs[e]=t},e.astToFormula=gv,e.chartHelpers=$U,e.compile=HS,e.compileTokens=US,e.components=HU,e.constants=zU,e.convertAstNodes=cv,e.coreTypes=Ls,e.findCellInNewZone=Pr,e.functionCache=LS,e.helpers=VU,e.hooks=UU,e.invalidateCFEvaluationCommands=Ns,e.invalidateChartEvaluationCommands=Ps,e.invalidateDependenciesCommands=Ms,e.invalidateEvaluationCommands=Fs,e.iterateAstNodes=hv,e.links=LU,e.load=gD,e.parse=av,e.parseTokens=lv,e.readonlyAllowedCommands=Vs,e.registries=kU,e.setDefaultSheetViewSize=function(e){Pe=e},e.setTranslationMethod=function(e,t=(()=>!0)){ko=e,Vo=t},e.stores=BU,e.tokenColors=wE,e.tokenize=cl,MU.version="18.4.11",MU.date="2025-09-19T07:25:39.033Z",MU.hash="c7e71ac"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);
|
|
3343
|
+
`}var FU;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(FU||(FU={}));function PU(e,t={}){const o=ze(t);return o.type=e,o}const MU={},NU={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:te,HEADER_WIDTH:oe,DESKTOP_BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:se,DEFAULT_CELL_HEIGHT:ie,SCROLLBAR_WIDTH:ne},kU={autoCompleteProviders:mE,autofillModifiersRegistry:PV,autofillRulesRegistry:MV,cellMenuRegistry:tF,colMenuRegistry:gP,errorTypes:oi,linkMenuRegistry:bR,functionRegistry:RS,featurePluginRegistry:EL,iconsOnCellRegistry:TV,statefulUIPluginRegistry:RL,coreViewsPluginRegistry:TL,corePluginRegistry:xL,rowMenuRegistry:SP,sidePanelRegistry:wk,figureRegistry:Gx,chartSidePanelComponentRegistry:JM,chartComponentRegistry:ix,chartRegistry:sx,chartSubtypeRegistry:rx,topbarMenuRegistry:ML,topbarComponentRegistry:NL,clickableCellRegistry:AL,otRegistry:$V,inverseCommandRegistry:DL,urlRegistry:zo,cellPopoverRegistry:Zx,numberFormatMenuRegistry:OL,repeatLocalCommandTransformRegistry:vL,repeatCommandTransformRegistry:fL,clipboardHandlersRegistries:eh,pivotRegistry:ik,pivotTimeAdapterRegistry:vc,pivotSidePanelRegistry:lk,pivotNormalizationValueRegistry:jc,supportedPivotPositionalFormulaRegistry:Ok,pivotToFunctionValueRegistry:Yc,migrationStepRegistry:lD,chartJsExtensionRegistry:Eh},VU={arg:Qh,isEvaluationError:gi,toBoolean:Ei,toJsDate:Ri,toNumber:fi,toString:wi,toNormalizedPivotValue:Gc,toFunctionPivotValue:qc,toXC:Po,toZone:ur,toUnboundedZone:dr,toCartesian:Fo,numberToLetters:wo,lettersToNumber:Io,UuidGenerator:Ka,formatValue:In,createCurrencyFormat:Vn,ColorGenerator:fo,computeTextWidth:Va,createEmptyWorkbookData:SD,createEmptySheet:bD,createEmptyExcelSheet:CD,rgbaToHex:Yt,colorToRGBA:Xt,positionToZone:Mr,isDefined:lt,isMatrix:js,lazy:ut,genericRepeat:bL,createAction:i,createActions:o,transformRangeData:oh,deepEquals:mt,overlap:xr,union:yr,isInside:Er,deepCopy:ze,expandZoneOnInsertion:vr,reduceZoneOnDeletion:Cr,unquote:Ge,getMaxObjectId:kc,getFunctionsFromTokens:GS,getFirstPivotFunction:BN,getNumberOfPivotFunctions:zN,parseDimension:Hc,isDateOrDatetimeField:Uc,makeFieldProposal:VN,insertTokenAfterArgSeparator:LN,insertTokenAfterLeftParenthesis:HN,mergeContiguousZones:Br,getPivotHighlights:wN,pivotTimeAdapter:bc,UNDO_REDO_PIVOT_COMMANDS:OV,createPivotFormula:$c,areDomainArgsFieldsValid:zc,splitReference:ra,sanitizeSheetName:qe,getUniqueText:Vt,isNumber:Rs,isDateTime:cs},LU={isMarkdownLink:et,parseMarkdownLink:st,markdownLink:ot,openLink:Zo,urlRepresentation:qo},HU={Checkbox:oR,Section:BE,RoundColorPicker:zE,ChartDataSeries:cM,ChartErrorSection:hM,ChartLabelRange:dM,ChartTitle:SM,ChartPanel:tN,ChartFigure:zx,ChartJsComponent:jC,Grid:_k,GridOverlay:GP,ScorecardChart:cy,LineConfigPanel:LM,BarConfigPanel:gM,PieChartDesignPanel:BM,GenericChartConfigPanel:uM,ChartWithAxisDesignPanel:TM,LineChartDesignPanel:HM,GaugeChartConfigPanel:OM,GaugeChartDesignPanel:FM,ScorecardChartConfigPanel:$M,ScorecardChartDesignPanel:GM,GeoChartDesignPanel:kM,RadarChartDesignPanel:zM,WaterfallChartDesignPanel:KM,ComboChartDesignPanel:DM,FunnelChartDesignPanel:_M,ChartTypePicker:QM,FigureComponent:Wx,MenuPopover:Ux,Popover:kx,SelectionInput:XE,ValidationMessages:kP,AddDimensionButton:RN,PivotDimensionGranularity:_N,PivotDimensionOrder:ON,PivotDimension:DN,PivotLayoutConfigurator:MN,PivotHTMLRenderer:Pk,PivotDeferUpdate:IN,PivotTitleSection:NN,CogWheelMenu:AN,TextInput:TN,SidePanelCollapsible:Jx,RadioSelection:yM,GeoChartRegionSelectSection:PM,ChartDashboardMenu:Bx,FullScreenChart:Fk},UU={useDragAndDropListItems:$E,useHighlights:iN,useHighlightsOnHover:sN},BU={useStoreProvider:ah,DependencyContainer:ih,CellPopoverStore:jx,ComposerFocusStore:bh,CellComposerStore:AP,FindAndReplaceStore:fN,HighlightStore:vE,DelayedHoveredCellStore:qx,HoveredTableStore:BP,ModelStore:gh,NotificationStore:bE,RendererStore:mh,SelectionInputStore:YE,SpreadsheetStore:fh,useStore:lh,useLocalStore:ch,SidePanelStore:Rk,PivotSidePanelStore:rk,PivotMeasureDisplayPanelStore:CN,ClientFocusStore:yP,GridRenderer:JP};const zU={DEFAULT_LOCALE:qs,HIGHLIGHT_COLOR:a,PIVOT_TABLE_CONFIG:Ve,ChartTerms:Yy},$U={...ux,...xI};e.AbstractCellClipboardHandler=rl,e.AbstractChart=YC,e.AbstractFigureClipboardHandler=Qc,e.CellErrorType=ti,e.ClientDisconnectedError=sL,e.CorePlugin=Nk,e.CoreViewPlugin=$k,e.DispatchResult=Us,e.EvaluationError=si,e.LocalTransportService=kL,e.Model=class extends sh{corePlugins=[];statefulUIPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;coreViewPluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},o={},s=[],i=new Ka,n=!1){const r=performance.now();console.debug("##### Model creation #####"),super(),ko===Mo&&Vo===No&&(Vo=()=>!0),s=fD(e,s);const a=gD(e,n);this.state=new _H,this.uuidGenerator=i,this.config=this.setupConfig(o),this.session=this.setupSession(a.revisionId),this.coreGetters={},this.range=new Bk(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.coreGetters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.coreGetters.getRangeData=this.range.getRangeData.bind(this.range),this.coreGetters.getRangeDataFromXc=this.range.getRangeDataFromXc.bind(this.range),this.coreGetters.getRangeDataFromZone=this.range.getRangeDataFromZone.bind(this.range),this.coreGetters.getRangeFromRangeData=this.range.getRangeFromRangeData.bind(this.range),this.coreGetters.getRangeFromZone=this.range.getRangeFromZone.bind(this.range),this.coreGetters.recomputeRanges=this.range.recomputeRanges.bind(this.range),this.coreGetters.isRangeValid=this.range.isRangeValid.bind(this.range),this.coreGetters.extendRange=this.range.extendRange.bind(this.range),this.coreGetters.getRangesUnion=this.range.getRangesUnion.bind(this.range),this.coreGetters.removeRangesSheetPrefix=this.range.removeRangesSheetPrefix.bind(this.range),this.coreGetters.adaptFormulaStringDependencies=this.range.adaptFormulaStringDependencies.bind(this.range),this.coreGetters.copyFormulaStringForSheet=this.range.copyFormulaStringForSheet.bind(this.range),this.getters={isReadonly:()=>"readonly"===this.config.mode||"dashboard"===this.config.mode,isDashboard:()=>"dashboard"===this.config.mode},this.selection=new AH(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.coreViewPluginConfig=this.setupCoreViewPluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(const e of xL.getAll())this.setupCorePlugin(e,a);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(s);for(const e of TL.getAll()){const t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(const e of RL.getAll()){const t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(const e of EL.getAll()){const t=this.setupUiPlugin(e);this.handlers.push(t),this.uiHandlers.push(t)}if(this.dispatch("START"),this.selection.observe(this,{handleEvent:()=>this.trigger("update")}),this.setupSessionEvents(),this.joinSession(),o.snapshotRequested||e["[Content_Types].xml"]&&!this.getters.isReadonly()){const e=performance.now();console.debug("Snapshot requested"),this.session.snapshot(this.exportData()),this.garbageCollectExternalResources(),console.debug("Snapshot taken in",performance.now()-e,"ms")}t.markRaw(this),console.debug("Model created in",performance.now()-r,"ms"),console.debug("######")}joinSession(){this.session.join(this.config.client)}async leaveSession(){const e=this.getters.isReadonly()?void 0:ut((()=>this.exportData()));await this.session.leave(e)}setupUiPlugin(e){const t=new e(this.uiPluginConfig);for(const o of e.getters){if(!(o in t))throw new Error(`Invalid getter name: ${o} for plugin ${t.constructor}`);if(o in this.getters)throw new Error(`Getter "${o}" is already defined.`);this.getters[o]=t[o].bind(t)}for(const o of e.layers)this.renderers[o]||(this.renderers[o]=[]),this.renderers[o].push(t);return t}setupCoreViewPlugin(e){const t=new e(this.coreViewPluginConfig);for(const o of e.getters){if(!(o in t))throw new Error(`Invalid getter name: ${o} for plugin ${t.constructor}`);if(o in this.getters)throw new Error(`Getter "${o}" is already defined.`);this.getters[o]=t[o].bind(t)}return t}setupCorePlugin(e,t){const o=new e(this.corePluginConfig);for(const t of e.getters){if(!(t in o))throw new Error(`Invalid getter name: ${t} for plugin ${o.constructor}`);if(t in this.coreGetters)throw new Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=o[t].bind(o)}o.import(t),this.corePlugins.push(o),this.coreHandlers.push(o),this.handlers.push(o)}onRemoteRevisionReceived({commands:e}){for(const t of e){const e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new iL(EH({initialRevisionId:e,recordChanges:this.state.recordChanges.bind(this.state),dispatch:e=>{this.checkDispatchAllowed(e).isSuccessful?(this.isReplayingCommand=!0,this.dispatchToHandlers(this.coreHandlers,e),this.isReplayingCommand=!1):this.dispatchToHandlers(this.coreHandlers,{type:"UNDO",commands:[e]})}}),this.config.transportService,e)}setupSessionEvents(){this.session.on("remote-revision-received",this,this.onRemoteRevisionReceived),this.session.on("revision-undone",this,(({commands:e})=>{this.dispatchFromCorePlugin("UNDO",{commands:e}),this.finalize()})),this.session.on("revision-redone",this,(({commands:e})=>{this.dispatchFromCorePlugin("REDO",{commands:e}),this.finalize()})),this.session.on("unexpected-revision-id",this,(()=>this.trigger("unexpected-revision-id"))),this.session.on("collaborative-event-received",this,(()=>{this.trigger("update")}))}setupConfig(e){const t=e.client||{id:this.uuidGenerator.smallUuid(),name:Ho("Anonymous").toString()},o=e.transportService||new kL;return{...e,mode:e.mode||"normal",custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:o,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger("notify-ui",e),raiseBlockingErrorUI:e=>this.trigger("raise-error-ui",{text:e}),customColors:e.customColors||[]}}setupExternalConfig(e){const t=e.loadLocales||(()=>Promise.resolve(Ws));return{...e,loadLocales:t}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,canDispatch:this.canDispatch,custom:this.config.custom,external:this.config.external}}setupCoreViewPluginConfig(){return{getters:this.getters,stateObserver:this.state,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,canDispatch:this.canDispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}checkDispatchAllowed(e){const t=Hs(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return t.some((e=>"Success"!==e))?new Us(t.flat()):Us.Success}checkDispatchAllowedCoreCommand(e){const t=this.corePlugins.map((t=>t.allowDispatch(e)));return t.push(this.range.allowDispatch(e)),t}checkDispatchAllowedLocalCommand(e){return this.uiHandlers.map((t=>t.allowDispatch(e)))}finalize(){this.status=3;for(const e of this.handlers)e.finalize();this.status=0,this.trigger("command-finalized")}canDispatch=(e,t)=>this.checkDispatchAllowed(PU(e,t));dispatch=(e,t)=>{const o=PU(e,t),s=this.status;if(this.getters.isReadonly()&&(i=o,!Vs.has(i.type)))return new Us("Readonly");var i;if(!this.session.canApplyOptimisticUpdate())return new Us("WaitingSessionConfirmation");switch(s){case 0:const t=this.checkDispatchAllowed(o);if(!t.isSuccessful)return this.trigger("update"),t;this.status=1;const{changes:s,commands:i}=this.state.recordChanges((()=>{const t=performance.now();Hs(o)&&this.state.addCommand(o),this.dispatchToHandlers(this.handlers,o),this.finalize();const s=performance.now()-t;s>5&&console.debug(e,s,"ms")}));this.session.save(o,i,s),this.status=0,this.trigger("update");break;case 1:if(Hs(o)){const e=this.checkDispatchAllowed(o);if(!e.isSuccessful)return e;this.state.addCommand(o)}this.dispatchToHandlers(this.handlers,o);break;case 3:throw new Error("Cannot dispatch commands in the finalize state");case 2:if(Hs(o))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,o)}return Us.Success};dispatchFromCorePlugin=(e,t)=>{const o=PU(e,t),s=this.status;this.status=2;const i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,o),this.status=s,Us.Success};dispatchToHandlers(e,t){const o=Hs(t);for(const s of e)!o&&s instanceof Nk||s.beforeHandle(t);for(const s of e)!o&&s instanceof Nk||s.handle(t);this.trigger("command-dispatched",t)}drawLayer(e,t){const o=this.renderers[t];if(o)for(const s of o)e.ctx.save(),s.drawLayer(e,t),e.ctx.restore()}exportData(){let e=SD();for(const t of this.handlers)t instanceof Nk&&t.export(e);return e.revisionId=this.session.getRevisionId()||Se,e=ze(e),e}updateMode(e){this.config.mode=e,this.trigger("update")}exportXLSX(){this.dispatch("EVALUATE_CELLS");let e={...SD(),sheets:[CD(uD,"Sheet1")]};for(const t of this.handlers)t instanceof Mk&&t.exportForExcel(e);return e=ze(e),_U(e)}garbageCollectExternalResources(){for(const e of this.corePlugins)e.garbageCollectExternalResources()}},e.PivotRuntimeDefinition=$N,e.Registry=n,e.Revision=oL,e.SPREADSHEET_DIMENSIONS=NU,e.Spreadsheet=vH,e.SpreadsheetPivotTable=qN,e.UIPlugin=BV,e.__info__=MU,e.addFunction=function e(t,o){return RS.add(t,o),{addFunction:(t,o)=>e(t,o)}},e.addRenderingLayer=function(e,t){if(Xs[e])throw new Error(`Layer ${e} already exists`);Xs[e]=t},e.astToFormula=gv,e.chartHelpers=$U,e.compile=HS,e.compileTokens=US,e.components=HU,e.constants=zU,e.convertAstNodes=cv,e.coreTypes=Ls,e.findCellInNewZone=Pr,e.functionCache=LS,e.helpers=VU,e.hooks=UU,e.invalidateCFEvaluationCommands=Ns,e.invalidateChartEvaluationCommands=Ps,e.invalidateDependenciesCommands=Ms,e.invalidateEvaluationCommands=Fs,e.iterateAstNodes=hv,e.links=LU,e.load=gD,e.parse=av,e.parseTokens=lv,e.readonlyAllowedCommands=Vs,e.registries=kU,e.setDefaultSheetViewSize=function(e){Pe=e},e.setTranslationMethod=function(e,t=(()=>!0)){ko=e,Vo=t},e.stores=BU,e.tokenColors=wE,e.tokenize=cl,MU.version="18.4.12",MU.date="2025-09-23T12:37:43.708Z",MU.hash="0c91305"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);
|