@odoo/o-spreadsheet 18.3.0-alpha.1 → 18.3.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/o-spreadsheet.cjs.js +26 -8
- package/dist/o-spreadsheet.d.ts +5 -0
- package/dist/o-spreadsheet.esm.js +26 -8
- package/dist/o-spreadsheet.iife.js +26 -8
- package/dist/o-spreadsheet.iife.min.js +189 -189
- package/dist/o_spreadsheet.xml +3 -3
- package/package.json +1 -1
|
@@ -335,7 +335,7 @@
|
|
|
335
335
|
color: ${"#09414A"};
|
|
336
336
|
background-color: ${"#CDEDF1"};
|
|
337
337
|
}
|
|
338
|
-
`;class hD extends t.Component{static template="o-spreadsheet-ValidationMessages";static props={messages:Array,msgType:String,singleBox:{type:Boolean,optional:!0}};get divClasses(){return"warning"===this.props.msgType?"o-validation-warning":"info"===this.props.msgType?"o-validation-info":"o-validation-error"}get alertBoxes(){return this.props.singleBox?[this.props.messages]:this.props.messages.map((e=>[e]))}}class dD extends t.Component{static template="o-spreadsheet.ChartErrorSection";static components={Section:X_,ValidationMessages:hD};static props={messages:{type:Array,element:String}}}class uD extends t.Component{static template="o-spreadsheet.ChartLabelRange";static components={SelectionInput:lD,Checkbox:HI,Section:X_};static props={title:{type:String,optional:!0},range:String,isInvalid:Boolean,onSelectionChanged:Function,onSelectionConfirmed:Function,options:{type:Array,optional:!0}};static defaultProps={title:Mo("Categories / Labels"),options:[]}}class gD extends t.Component{static template="o-spreadsheet-GenericChartConfigPanel";static components={ChartDataSeries:cD,ChartLabelRange:uD,Section:X_,Checkbox:HI,ChartErrorSection:dD};static props={figureId:String,definition:Object,updateChart:Function,canUpdateChart:Function};state=t.useState({datasetDispatchResult:void 0,labelsDispatchResult:void 0});dataSets=[];labelRange;chartTerms=mE;setup(){this.dataSets=this.props.definition.dataSets,this.labelRange=this.props.definition.labelRange}get errorMessages(){return[...this.state.datasetDispatchResult?.reasons||[],...this.state.labelsDispatchResult?.reasons||[]].map((e=>mE.Errors[e]||mE.Errors.Unexpected))}get isDatasetInvalid(){return!!this.state.datasetDispatchResult?.isCancelledBecause("InvalidDataSet")}get isLabelInvalid(){return!!this.state.labelsDispatchResult?.isCancelledBecause("InvalidLabelRange")}get dataSetsHaveTitleLabel(){return Mo("Use row %s as headers",this.calculateHeaderPosition()||"")}getLabelRangeOptions(){return[{name:"aggregated",label:this.chartTerms.AggregatedChart,value:this.props.definition.aggregated??!1,onChange:this.onUpdateAggregated.bind(this)},{name:"dataSetsHaveTitle",label:this.dataSetsHaveTitleLabel,value:this.props.definition.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}onUpdateDataSetsHaveTitle(e){this.props.updateChart(this.props.figureId,{dataSetsHaveTitle:e})}onDataSeriesRangesChanged(e){this.dataSets=e.map(((e,t)=>({...this.dataSets?.[t],dataRange:e}))),this.state.datasetDispatchResult=this.props.canUpdateChart(this.props.figureId,{dataSets:this.dataSets})}onDataSeriesReordered(e){const t=sx({dataSets:this.dataSets},this.dataSets.length),o=this.dataSets.map((e=>t.next()));this.dataSets=e.map((e=>({backgroundColor:o[e],...this.dataSets[e]}))),this.state.datasetDispatchResult=this.props.updateChart(this.props.figureId,{dataSets:this.dataSets})}onDataSeriesRemoved(e){const t=sx({dataSets:this.dataSets},this.dataSets.length),o=this.dataSets.map((e=>t.next()));this.dataSets=this.dataSets.map(((e,t)=>({backgroundColor:o[t],...e}))).filter(((t,o)=>o!==e)),this.state.datasetDispatchResult=this.props.updateChart(this.props.figureId,{dataSets:this.dataSets})}onDataSeriesConfirmed(){this.dataSets=Hr(this.env.model.getters,this.dataSets),this.state.datasetDispatchResult=this.props.updateChart(this.props.figureId,{dataSets:this.dataSets})}getDataSeriesRanges(){return this.dataSets}onLabelRangeChanged(e){this.labelRange=e[0],this.state.labelsDispatchResult=this.props.canUpdateChart(this.props.figureId,{labelRange:this.labelRange})}onLabelRangeConfirmed(){this.state.labelsDispatchResult=this.props.updateChart(this.props.figureId,{labelRange:this.labelRange})}getLabelRange(){return this.labelRange||""}onUpdateAggregated(e){this.props.updateChart(this.props.figureId,{aggregated:e})}calculateHeaderPosition(){if(this.isDatasetInvalid||this.isLabelInvalid)return;const e=this.env.model.getters,t=e.getActiveSheetId(),o=Ur(e,t,this.labelRange),s=$c(e,this.dataSets,t,this.props.definition.dataSetsHaveTitle);return s.length?s[0].dataRange.zone.top+1:o?o.zone.top+1:void 0}}class pD extends gD{static template="o-spreadsheet-BarConfigPanel";get stackedLabel(){return this.props.definition.horizontal?this.chartTerms.StackedBarChart:this.chartTerms.StackedColumnChart}onUpdateStacked(e){this.props.updateChart(this.props.figureId,{stacked:e})}}Pc`
|
|
338
|
+
`;class hD extends t.Component{static template="o-spreadsheet-ValidationMessages";static props={messages:Array,msgType:String,singleBox:{type:Boolean,optional:!0}};get divClasses(){return"warning"===this.props.msgType?"o-validation-warning":"info"===this.props.msgType?"o-validation-info":"o-validation-error"}get alertBoxes(){return this.props.singleBox?[this.props.messages]:this.props.messages.map((e=>[e]))}}class dD extends t.Component{static template="o-spreadsheet.ChartErrorSection";static components={Section:X_,ValidationMessages:hD};static props={messages:{type:Array,element:String}}}class uD extends t.Component{static template="o-spreadsheet.ChartLabelRange";static components={SelectionInput:lD,Checkbox:HI,Section:X_};static props={title:{type:String,optional:!0},range:String,isInvalid:Boolean,onSelectionChanged:Function,onSelectionConfirmed:Function,options:{type:Array,optional:!0}};static defaultProps={title:Mo("Categories / Labels"),options:[]}}class gD extends t.Component{static template="o-spreadsheet-GenericChartConfigPanel";static components={ChartDataSeries:cD,ChartLabelRange:uD,Section:X_,Checkbox:HI,ChartErrorSection:dD};static props={figureId:String,definition:Object,updateChart:Function,canUpdateChart:Function};state=t.useState({datasetDispatchResult:void 0,labelsDispatchResult:void 0});dataSets=[];labelRange;chartTerms=mE;setup(){this.dataSets=this.props.definition.dataSets,this.labelRange=this.props.definition.labelRange}get errorMessages(){return[...this.state.datasetDispatchResult?.reasons||[],...this.state.labelsDispatchResult?.reasons||[]].map((e=>mE.Errors[e]||mE.Errors.Unexpected))}get isDatasetInvalid(){return!!this.state.datasetDispatchResult?.isCancelledBecause("InvalidDataSet")}get isLabelInvalid(){return!!this.state.labelsDispatchResult?.isCancelledBecause("InvalidLabelRange")}get dataSetsHaveTitleLabel(){return Mo("Use row %s as headers",this.calculateHeaderPosition()||"")}getLabelRangeOptions(){return[{name:"aggregated",label:this.chartTerms.AggregatedChart,value:this.props.definition.aggregated??!1,onChange:this.onUpdateAggregated.bind(this)},{name:"dataSetsHaveTitle",label:this.dataSetsHaveTitleLabel,value:this.props.definition.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}onUpdateDataSetsHaveTitle(e){this.props.updateChart(this.props.figureId,{dataSetsHaveTitle:e})}onDataSeriesRangesChanged(e){this.dataSets=e.map(((e,t)=>({...this.dataSets?.[t],dataRange:e}))),this.state.datasetDispatchResult=this.props.canUpdateChart(this.props.figureId,{dataSets:this.dataSets})}onDataSeriesReordered(e){const t=sx({dataSets:this.dataSets},this.dataSets.length),o=this.dataSets.map((e=>t.next()));this.dataSets=e.map((e=>({backgroundColor:o[e],...this.dataSets[e]}))),this.state.datasetDispatchResult=this.props.updateChart(this.props.figureId,{dataSets:this.dataSets})}onDataSeriesRemoved(e){const t=sx({dataSets:this.dataSets},this.dataSets.length),o=this.dataSets.map((e=>t.next()));this.dataSets=this.dataSets.map(((e,t)=>({backgroundColor:o[t],...e}))).filter(((t,o)=>o!==e)),this.state.datasetDispatchResult=this.props.updateChart(this.props.figureId,{dataSets:this.dataSets})}onDataSeriesConfirmed(){this.dataSets=Hr(this.env.model.getters,this.dataSets),this.state.datasetDispatchResult=this.props.updateChart(this.props.figureId,{dataSets:this.dataSets}),this.state.datasetDispatchResult.isSuccessful&&(this.dataSets=this.env.model.getters.getChartDefinition(this.props.figureId).dataSets)}getDataSeriesRanges(){return this.dataSets}onLabelRangeChanged(e){this.labelRange=e[0],this.state.labelsDispatchResult=this.props.canUpdateChart(this.props.figureId,{labelRange:this.labelRange})}onLabelRangeConfirmed(){this.state.labelsDispatchResult=this.props.updateChart(this.props.figureId,{labelRange:this.labelRange})}getLabelRange(){return this.labelRange||""}onUpdateAggregated(e){this.props.updateChart(this.props.figureId,{aggregated:e})}calculateHeaderPosition(){if(this.isDatasetInvalid||this.isLabelInvalid)return;const e=this.env.model.getters,t=e.getActiveSheetId(),o=Ur(e,t,this.labelRange),s=$c(e,this.dataSets,t,this.props.definition.dataSetsHaveTitle);return s.length?s[0].dataRange.zone.top+1:o?o.zone.top+1:void 0}}class pD extends gD{static template="o-spreadsheet-BarConfigPanel";get stackedLabel(){return this.props.definition.horizontal?this.chartTerms.StackedBarChart:this.chartTerms.StackedColumnChart}onUpdateStacked(e){this.props.updateChart(this.props.figureId,{stacked:e})}}Pc`
|
|
339
339
|
.o_side_panel_collapsible_title {
|
|
340
340
|
font-size: 16px;
|
|
341
341
|
cursor: pointer;
|
|
@@ -680,7 +680,7 @@
|
|
|
680
680
|
}
|
|
681
681
|
}
|
|
682
682
|
}
|
|
683
|
-
`;class ND extends t.Component{static template="o-spreadsheet-TextValueProvider";static props={proposals:Array,selectedIndex:{type:Number,optional:!0},onValueSelected:Function,onValueHovered:Function};autoCompleteListRef=t.useRef("autoCompleteList");setup(){t.useEffect((()=>{const e=this.props.selectedIndex;if(void 0===e)return;const t=this.autoCompleteListRef.el?.children[e];t?.scrollIntoView?.({block:"nearest"})}),(()=>[this.props.selectedIndex,this.autoCompleteListRef.el]))}}class kD extends _c{mutators=["useProvider","moveSelection","hide","selectIndex"];selectedIndex=void 0;provider;get selectedProposal(){if(void 0!==this.selectedIndex&&void 0!==this.provider)return this.provider.proposals[this.selectedIndex]}useProvider(e){this.provider=e,this.selectedIndex=e.autoSelectFirstProposal?0:void 0}hide(){this.provider=void 0,this.selectedIndex=void 0}selectIndex(e){this.selectedIndex=e}moveSelection(e){this.provider&&(void 0!==this.selectedIndex?"previous"===e?(this.selectedIndex--,this.selectedIndex<0&&(this.selectedIndex=this.provider.proposals.length-1)):this.selectedIndex=(this.selectedIndex+1)%this.provider.proposals.length:this.selectedIndex=0)}}class LD{el;constructor(e){this.el=e}updateEl(e){this.el=e}selectRange(e,t){let o=window.getSelection();const{start:s,end:i}=this.getCurrentSelection();if(s===e&&i===t)return;if(0===o.rangeCount){const e=document.createRange();o.addRange(e)}const n=o.getRangeAt(0);let r;if(this.el.contains(n.startContainer)?r=n:(r=document.createRange(),o.removeAllRanges(),o.addRange(r)),e===t&&0===e)r.setStart(this.el,0),r.setEnd(this.el,0);else{const o=this.getText().length;(e<0||t>o)&&(console.warn(`wrong selection asked start ${e}, end ${t}, text content length ${o}`),e<0&&(e=0),t>o&&(t=o),e>o&&(e=o));let s=this.findChildAtCharacterIndex(e),i=this.findChildAtCharacterIndex(t);r.setStart(s.node,s.offset),r.setEnd(i.node,i.offset)}}findChildAtCharacterIndex(e){let t,o,s=XI(this.el),i=e,n=!0;do{t=s.next(),t.done||t.value.hasChildNodes()||(t.value.textContent&&t.value.textContent.length<i?i-=t.value.textContent.length:t.value.textContent&&t.value.textContent.length>=i&&s.return(t.value),o=t.value),t.done||"P"!==t.value.nodeName||(n?n=!1:i--)}while(!t.done&&i);return t.value?{node:t.value,offset:i}:{node:o,offset:i}}setText(e){if(0===e.length)return void this.removeAll();const t=Array.from(this.el.childNodes),o=e.length;for(let s=0;s<o;s++){const o=e[s],i=t[s];let n,r=!1;i&&"P"===i.nodeName?n=i:(r=!0,n=document.createElement("p"));const a=o.length,l=Array.from(n.childNodes);for(let e=0;e<a;e++){const t=o[e],s=l[e];if(s&&"tagName"in s&&"SPAN"===s.tagName&&VD(t,s))continue;if(!t.value&&!t.class){s&&n.removeChild(s);continue}const i=document.createElement("span");i.innerText=t.value,i.style.color=t.color||"",t.class&&i.classList.add(t.class),s?n.replaceChild(i,s):n.appendChild(i)}if(l.length>a)for(let e=a;e<l.length;e++)n.removeChild(l[e]);if(!n.hasChildNodes()){const e=document.createElement("span");e.appendChild(document.createElement("br")),n.appendChild(e)}r&&(i?this.el.replaceChild(n,i):this.el.appendChild(n))}if(t.length>o)for(let e=o;e<t.length;e++)this.el.removeChild(t[e])}scrollSelectionIntoView(){const e=document.getSelection()?.focusNode;if(!e||!this.el.contains(e))return;const t=e instanceof HTMLElement?e:e.parentElement;t?.scrollIntoView?.({block:"nearest"})}removeSelection(){window.getSelection().removeAllRanges()}removeAll(){if(this.el)for(;this.el.firstChild;)this.el.removeChild(this.el.firstChild)}getCurrentSelection(){return KI(this.el)}getText(){let e="",t=XI(this.el),o=t.next(),s=!0;for(;!o.done;)o.value.hasChildNodes()||(e+=o.value.textContent),("P"===o.value.nodeName||"DIV"===o.value.nodeName&&o.value!==this.el)&&(s?s=!1:e+=Pe),o=t.next();return e}}function VD(e,t){const o=(e.color?zt(e.color):"")===(t.style?.color?zt(t.style.color):""),s=mt([e.class],[...t.classList]),i=t.innerText===e.value;return o&&s&&i}Pc`
|
|
683
|
+
`;class ND extends t.Component{static template="o-spreadsheet-TextValueProvider";static props={proposals:Array,selectedIndex:{type:Number,optional:!0},onValueSelected:Function,onValueHovered:Function};autoCompleteListRef=t.useRef("autoCompleteList");setup(){t.useEffect((()=>{const e=this.props.selectedIndex;if(void 0===e)return;const t=this.autoCompleteListRef.el?.children[e];t?.scrollIntoView?.({block:"nearest"})}),(()=>[this.props.selectedIndex,this.autoCompleteListRef.el]))}}class kD extends _c{mutators=["useProvider","moveSelection","hide","selectIndex"];selectedIndex=void 0;provider;get selectedProposal(){if(void 0!==this.selectedIndex&&void 0!==this.provider)return this.provider.proposals[this.selectedIndex]}useProvider(e){this.provider=e,this.selectedIndex=e.autoSelectFirstProposal?0:void 0}hide(){this.provider=void 0,this.selectedIndex=void 0}selectIndex(e){this.selectedIndex=e}moveSelection(e){this.provider&&(void 0!==this.selectedIndex?"previous"===e?(this.selectedIndex--,this.selectedIndex<0&&(this.selectedIndex=this.provider.proposals.length-1)):this.selectedIndex=(this.selectedIndex+1)%this.provider.proposals.length:this.selectedIndex=0)}}class LD{el;constructor(e){this.el=e}updateEl(e){this.el=e}selectRange(e,t){let o=window.getSelection();const{start:s,end:i}=this.getCurrentSelection();if(s===e&&i===t)return;if(0===o.rangeCount){const e=document.createRange();o.addRange(e)}const n=o.getRangeAt(0);let r;if(this.el.contains(n.startContainer)?r=n:(r=document.createRange(),o.removeAllRanges(),o.addRange(r)),e===t&&0===e)r.setStart(this.el,0),r.setEnd(this.el,0);else{const o=this.getText().length;(e<0||t>o)&&(console.warn(`wrong selection asked start ${e}, end ${t}, text content length ${o}`),e<0&&(e=0),t>o&&(t=o),e>o&&(e=o));let s=this.findChildAtCharacterIndex(e),i=this.findChildAtCharacterIndex(t);e<=t?(r.setStart(s.node,s.offset),r.setEnd(i.node,i.offset)):(r.setStart(i.node,i.offset),r.setEnd(s.node,s.offset))}}findChildAtCharacterIndex(e){let t,o,s=XI(this.el),i=e,n=!0;do{t=s.next(),t.done||t.value.hasChildNodes()||(t.value.textContent&&t.value.textContent.length<i?i-=t.value.textContent.length:t.value.textContent&&t.value.textContent.length>=i&&s.return(t.value),o=t.value),t.done||"P"!==t.value.nodeName||(n?n=!1:i--)}while(!t.done&&i);return t.value?{node:t.value,offset:i}:{node:o,offset:i}}setText(e){if(0===e.length)return void this.removeAll();const t=Array.from(this.el.childNodes),o=e.length;for(let s=0;s<o;s++){const o=e[s],i=t[s];let n,r=!1;i&&"P"===i.nodeName?n=i:(r=!0,n=document.createElement("p"));const a=o.length,l=Array.from(n.childNodes);for(let e=0;e<a;e++){const t=o[e],s=l[e];if(s&&"tagName"in s&&"SPAN"===s.tagName&&VD(t,s))continue;if(!t.value&&!t.class){s&&n.removeChild(s);continue}const i=document.createElement("span");i.innerText=t.value,i.style.color=t.color||"",t.class&&i.classList.add(t.class),s?n.replaceChild(i,s):n.appendChild(i)}if(l.length>a)for(let e=a;e<l.length;e++)n.removeChild(l[e]);if(!n.hasChildNodes()){const e=document.createElement("span");e.appendChild(document.createElement("br")),n.appendChild(e)}r&&(i?this.el.replaceChild(n,i):this.el.appendChild(n))}if(t.length>o)for(let e=o;e<t.length;e++)this.el.removeChild(t[e])}scrollSelectionIntoView(){const e=document.getSelection()?.focusNode;if(!e||!this.el.contains(e))return;const t=e instanceof HTMLElement?e:e.parentElement;t?.scrollIntoView?.({block:"nearest"})}removeSelection(){window.getSelection().removeAllRanges()}removeAll(){if(this.el)for(;this.el.firstChild;)this.el.removeChild(this.el.firstChild)}getCurrentSelection(){return KI(this.el)}getText(){let e="",t=XI(this.el),o=t.next(),s=!0;for(;!o.done;)o.value.hasChildNodes()||(e+=o.value.textContent),("P"===o.value.nodeName||"DIV"===o.value.nodeName&&o.value!==this.el)&&(s?s=!1:e+=Pe),o=t.next();return e}}function VD(e,t){const o=(e.color?zt(e.color):"")===(t.style?.color?zt(t.style.color):""),s=mt([e.class],[...t.classList]),i=t.innerText===e.value;return o&&s&&i}Pc`
|
|
684
684
|
.o-formula-assistant {
|
|
685
685
|
background: #ffffff;
|
|
686
686
|
.o-formula-assistant-head {
|
|
@@ -1201,7 +1201,7 @@
|
|
|
1201
1201
|
.pivot-defer-update {
|
|
1202
1202
|
min-height: 40px;
|
|
1203
1203
|
}
|
|
1204
|
-
`;class $O extends t.Component{static template="o-spreadsheet-PivotDeferUpdate";static props={deferUpdate:Boolean,isDirty:Boolean,toggleDeferUpdate:Function,discard:Function,apply:Function};static components={Section:X_,Checkbox:HI};get deferUpdatesLabel(){return Mo("Defer updates")}get deferUpdatesTooltip(){return Mo("Changing the pivot definition requires to reload the data. It may take some time.")}}Pc`
|
|
1204
|
+
`;class $O extends t.Component{static template="o-spreadsheet-PivotDeferUpdate";static props={deferUpdate:Boolean,isDirty:Boolean,toggleDeferUpdate:Function,discard:Function,apply:Function};static components={Section:X_,Checkbox:HI};get deferUpdatesLabel(){return Mo("Defer updates")}get deferUpdatesTooltip(){return Mo("Changing the pivot definition requires to reload the data. It may take some time.")}}function WO({refName:e}){const o=t.useRef(e);t.useEffect((e=>{e?.focus()}),(()=>[o.el]))}Pc`
|
|
1205
1205
|
input.pivot-dimension-search-field:focus {
|
|
1206
1206
|
outline: none;
|
|
1207
1207
|
}
|
|
@@ -1219,7 +1219,7 @@
|
|
|
1219
1219
|
flex-grow: 0;
|
|
1220
1220
|
height: inherit;
|
|
1221
1221
|
}
|
|
1222
|
-
`;class
|
|
1222
|
+
`;class GO extends t.Component{static template="o-spreadsheet-AddDimensionButton";static components={Popover:PI,TextValueProvider:ND};static props={onFieldPicked:Function,fields:Array,slots:{type:Object,optional:!0}};buttonRef=t.useRef("button");popover=t.useState({isOpen:!1});search=t.useState({input:""});autoComplete;setup(){this.autoComplete=wc(kD),this.autoComplete.useProvider(this.getProvider()),t.useExternalListener(window,"click",(e=>{e.target!==this.buttonRef.el&&(this.popover.isOpen=!1)})),WO({refName:"autofocus"})}getProvider(){return{proposals:this.proposals,autoSelectFirstProposal:!1,selectProposal:e=>{const t=this.props.fields.find((t=>t.string===e));t&&this.pickField(t)}}}get proposals(){let e;return e=this.search.input?zr(this.search.input,this.props.fields,(e=>e.string)):this.props.fields,e.map((e=>{const t=e.string;return{text:t,fuzzySearchKey:t,htmlContent:Ah(this.search.input,t,I,"o-semi-bold")}}))}get popoverProps(){const{x:e,y:t,width:o,height:s}=this.buttonRef.el.getBoundingClientRect();return{anchorRect:{x:e,y:t,width:o,height:s},positioning:"BottomLeft"}}updateSearch(e){this.search.input=e,this.autoComplete.useProvider(this.getProvider())}pickField(e){this.props.onFieldPicked(e.name),this.togglePopover()}togglePopover(){this.popover.isOpen=!this.popover.isOpen,this.search.input="",this.autoComplete.useProvider(this.getProvider())}onKeyDown(e){switch(e.key){case"Enter":const t=this.autoComplete.provider?.proposals;1===t?.length&&this.autoComplete.provider?.selectProposal(t[0].text||"");const o=this.autoComplete.selectedProposal;this.autoComplete.provider?.selectProposal(o?.text||"");break;case"ArrowUp":case"ArrowDown":this.autoComplete.moveSelection("ArrowDown"===e.key?"next":"previous");break;case"Escape":this.popover.isOpen=!1}}}Pc`
|
|
1223
1223
|
.o-spreadsheet {
|
|
1224
1224
|
.os-input {
|
|
1225
1225
|
border-width: 0 0 1px 0;
|
|
@@ -1233,7 +1233,7 @@
|
|
|
1233
1233
|
border-color: ${D};
|
|
1234
1234
|
}
|
|
1235
1235
|
}
|
|
1236
|
-
`;class
|
|
1236
|
+
`;class qO extends t.Component{static template="o-spreadsheet-TextInput";static props={value:String,onChange:Function,class:{type:String,optional:!0},id:{type:String,optional:!0},placeholder:{type:String,optional:!0},autofocus:{type:Boolean,optional:!0}};inputRef=t.useRef("input");setup(){t.useExternalListener(window,"click",(e=>{e.target!==this.inputRef.el&&this.inputRef.el?.value!==this.props.value&&this.save()}),{capture:!0}),this.props.autofocus&&WO({refName:"input"})}onKeyDown(e){switch(e.key){case"Enter":this.save(),e.preventDefault(),e.stopPropagation();break;case"Escape":this.inputRef.el&&(this.inputRef.el.value=this.props.value,this.inputRef.el.blur()),e.preventDefault(),e.stopPropagation()}}save(){const e=(this.inputRef.el?.value||"").trim();e!==this.props.value&&this.props.onChange(e),this.inputRef.el?.blur()}onMouseDown(e){e.target!==document.activeElement&&(e.preventDefault(),e.stopPropagation())}onMouseUp(e){const t=e.target;t!==document.activeElement&&(t.focus(),t.select(),e.preventDefault(),e.stopPropagation())}}class ZO extends t.Component{static template="o-spreadsheet-CogWheelMenu";static components={Menu:mR};static props={items:Array};buttonRef=t.useRef("button");menuState=t.useState({isOpen:!1,position:null,menuItems:[]});menuId=this.env.model.uuidGenerator.uuidv4();toggleMenu(e){if(e.closedMenuId===this.menuId)return;const{x:t,y:s}=this.buttonRef.el.getBoundingClientRect();this.menuState.isOpen=!this.menuState.isOpen,this.menuState.position={x:t,y:s},this.menuState.menuItems=o(this.props.items)}}Pc`
|
|
1237
1237
|
.pivot-dimension {
|
|
1238
1238
|
background-color: white;
|
|
1239
1239
|
border: 1px solid ${D};
|
|
@@ -1259,7 +1259,7 @@
|
|
|
1259
1259
|
}
|
|
1260
1260
|
}
|
|
1261
1261
|
}
|
|
1262
|
-
`;class
|
|
1262
|
+
`;class jO extends t.Component{static template="o-spreadsheet-PivotDimension";static props={dimension:Object,onRemoved:{type:Function,optional:!0},onNameUpdated:{type:Function,optional:!0},slots:{type:Object,optional:!0}};static components={CogWheelMenu:ZO,TextInput:qO};updateName(e){this.props.onNameUpdated?.(this.props.dimension,""===e||e.startsWith("=")?void 0:e)}}class YO extends t.Component{static template="o-spreadsheet-PivotDimensionGranularity";static props={dimension:Object,onUpdated:Function,availableGranularities:Set,allGranularities:Array};periods=Zl}class XO extends t.Component{static template="o-spreadsheet-PivotDimensionOrder";static props={dimension:Object,onUpdated:Function}}class KO extends t.Component{static template="o-spreadsheet-PivotMeasureEditor";static components={PivotDimension:jO,StandaloneComposer:qD};static props={definition:Object,measure:Object,onMeasureUpdated:Function,onRemoved:Function,generateMeasureId:Function,aggregators:Object,pivotId:String};getMeasureAutocomplete(){return e=this.props.definition,t=this.props.measure,{sequence:0,autoSelectFirstProposal:!0,getProposals(o){const s=e.measures.filter((e=>e!==t)).map((e=>{const t=We(e.id);return{text:t,description:e.displayName,htmlContent:[{value:t,color:J}],fuzzySearchKey:e.displayName+t+e.fieldName}})),i=e.rows.concat(e.columns).map((e=>{const t=We(e.nameWithGranularity);return{text:t,description:e.displayName,htmlContent:[{value:t,color:J}],fuzzySearchKey:e.displayName+t+e.fieldName}}));return s.concat(i)},selectProposal(e,t){let o=e.end;"SYMBOL"===e.type&&(o=e.start);const s=e.end;this.composer.changeComposerCursorSelection(o,s),this.composer.replaceComposerCursorSelection(t)}};var e,t}updateMeasureFormula(e){this.props.onMeasureUpdated({...this.props.measure,computedBy:{sheetId:this.env.model.getters.getActiveSheetId(),formula:"="===e[0]?e:"="+e}})}updateAggregator(e){this.props.onMeasureUpdated({...this.props.measure,aggregator:e,id:this.props.generateMeasureId(this.props.measure.fieldName,e)})}updateName(e,t){this.props.measure.computedBy&&t?this.props.onMeasureUpdated({...this.props.measure,userDefinedName:t,id:this.props.generateMeasureId(t,this.props.measure.aggregator),fieldName:t}):this.props.onMeasureUpdated({...this.props.measure,userDefinedName:t})}toggleMeasureVisibility(){this.props.onMeasureUpdated({...this.props.measure,isHidden:!this.props.measure.isHidden})}openShowValuesAs(){this.env.openSidePanel("PivotMeasureDisplayPanel",{pivotId:this.props.pivotId,measure:this.props.measure})}getColoredSymbolToken(e){if("SYMBOL"!==e.type)return;const t=$e(e.value,"'");return this.props.definition.columns.some((e=>e.nameWithGranularity===t))||this.props.definition.rows.some((e=>e.nameWithGranularity===t))||this.props.definition.measures.some((e=>e.id===t&&e.id!==this.props.measure.id))?J:void 0}}Pc`
|
|
1263
1263
|
.o-pivot-sort {
|
|
1264
1264
|
.o-sort-card {
|
|
1265
1265
|
width: fit-content;
|
|
@@ -1271,20 +1271,20 @@
|
|
|
1271
1271
|
}
|
|
1272
1272
|
}
|
|
1273
1273
|
}
|
|
1274
|
-
`;class
|
|
1274
|
+
`;class JO extends t.Component{static template="o-spreadsheet-PivotSortSection";static components={Section:X_};static props={definition:Object,pivotId:String};get hasValidSort(){const e=this.env.model.getters.getPivot(this.props.pivotId);return!!this.props.definition.sortedColumn&&lc(this.props.definition.sortedColumn,e)}get sortDescription(){const e="asc"===this.props.definition.sortedColumn?.order?Mo("ascending"):Mo("descending");return Mo("Sorted on column (%(ascOrDesc)s):",{ascOrDesc:e})}get sortValuesAndFields(){const e=this.props.definition.sortedColumn;if(!e)return[];const t=this.env.model.getters.getPivot(this.props.pivotId),o=this.env.model.getters.getLocale(),s=[],i=[];for(const n of e.domain){s.push(n);const{value:e,format:r}=t.getPivotHeaderValueAndFormat(s),a=Qn(e,{format:r,locale:o}),l=t.definition.getDimension(n.field);i.push({field:rc(l),value:a})}0===e.domain.length&&i.push({value:Mo("Total")});const n=t.getMeasure(e.measure).displayName;return i.push({value:n,field:Mo("Measure")}),i}}Pc`
|
|
1275
1275
|
.add-calculated-measure {
|
|
1276
1276
|
cursor: pointer;
|
|
1277
1277
|
}
|
|
1278
|
-
`;class JO extends t.Component{static template="o-spreadsheet-PivotLayoutConfigurator";static components={AddDimensionButton:WO,PivotDimension:ZO,PivotDimensionOrder:YO,PivotDimensionGranularity:jO,PivotMeasureEditor:XO,PivotSortSection:KO};static props={definition:Object,onDimensionsUpdated:Function,unusedGroupableFields:Array,measureFields:Array,unusedGranularities:Object,dateGranularities:Array,datetimeGranularities:Array,getScrollableContainerEl:{type:Function,optional:!0},pivotId:String};dimensionsRef=t.useRef("pivot-dimensions");dragAndDrop=Q_();AGGREGATORS=Wl;composerFocus;isDateOrDatetimeField=Xl;setup(){this.composerFocus=Cc(Oc)}startDragAndDrop(e,t){if(0!==t.button||"SELECT"===t.target.tagName)return;const o=this.getDimensionElementsRects(),s=this.props.definition,{columns:i,rows:n}=s,r=[...i.map((e=>e.nameWithGranularity)),"__rows_title__",...n.map((e=>e.nameWithGranularity))],a=i.concat(n),l=r.map(((e,t)=>({id:e,size:o[t+1].height,position:o[t+1].y})));this.dragAndDrop.start("vertical",{draggedItemId:e.nameWithGranularity,initialMousePosition:t.clientY,items:l,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{const o=r.findIndex((t=>t===e));if(o===t)return;const s=[...r];s.splice(o,1),s.splice(t,0,e);const i=s.slice(0,s.indexOf("__rows_title__")),n=s.slice(s.indexOf("__rows_title__")+1);this.props.onDimensionsUpdated({columns:i.map((e=>a.find((t=>t.nameWithGranularity===e)))).filter(at),rows:n.map((e=>a.find((t=>t.nameWithGranularity===e)))).filter(at)})}})}getGranularitiesFor(e){return Xl(e)?"date"===e.type?this.props.dateGranularities:this.props.datetimeGranularities:[]}startDragAndDropMeasures(e,t){if(0!==t.button||"SELECT"===t.target.tagName||"INPUT"===t.target.tagName||"inactive"!==this.composerFocus.focusMode)return;const o=this.getDimensionElementsRects(),s=this.props.definition,{measures:i,columns:n,rows:r}=s,a=i.map((e=>e.id)),l=3+n.length+r.length,c=a.map(((e,t)=>({id:e,size:o[t+l].height,position:o[t+l].y})));this.dragAndDrop.start("vertical",{draggedItemId:e.id,initialMousePosition:t.clientY,items:c,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{const o=a.findIndex((t=>t===e));if(o===t)return;const s=[...a];s.splice(o,1),s.splice(t,0,e),this.props.onDimensionsUpdated({measures:s.map((e=>i.find((t=>t.id===e)))).filter(at)})}})}getDimensionElementsRects(){return Array.from(this.dimensionsRef.el.children).map((e=>{const t=getComputedStyle(e),o=e.getBoundingClientRect();return{x:o.x,y:o.y,width:o.width+parseInt(t.marginLeft||"0")+parseInt(t.marginRight||"0"),height:o.height+parseInt(t.marginTop||"0")+parseInt(t.marginBottom||"0")}}))}removeDimension(e){const{columns:t,rows:o}=this.props.definition;this.props.onDimensionsUpdated({columns:t.filter((t=>t.nameWithGranularity!==e.nameWithGranularity)),rows:o.filter((t=>t.nameWithGranularity!==e.nameWithGranularity))})}removeMeasureDimension(e){const{measures:t}=this.props.definition;this.props.onDimensionsUpdated({measures:t.filter((t=>t.id!==e.id))})}addColumnDimension(e){const{columns:t}=this.props.definition;this.props.onDimensionsUpdated({columns:t.concat([{fieldName:e,order:"asc"}])})}addRowDimension(e){const{rows:t}=this.props.definition;this.props.onDimensionsUpdated({rows:t.concat([{fieldName:e,order:"asc"}])})}addMeasureDimension(e){const{measures:t}=this.props.definition,o=this.getDefaultMeasureAggregator(e);this.props.onDimensionsUpdated({measures:t.concat([{id:this.getMeasureId(e,o),fieldName:e,aggregator:o}])})}updateMeasure(e,t){const{measures:o}=this.props.definition,s={measures:o.map((o=>o.id===e.id?t:o))};this.props.definition.sortedColumn?.measure===e.id&&(s.sortedColumn={...this.props.definition.sortedColumn,measure:t.id}),this.props.onDimensionsUpdated(s)}getMeasureId(e,t){const o=e+(t?`:${t}`:"");let s=o,i=2;for(;this.props.definition.measures.some((e=>e.id===s));)s=`${o}:${i}`,i++;return s}getDefaultMeasureAggregator(e){const t=this.props.measureFields.find((t=>t.name===e));return t?.aggregator?t.aggregator:"count"}addCalculatedMeasure(){const{measures:e}=this.props.definition,t=this.env.model.getters.generateNewCalculatedMeasureName(e);this.props.onDimensionsUpdated({measures:e.concat([{id:this.getMeasureId(t),fieldName:t,aggregator:"sum",computedBy:{sheetId:this.env.model.getters.getActiveSheetId(),formula:"=0"}}])})}updateOrder(e,t){const{rows:o,columns:s}=this.props.definition;this.props.onDimensionsUpdated({rows:o.map((o=>o.nameWithGranularity===e.nameWithGranularity?{...o,order:t||void 0}:o)),columns:s.map((o=>o.nameWithGranularity===e.nameWithGranularity?{...o,order:t||void 0}:o))})}updateGranularity(e,t){const{rows:o,columns:s}=this.props.definition;this.props.onDimensionsUpdated({rows:o.map((o=>o.nameWithGranularity===e.nameWithGranularity?{...o,granularity:t}:o)),columns:s.map((o=>o.nameWithGranularity===e.nameWithGranularity?{...o,granularity:t}:o))})}getMeasureDescription(e){const t=e.display;if(!t||"no_calculations"===t.type)return"";const o=this.env.model.getters.getPivot(this.props.pivotId),s=[...o.definition.columns,...o.definition.rows].find((e=>e.nameWithGranularity===t.fieldNameWithGranularity)),i=s?rc(s):"";return wE.descriptions[t.type](i)}}class QO extends t.Component{static template="o-spreadsheet-PivotTitleSection";static components={CogWheelMenu:qO,Section:X_,TextInput:GO};static props={pivotId:String,flipAxis:Function};get cogWheelMenuItems(){return[{name:Mo("Flip axes"),icon:"o-spreadsheet-Icon.EXCHANGE",execute:this.props.flipAxis},{name:Mo("Duplicate"),icon:"o-spreadsheet-Icon.COPY",execute:()=>this.duplicatePivot()},{name:Mo("Delete"),icon:"o-spreadsheet-Icon.TRASH",execute:()=>this.delete()}]}get name(){return this.env.model.getters.getPivotName(this.props.pivotId)}get displayName(){return this.env.model.getters.getPivotDisplayName(this.props.pivotId)}duplicatePivot(){const e=this.env.model.uuidGenerator.smallUuid(),t=this.env.model.uuidGenerator.smallUuid(),o=this.env.model.dispatch("DUPLICATE_PIVOT_IN_NEW_SHEET",{pivotId:this.props.pivotId,newPivotId:e,newSheetId:t});let s;s=o.isSuccessful?Mo("Pivot duplicated."):o.isCancelledBecause("PivotInError")?Mo("Cannot duplicate a pivot in error."):Mo("Pivot duplication failed.");const i=o.isSuccessful?"success":"danger";this.env.notifyUser({text:s,sticky:!1,type:i}),o.isSuccessful&&this.env.openSidePanel("PivotSidePanel",{pivotId:e})}delete(){this.env.askConfirmation(Mo("Are you sure you want to delete this pivot?"),(()=>{this.env.model.dispatch("REMOVE_PIVOT",{pivotId:this.props.pivotId})}))}onNameChanged(e){const t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);this.env.model.dispatch("UPDATE_PIVOT",{pivotId:this.props.pivotId,pivot:{...t,name:e}})}}class eF{measures;columns;rows;sortedColumn;constructor(e,t){this.measures=e.measures.map((e=>function(e,t){const o=t.fieldName,s="__count"===o?{name:"__count",string:Mo("Count"),type:"integer",aggregator:"sum"}:e[o],i=t.aggregator;return{id:t.id,get displayName(){return t.userDefinedName??s?.string??t.fieldName},userDefinedName:t.userDefinedName,fieldName:o,aggregator:i,type:"__count"===o?"integer":s?.type??"integer",isValid:!(!s&&!t.computedBy),isHidden:t.isHidden,format:t.format,computedBy:t.computedBy,display:t.display}}(t,e))),this.columns=e.columns.map((e=>tF(t,e))),this.rows=e.rows.map((e=>tF(t,e))),this.sortedColumn=e.sortedColumn}getDimension(e){const t=this.columns.find((t=>t.nameWithGranularity===e))||this.rows.find((t=>t.nameWithGranularity===e));if(!t)throw new Ai(Mo("Dimension %s does not exist",e));return t}getMeasure(e){const t=this.measures.find((t=>t.id===e));if(!t)throw new Ai(Mo("Field %s is not a measure",e));return t}}function tF(e,t){const o=e[t.fieldName],s=o?.type??"integer",i=o&&Xl(o)?t.granularity:void 0;return{displayName:o?.string??t.fieldName,nameWithGranularity:t.fieldName+(i?`:${i}`:""),fieldName:t.fieldName,granularity:i,type:s,order:t.order,isValid:!!o}}class oF extends eF{range;constructor(e,t,o){if(super(e,t),e.dataSet){const{sheetId:t,zone:s}=e.dataSet;this.range=o.getRangeFromZone(t,s)}}}class sF{columns;rows;measures;fieldsType;maxIndent;pivotCells={};rowTree;colTree;isSorted=!1;constructor(e,t,o,s){this.columns=e.map((e=>{let t=1;return e.map((e=>(e={...e,offset:t},t+=e.width,e)))})),this.rows=t,this.measures=o,this.fieldsType=s,this.maxIndent=Math.max(...this.rows.map((e=>e.indent))),this.rowTree=ut((()=>this.buildRowsTree())),this.colTree=ut((()=>this.buildColumnsTree()))}getNumberOfDataColumns(){return this.columns.at(-1)?.length||0}getPivotCells(e=!0,t=!0){const o=JSON.stringify({includeTotal:e,includeColumnHeaders:t});if(!this.pivotCells[o]){const s=this.rows.length,i=this.getNumberOfDataColumns();let n=this.columns.length+s,r=1+i;e||1===s||(n-=1),e||i===this.measures.length||(r-=this.measures.length);const a=[],l=t?0:this.columns.length;for(let t=0;t<r;t++){a.push([]);for(let o=l;o<n;o++)(e||o!==n)&&a[t].push(this.getPivotCell(t,o,e))}this.pivotCells[o]=a}return this.pivotCells[o]}getRowTree(){return this.rowTree()}getColTree(){return this.colTree()}isTotalRow(e){return this.rows[e].indent!==this.maxIndent}getPivotCell(e,t,o=!0){const s=this.columns.length;if(e>0&&t===s-1){const o=this.getColHeaderDomain(e,t);if(!o)return iF;const s=o.at(-1)?.value?.toString()||"";return{type:"MEASURE_HEADER",domain:o.slice(0,-1),measure:s}}if(t<=s-1){const o=this.getColHeaderDomain(e,t);return o?{type:"HEADER",domain:o}:iF}if(0===e){const e=t-s;return{type:"HEADER",domain:this.getRowDomain(e)}}{const i=t-s;if(!o&&this.isTotalRow(i))return iF;return{type:"VALUE",domain:[...this.getRowDomain(i),...this.getColDomain(e)],measure:this.getColMeasure(e)}}}getColHeaderDomain(e,t){if(0===e)return;const o=[],s=this.columns[t].find((t=>t.offset===e));if(s){for(let e=0;e<s.fields.length;e++){const t=s.fields[e];if("measure"===t)o.push({type:"char",field:t,value:ec({displayName:"measure",type:"char"},s.values[e])});else{const{fieldName:i,granularity:n}=Yl(t),r=this.fieldsType[i]||"char";o.push({type:r,field:t,value:ec({displayName:i,type:r,granularity:n},s.values[e])})}}return o}}getColDomain(e){const t=this.getColHeaderDomain(e,this.columns.length-1);return t?t.slice(0,-1):[]}getColMeasure(e){const t=this.getColHeaderDomain(e,this.columns.length-1),o=t?.at(-1)?.value;if(null==o)throw new Error("Measure is missing");return o.toString()}getRowDomain(e){const t=[];for(let o=0;o<this.rows[e].fields.length;o++){const s=this.rows[e].fields[o],{fieldName:i,granularity:n}=Yl(s),r=this.fieldsType[i]||"char";t.push({type:r,field:s,value:ec({displayName:i,type:r,granularity:n},this.rows[e].values[o])})}return t}buildRowsTree(){const e=[];let t=0;const o={};o[0]=e;for(const s of this.rows){if(0===s.fields.length||0===s.values.length)return e;const i=s.fields.length-1,n=s.fields[i],{fieldName:r,granularity:a}=Yl(n),l=ec({displayName:r,type:this.fieldsType[r]??"char",granularity:a},s.values[i]);if(i>t){t=i,o[t]=[];const e=o[t-1].at(-1);e&&(e.children=o[t])}t=i;const c={value:l,field:s.fields[i],children:[],type:this.fieldsType[r]||"char",width:0};o[t].push(c)}return e}buildColumnsTree(){const e=[],t=this.columns.at(-2)||[],o={};o[0]=e;for(const e of t)for(let t=0;t<e.fields.length;t++){const s=e.fields[t],{fieldName:i,granularity:n}=Yl(s),r=ec({displayName:i,type:this.fieldsType[i]??"char",granularity:n},e.values[t]),a={value:r,field:e.fields[t],children:[],width:e.width,type:this.fieldsType[i]||"char"};o[t]?.at(-1)?.value!==r&&(o[t+1]=[],a.children=o[t+1],o[t].push(a))}return e}export(){return{cols:this.columns,rows:this.rows,measures:this.measures,fieldsType:this.fieldsType}}sort(e,t,o){if(this.isSorted)return;const s=(e,t)=>{const s=o(e,t).value;return"number"==typeof s?s:-1/0},i=t.domain,n=Tl(this.rowTree(),[],((o,n)=>{const r=s(e,[...o,...i]),a=s(e,[...n,...i]);return"asc"===t.order?r-a:a-r}));this.rowTree=ut(n),this.rows=[...this.rowTreeToRows(n),this.rows[this.rows.length-1]],this.isSorted=!0}rowTreeToRows(e,t){return e.flatMap((e=>{const o={indent:t?t.indent+1:1,fields:[...t?.fields||[],e.field],values:[...t?.values||[],e.value]};return[o,...this.rowTreeToRows(e.children,o)]}))}}const iF={type:"EMPTY"};function nF(e,t){const o=t.measures.filter((e=>!e.isHidden)).map((e=>e.id)),s=aF(e,t.columns,0);lF(s,o.length);const i=function(e,t){const o=t.columns.map((e=>e.nameWithGranularity)),s=o.length,i=t.measures.filter((e=>!e.isHidden)),n=i.length,r=new Array(s).fill(0).map((()=>[]));function a(e,t,i){const n=r[t];for(const r of e){const e=i.concat([r.value]),l={fields:o.slice(0,t+1),values:e,width:r.width,offset:0};n.push(l),t<=s-1&&a(r.children,t+1,e)}}a(e,0,[]);const l=o.length>0,c=[];l&&r[r.length-1].forEach((e=>{i.forEach((t=>{const o={fields:[...e.fields,"measure"],values:[...e.values,t.id],width:1,offset:0};c.push(o)}))}));i.forEach((e=>{const t={fields:["measure"],values:[e.id],width:1,offset:0};c.push(t)})),r.push(c),1===r.length&&r.unshift([]);return r[r.length-2].push({fields:[],values:[],width:n,offset:0}),r}(s,t),n=rF(e,0,t.rows,[],[]);n.push({fields:[],values:[],indent:0});const r={};for(const e of t.columns)r[e.fieldName]=e.type;for(const e of t.rows)r[e.fieldName]=e.type;return new sF(i,n,o,r)}function rF(e,t,o,s,i){if(t>=o.length)return[];const n=o[t],r=n.nameWithGranularity,a=cF(e,n),l=hF(a,n),c=[],h=s.concat(r);for(const e of l){const s=i.concat(e);c.push({fields:h,values:s,indent:t+1});const n=a[e];n&&c.push(...rF(n,t+1,o,h,s))}return c}function aF(e,t,o){if(o>=t.length)return[];const s=t[o],i=t[o].nameWithGranularity,n=cF(e,s);return hF(n,t[o]).map((e=>({value:n[e]?.[0]?.[s.nameWithGranularity]?.value??null,field:i,children:aF(n[e]||[],t,o+1),type:s.type,width:0})))}function lF(e,t){for(const o in e){const s=e[o];0===s.children.length?s.width=t:(lF(s.children,t),s.width=s.children.reduce(((e,t)=>e+t.width),0))}}function cF(e,t){return Object.groupBy(e,function(e){const t=e.nameWithGranularity;return e=>`${e[t]?.value??null}`}(t))}function hF(e,t){return t.order?Object.keys(e).sort(((e,o)=>function(e,t,o){if("null"===t)return"asc"===e.order?1:-1;if("null"===o)return"asc"===e.order?-1:1;if("integer"===e.type||"datetime"===e.type)return"asc"===e.order?Number(t)-Number(o):Number(o)-Number(t);return"asc"===e.order?t.localeCompare(o):o.localeCompare(t)}(t,e,o))):Object.keys(e)}const dF=Symbol("NULL");function uF(e,t,o){const s=e.granularity;if(!s||!(s in gF))throw new Error(`Unknown date granularity: ${s}`);const i="number"==typeof t||"string"==typeof t?t:dF;if(!gF[s].set.has(t)){gF[s].set.add(t);let n=null;if("number"==typeof t||"string"==typeof t){const e=Ki(t,o);switch(s){case"year":n=e.getFullYear();break;case"quarter_number":n=Math.floor(e.getMonth()/3)+1;break;case"month_number":n=e.getMonth()+1;break;case"iso_week_number":n=e.getIsoWeek();break;case"day_of_month":n=e.getDate();break;case"day":n=Math.floor(Ui(t,o));break;case"day_of_week":n=(e.getDay()+7-o.weekStart)%7+1;break;case"hour_number":n=e.getHours();break;case"minute_number":n=e.getMinutes();break;case"second_number":n=e.getSeconds()}}gF[s].values[i]=ec(e,n)}return gF[s].values[i]}const gF={year:{set:new Set,values:{}},quarter_number:{set:new Set,values:{}},month_number:{set:new Set,values:{}},iso_week_number:{set:new Set,values:{}},day_of_month:{set:new Set,values:{}},day:{set:new Set,values:{}},day_of_week:{set:new Set,values:{}},hour_number:{set:new Set,values:{}},minute_number:{set:new Set,values:{}},second_number:{set:new Set,values:{}}};var pF;!function(e){e[e.NONE=0]="NONE",e[e.TABLE=1]="TABLE",e[e.DATA=2]="DATA",e[e.DEFINITION=3]="DEFINITION",e[e.ALL=4]="ALL"}(pF||(pF={}));const mF=new n,fF=["year","quarter_number","month_number","iso_week_number","day_of_month","day","day_of_week"];mF.add("SPREADSHEET",{ui:class{type="SPREADSHEET";getters;_definition;coreDefinition;metaData={fields:{},fieldKeys:[]};dataEntries=[];table;invalidRangeError;needsReevaluation=!0;constructor(e,t){this.getters=t.getters,this.coreDefinition=t.definition}init(e={}){this._definition&&!e.reload||(this.reload(pF.ALL),this.needsReevaluation=!1)}reload(e){e===pF.ALL&&(this.metaData=this.loadMetaData()),e>=pF.DEFINITION&&(this._definition=this.loadRuntimeDefinition()),e>=pF.DATA&&(this.dataEntries=this.loadData()),e>=pF.TABLE&&(this.table=void 0)}onDefinitionChange(e){const t=this.coreDefinition;if(this.coreDefinition=e,this._definition){const o=Math.max(this.computeShouldReload(t,e),pF.NONE);this.reload(o)}}computeShouldReload(e,t){return mt(e.dataSet,t.dataSet)?pF.DEFINITION:pF.ALL}get isInvalidRange(){return!!this.invalidRangeError}get invalidRangeMessage(){return this.invalidRangeError?.message}get definition(){if(this._definition||this.init(),!this._definition)throw new Error("Pivot definition should be defined at this point.");return this._definition}isValid(){if(this.invalidRangeError||!this.definition)return!1;for(const e of this.definition.measures)if(!e.isValid)return!1;for(const e of this.definition.columns)if(!e.isValid)return!1;for(const e of this.definition.rows)if(!e.isValid)return!1;return!0}assertIsValid({throwOnError:e}){if(!this.isValid()){if(e)throw this.invalidRangeError?this.invalidRangeError:new Ai(Mo("At least one measure and/or dimension is not correct."));return{value:Ri.GenericError,message:this.invalidRangeError?.message??Mo("At least one measure and/or dimension is not correct.")}}}areDomainArgsFieldsValid(e){let t=e.filter(((e,t)=>t%2==0)).map(Zi);return t.length&&"measure"===t.at(-1)&&(t=t.slice(0,-1)),Jl(t,this.definition)}parseArgsToPivotDomain(e){const t=[];for(let o=0;o<e.length-1;o+=2){const s=Zi(e[o]),i=this.getTypeOfDimension(s),n="measure"===s?Zi(e[o+1]):ec(this.getDimension(s),e[o+1]);t.push({field:s,value:n,type:i})}return t}markAsDirtyForEvaluation(){this.needsReevaluation=!0}getMeasure(e){return this.definition.getMeasure(e)}getPivotMeasureValue(e){return{value:this.getMeasure(e).displayName}}getPivotHeaderValueAndFormat(e){const t=e.at(-1);if(!t)return{value:Mo("Total")};const o=this.getDimension(t.field),s=this.filterDataEntriesFromDomain(this.dataEntries,e),i=s[0]?.[o.nameWithGranularity];if("datetime"===o.type){return _l(o.granularity).toValueAndFormat(t.value,this.getters.getLocale())}return i?null===i.value?{value:Mo("(Undefined)")}:{value:i.value,format:i.format}:{value:""}}getPivotCellValueAndFormat(e,t){const o=this.filterDataEntriesFromDomain(this.dataEntries,t);if(0===o.length)return{value:""};const s=this.getMeasure(e),i=o.map((e=>e[s.fieldName])).filter(at),n=i.filter((e=>e.type!==ri.empty)),r=s.aggregator,a=Gl[r];if(!a)throw new Error(`Aggregator ${r} does not exist`);try{const e=a([i],this.getters.getLocale());return 0===n.length?{...e,value:""}:e}catch(e){return Zb(e,r.toUpperCase())}}getPossibleFieldValues(e){const t=[],o=cF(this.dataEntries,e),s=hF(o,e);for(const i of s)t.push({value:o[i]?.[0]?.[e.nameWithGranularity]?.value??"",label:o[i]?.[0]?.[e.nameWithGranularity]?.formattedValue||""});return t}getTableStructure(){if(!this.isValid())throw new Error("Pivot is not valid !");return this.table||(this.table=nF(this.dataEntries,this.definition)),this.table}getFields(){return this.metaData.fields}get fields(){return this.getFields()}loadMetaData(){if(this.invalidRangeError=void 0,!this.coreDefinition.dataSet)return this.invalidRangeError=new Ai(Mo("The pivot cannot be created because the dataset is missing.")),{fields:{},fieldKeys:[]};{const{zone:e,sheetId:t}=this.coreDefinition.dataSet,o=this.getters.getRangeFromZone(t,e);try{return this.extractFieldsFromRange(o)}catch(e){return this.invalidRangeError=e,{fields:{},fieldKeys:[]}}}}loadRuntimeDefinition(){return new oF(this.coreDefinition,this.fields,this.getters)}loadData(){const e=this._definition?.range;return this.isValid()&&e?this.extractDataEntriesFromRange(e):[]}getTypeOfDimension(e){if("measure"===e)return"char";const{fieldName:t}=Yl(e),o=this.fields[t]?.type;if(!o)throw new Error(`Field ${t} does not exist`);return o}filterDataEntriesFromDomain(e,t){return t.reduce(((e,t)=>this.filterDataEntriesFromDomainNode(e,t)),e)}filterDataEntriesFromDomainNode(e,t){const{field:o,value:s}=t,{nameWithGranularity:i}=this.getDimension(o);return e.filter((e=>e[i]?.value===s))}getDimension(e){return this.definition.getDimension(e)}getTypeFromZone(e,t){const o=this.getters.getEvaluatedCellsInZone(e,t).filter((e=>e.type!==ri.empty));return 0===o.length?"integer":o.every((e=>e.format&&ar(e.format)))?"datetime":o.every((e=>e.type===ri.boolean))?"boolean":o.some((e=>e.type===ri.text))?"char":"integer"}assertCellIsValidField(e,t,o){if(o.type===ri.error)throw new Ai(Mo("The pivot cannot be created because cell %s contains an error",Co(e,t)));if(o.type===ri.empty||""===o.value)throw new Ai(Mo("The pivot cannot be created because cell %s is empty",Co(e,t)));if("__count"===o.value)throw new Ai(Mo("The pivot cannot be created because cell %s contains a reserved value",Co(e,t)))}extractFieldsFromRange(e){const t={},o=[],s=e.sheetId,i=e.zone.top;for(let n=e.zone.left;n<=e.zone.right;n++){const r=this.getters.getEvaluatedCell({sheetId:s,col:n,row:i});this.assertCellIsValidField(n,i,r);const a=r.value?.toString();if(a){const i=this.getTypeFromZone(s,{top:e.zone.top+1,left:n,bottom:e.zone.bottom,right:n}),r=this.findName(a,t);t[r]={name:r,type:i,string:r,aggregator:"integer"===i?"sum":"count"},o.push(r)}}return{fields:t,fieldKeys:o}}findName(e,t){return Nt(e,Object.keys(t),{compute:(e,t)=>`${e}${t}`,start:2})}extractDataEntriesFromRange(e){const t=[];for(let o=e.zone.top+1;o<=e.zone.bottom;o++){const s={top:o,bottom:o,left:e.zone.left,right:e.zone.right},i=this.getters.getEvaluatedCellsInZone(e.sheetId,s),n={};for(const e in i){const t=i[e],o=this.fields[this.metaData.fieldKeys[e]];if(!o)throw new Error(`Field ${this.metaData.fieldKeys[e]} does not exist`);""===t.value?n[o.name]={value:null,type:ri.empty,formattedValue:""}:n[o.name]=t}n.__count={value:1,type:ri.number,formattedValue:"1"},t.push(n)}const o=this.definition.columns.concat(this.definition.rows).filter((e=>"datetime"===e.type));if(o.length){const e=this.getters.getLocale();for(const s of t)for(const t of o){const o=uF(t,s[t.fieldName]?.value||null,this.getters.getLocale()),i=_l(t.granularity),{format:n,value:r}=i.toValueAndFormat(o,e);s[t.nameWithGranularity]={value:o,type:s[t.fieldName]?.type||ri.empty,format:s[t.fieldName]?.format,formattedValue:Qn(r,{locale:e,format:n})}}}return t}},definition:oF,externalData:!1,onIterationEndEvaluation:e=>e.markAsDirtyForEvaluation(),dateGranularities:[...fF],datetimeGranularities:[...fF,"hour_number","minute_number","second_number"],isMeasureCandidate:e=>"boolean"!==e.type,isGroupable:()=>!0});class vF extends _c{pivotId;mutators=["reset","deferUpdates","applyUpdate","discardPendingUpdate","update"];updatesAreDeferred;draft=null;notification=this.get(Qb);alreadyNotified=!1;constructor(e,t){super(e),this.pivotId=t,this.updatesAreDeferred=this.getters.getPivotCoreDefinition(this.pivotId).deferUpdates??!1}handle(e){if("UPDATE_PIVOT"===e.type)e.pivotId===this.pivotId&&this.getters.getPivot(this.pivotId).init()}get fields(){return this.pivot.getFields()}get pivot(){return this.getters.getPivot(this.pivotId)}get definition(){const e=mF.get(this.pivot.type).definition;return this.draft?new e(this.draft,this.fields,this.getters):this.pivot.definition}get isDirty(){return!!this.draft}get measureFields(){const e=[{name:"__count",string:Mo("Count"),type:"integer",aggregator:"sum"}],t=this.fields;for(const o in t){const s=t[o];s&&(mF.get(this.pivot.type).isMeasureCandidate(s)&&e.push(s))}return e.sort(((e,t)=>e.string.localeCompare(t.string)))}get unusedGroupableFields(){const e=[],t=this.fields;for(const o in t){const s=t[o];s&&(mF.get(this.pivot.type).isGroupable(s)&&e.push(s))}const{columns:o,rows:s,measures:i}=this.definition,n=i.concat(s).concat(o).map((e=>e.fieldName)),r=this.unusedGranularities;return e.filter((e=>Xl(e)?!n.includes(e.name)||r[e.name].size>0:!n.includes(e.name))).sort(((e,t)=>e.string.localeCompare(t.string)))}get datetimeGranularities(){return mF.get(this.pivot.type).datetimeGranularities}get dateGranularities(){return mF.get(this.pivot.type).dateGranularities}get unusedGranularities(){return this.getUnusedGranularities(this.fields,this.draft??this.getters.getPivotCoreDefinition(this.pivotId))}reset(e){this.pivotId=e,this.updatesAreDeferred=!0,this.draft=null}deferUpdates(e){!1===e&&this.draft?(this.draft.deferUpdates=!1,this.applyUpdate()):this.update({deferUpdates:e}),this.updatesAreDeferred=e}applyUpdate(){if(this.draft&&(this.model.dispatch("UPDATE_PIVOT",{pivotId:this.pivotId,pivot:this.draft}),this.draft=null,!this.alreadyNotified&&!this.isDynamicPivotInViewport()&&this.isStaticPivotInViewport())){const e=`=PIVOT(${this.getters.getPivotFormulaId(this.pivotId)})`;this.alreadyNotified=!0,this.notification.notifyUser({type:"info",text:Mo("Pivot updates only work with dynamic pivot tables. Use %s or re-insert the static pivot from the Data menu.",e),sticky:!1})}}discardPendingUpdate(){this.draft=null}update(e){const t=this.getters.getPivotCoreDefinition(this.pivotId),o={...t,...this.draft,...e},s={...o,columns:o.columns.map((e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity}))),rows:o.rows.map((e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity}))),measures:o.measures.map((e=>({id:e.id,fieldName:e.fieldName,aggregator:e.aggregator,userDefinedName:e.userDefinedName,computedBy:e.computedBy,isHidden:e.isHidden,format:e.format,display:e.display}))),sortedColumn:this.shouldKeepSortedColumn(o)?o.sortedColumn:void 0};if(!this.draft&&mt(t,s))return;const i=this.addDefaultDateTimeGranularity(this.fields,s);this.draft=i,this.updatesAreDeferred||this.applyUpdate()}isDynamicPivotInViewport(){for(const e of this.getters.getVisibleCellPositions()){if(this.getters.isSpillPivotFormula(e))return!0}return!1}isStaticPivotInViewport(){for(const e of this.getters.getVisibleCellPositions()){const t=this.getters.getCell(e);if(t?.isFormula){const e=ES(t.compiledFormula.tokens);if(e&&"PIVOT"!==e.functionName)return!0}}return!1}addDefaultDateTimeGranularity(e,t){const{columns:o,rows:s}=t,i=Be(o),n=Be(s),r=this.getUnusedGranularities(e,t);for(const t of i.concat(n)){const o=e[t.fieldName]?.type;if(("date"===o||"datetime"===o)&&!t.granularity){const e=r[t.fieldName]?.values().next().value||"year";r[t.fieldName]?.delete(e),t.granularity=e}}return{...t,columns:i,rows:n}}getUnusedGranularities(e,t){const{columns:o,rows:s,measures:i}=t,n=o.concat(s).concat(i).filter((t=>{const o=e[t.fieldName]?.type;return"date"===o||"datetime"===o})),r={};for(const t of n)r[t.fieldName]=new Set("date"===e[t.fieldName]?.type?this.dateGranularities:this.datetimeGranularities);for(const e of n)r[e.fieldName].delete(e.granularity);return r}shouldKeepSortedColumn(e){const{sortedColumn:t}=e;if(!t)return!0;const o=this.getters.getPivotCoreDefinition(this.pivotId);return e.measures.find((e=>e.id===t.measure))&&mt(o.columns,e.columns)}}class bF extends t.Component{static template="o-spreadsheet-PivotSpreadsheetSidePanel";static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:JO,Section:X_,SelectionInput:lD,Checkbox:HI,PivotDeferUpdate:$O,PivotTitleSection:QO};store;state;pivotSidePanelRef=t.useRef("pivotSidePanel");setup(){this.store=wc(vF,this.props.pivotId),this.state=t.useState({range:void 0,rangeHasChanged:!1})}get shouldDisplayInvalidRangeError(){return(!this.store.isDirty||!this.state.rangeHasChanged)&&this.pivot.isInvalidRange}get ranges(){return this.state.range?[this.state.range]:this.definition.range?[this.env.model.getters.getRangeString(this.definition.range,"forceSheetReference")]:[]}get pivot(){return this.store.pivot}get definition(){return this.store.definition}getScrollableContainerEl(){return this.pivotSidePanelRef.el}onSelectionChanged(e){this.state.rangeHasChanged=!0,this.state.range=e[0]}onSelectionConfirmed(){if(this.state.range){const e=this.env.model.getters.getRangeFromSheetXC(this.env.model.getters.getActiveSheetId(),this.state.range);if(e.invalidSheetName||e.invalidXc)return;const t={sheetId:e.sheetId,zone:e.zone};this.store.update({dataSet:t}),this.store.applyUpdate()}}flipAxis(){const{rows:e,columns:t}=this.definition;this.onDimensionsUpdated({rows:t,columns:e})}onDimensionsUpdated(e){this.store.update(e)}}const SF=new n;SF.add("SPREADSHEET",{editor:bF});class yF extends t.Component{static template="o-spreadsheet-PivotSidePanel";static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:JO,Section:X_};setup(){dO(this)}get sidePanelEditor(){const e=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);if(!e)throw new Error("pivotId does not correspond to a pivot.");return SF.get(e.type).editor}get highlights(){return Z_(this.env.model.getters,this.props.pivotId)}}Pc`
|
|
1278
|
+
`;class QO extends t.Component{static template="o-spreadsheet-PivotLayoutConfigurator";static components={AddDimensionButton:GO,PivotDimension:jO,PivotDimensionOrder:XO,PivotDimensionGranularity:YO,PivotMeasureEditor:KO,PivotSortSection:JO};static props={definition:Object,onDimensionsUpdated:Function,unusedGroupableFields:Array,measureFields:Array,unusedGranularities:Object,dateGranularities:Array,datetimeGranularities:Array,getScrollableContainerEl:{type:Function,optional:!0},pivotId:String};dimensionsRef=t.useRef("pivot-dimensions");dragAndDrop=Q_();AGGREGATORS=Wl;composerFocus;isDateOrDatetimeField=Xl;setup(){this.composerFocus=Cc(Oc)}startDragAndDrop(e,t){if(0!==t.button||"SELECT"===t.target.tagName)return;const o=this.getDimensionElementsRects(),s=this.props.definition,{columns:i,rows:n}=s,r=[...i.map((e=>e.nameWithGranularity)),"__rows_title__",...n.map((e=>e.nameWithGranularity))],a=i.concat(n),l=r.map(((e,t)=>({id:e,size:o[t+1].height,position:o[t+1].y})));this.dragAndDrop.start("vertical",{draggedItemId:e.nameWithGranularity,initialMousePosition:t.clientY,items:l,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{const o=r.findIndex((t=>t===e));if(o===t)return;const s=[...r];s.splice(o,1),s.splice(t,0,e);const i=s.slice(0,s.indexOf("__rows_title__")),n=s.slice(s.indexOf("__rows_title__")+1);this.props.onDimensionsUpdated({columns:i.map((e=>a.find((t=>t.nameWithGranularity===e)))).filter(at),rows:n.map((e=>a.find((t=>t.nameWithGranularity===e)))).filter(at)})}})}getGranularitiesFor(e){return Xl(e)?"date"===e.type?this.props.dateGranularities:this.props.datetimeGranularities:[]}startDragAndDropMeasures(e,t){if(0!==t.button||"SELECT"===t.target.tagName||"INPUT"===t.target.tagName||"inactive"!==this.composerFocus.focusMode)return;const o=this.getDimensionElementsRects(),s=this.props.definition,{measures:i,columns:n,rows:r}=s,a=i.map((e=>e.id)),l=3+n.length+r.length,c=a.map(((e,t)=>({id:e,size:o[t+l].height,position:o[t+l].y})));this.dragAndDrop.start("vertical",{draggedItemId:e.id,initialMousePosition:t.clientY,items:c,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{const o=a.findIndex((t=>t===e));if(o===t)return;const s=[...a];s.splice(o,1),s.splice(t,0,e),this.props.onDimensionsUpdated({measures:s.map((e=>i.find((t=>t.id===e)))).filter(at)})}})}getDimensionElementsRects(){return Array.from(this.dimensionsRef.el.children).map((e=>{const t=getComputedStyle(e),o=e.getBoundingClientRect();return{x:o.x,y:o.y,width:o.width+parseInt(t.marginLeft||"0")+parseInt(t.marginRight||"0"),height:o.height+parseInt(t.marginTop||"0")+parseInt(t.marginBottom||"0")}}))}removeDimension(e){const{columns:t,rows:o}=this.props.definition;this.props.onDimensionsUpdated({columns:t.filter((t=>t.nameWithGranularity!==e.nameWithGranularity)),rows:o.filter((t=>t.nameWithGranularity!==e.nameWithGranularity))})}removeMeasureDimension(e){const{measures:t}=this.props.definition;this.props.onDimensionsUpdated({measures:t.filter((t=>t.id!==e.id))})}addColumnDimension(e){const{columns:t}=this.props.definition;this.props.onDimensionsUpdated({columns:t.concat([{fieldName:e,order:"asc"}])})}addRowDimension(e){const{rows:t}=this.props.definition;this.props.onDimensionsUpdated({rows:t.concat([{fieldName:e,order:"asc"}])})}addMeasureDimension(e){const{measures:t}=this.props.definition,o=this.getDefaultMeasureAggregator(e);this.props.onDimensionsUpdated({measures:t.concat([{id:this.getMeasureId(e,o),fieldName:e,aggregator:o}])})}updateMeasure(e,t){const{measures:o}=this.props.definition,s={measures:o.map((o=>o.id===e.id?t:o))};this.props.definition.sortedColumn?.measure===e.id&&(s.sortedColumn={...this.props.definition.sortedColumn,measure:t.id}),this.props.onDimensionsUpdated(s)}getMeasureId(e,t){const o=e+(t?`:${t}`:"");let s=o,i=2;for(;this.props.definition.measures.some((e=>e.id===s));)s=`${o}:${i}`,i++;return s}getDefaultMeasureAggregator(e){const t=this.props.measureFields.find((t=>t.name===e));return t?.aggregator?t.aggregator:"count"}addCalculatedMeasure(){const{measures:e}=this.props.definition,t=this.env.model.getters.generateNewCalculatedMeasureName(e);this.props.onDimensionsUpdated({measures:e.concat([{id:this.getMeasureId(t),fieldName:t,aggregator:"sum",computedBy:{sheetId:this.env.model.getters.getActiveSheetId(),formula:"=0"}}])})}updateOrder(e,t){const{rows:o,columns:s}=this.props.definition;this.props.onDimensionsUpdated({rows:o.map((o=>o.nameWithGranularity===e.nameWithGranularity?{...o,order:t||void 0}:o)),columns:s.map((o=>o.nameWithGranularity===e.nameWithGranularity?{...o,order:t||void 0}:o))})}updateGranularity(e,t){const{rows:o,columns:s}=this.props.definition;this.props.onDimensionsUpdated({rows:o.map((o=>o.nameWithGranularity===e.nameWithGranularity?{...o,granularity:t}:o)),columns:s.map((o=>o.nameWithGranularity===e.nameWithGranularity?{...o,granularity:t}:o))})}getMeasureDescription(e){const t=e.display;if(!t||"no_calculations"===t.type)return"";const o=this.env.model.getters.getPivot(this.props.pivotId),s=[...o.definition.columns,...o.definition.rows].find((e=>e.nameWithGranularity===t.fieldNameWithGranularity)),i=s?rc(s):"";return wE.descriptions[t.type](i)}}class eF extends t.Component{static template="o-spreadsheet-PivotTitleSection";static components={CogWheelMenu:ZO,Section:X_,TextInput:qO};static props={pivotId:String,flipAxis:Function};get cogWheelMenuItems(){return[{name:Mo("Flip axes"),icon:"o-spreadsheet-Icon.EXCHANGE",execute:this.props.flipAxis},{name:Mo("Duplicate"),icon:"o-spreadsheet-Icon.COPY",execute:()=>this.duplicatePivot()},{name:Mo("Delete"),icon:"o-spreadsheet-Icon.TRASH",execute:()=>this.delete()}]}get name(){return this.env.model.getters.getPivotName(this.props.pivotId)}get displayName(){return this.env.model.getters.getPivotDisplayName(this.props.pivotId)}duplicatePivot(){const e=this.env.model.uuidGenerator.smallUuid(),t=this.env.model.uuidGenerator.smallUuid(),o=this.env.model.dispatch("DUPLICATE_PIVOT_IN_NEW_SHEET",{pivotId:this.props.pivotId,newPivotId:e,newSheetId:t});let s;s=o.isSuccessful?Mo("Pivot duplicated."):o.isCancelledBecause("PivotInError")?Mo("Cannot duplicate a pivot in error."):Mo("Pivot duplication failed.");const i=o.isSuccessful?"success":"danger";this.env.notifyUser({text:s,sticky:!1,type:i}),o.isSuccessful&&this.env.openSidePanel("PivotSidePanel",{pivotId:e})}delete(){this.env.askConfirmation(Mo("Are you sure you want to delete this pivot?"),(()=>{this.env.model.dispatch("REMOVE_PIVOT",{pivotId:this.props.pivotId})}))}onNameChanged(e){const t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);this.env.model.dispatch("UPDATE_PIVOT",{pivotId:this.props.pivotId,pivot:{...t,name:e}})}}class tF{measures;columns;rows;sortedColumn;constructor(e,t){this.measures=e.measures.map((e=>function(e,t){const o=t.fieldName,s="__count"===o?{name:"__count",string:Mo("Count"),type:"integer",aggregator:"sum"}:e[o],i=t.aggregator;return{id:t.id,get displayName(){return t.userDefinedName??s?.string??t.fieldName},userDefinedName:t.userDefinedName,fieldName:o,aggregator:i,type:"__count"===o?"integer":s?.type??"integer",isValid:!(!s&&!t.computedBy),isHidden:t.isHidden,format:t.format,computedBy:t.computedBy,display:t.display}}(t,e))),this.columns=e.columns.map((e=>oF(t,e))),this.rows=e.rows.map((e=>oF(t,e))),this.sortedColumn=e.sortedColumn}getDimension(e){const t=this.columns.find((t=>t.nameWithGranularity===e))||this.rows.find((t=>t.nameWithGranularity===e));if(!t)throw new Ai(Mo("Dimension %s does not exist",e));return t}getMeasure(e){const t=this.measures.find((t=>t.id===e));if(!t)throw new Ai(Mo("Field %s is not a measure",e));return t}}function oF(e,t){const o=e[t.fieldName],s=o?.type??"integer",i=o&&Xl(o)?t.granularity:void 0;return{displayName:o?.string??t.fieldName,nameWithGranularity:t.fieldName+(i?`:${i}`:""),fieldName:t.fieldName,granularity:i,type:s,order:t.order,isValid:!!o}}class sF extends tF{range;constructor(e,t,o){if(super(e,t),e.dataSet){const{sheetId:t,zone:s}=e.dataSet;this.range=o.getRangeFromZone(t,s)}}}class iF{columns;rows;measures;fieldsType;maxIndent;pivotCells={};rowTree;colTree;isSorted=!1;constructor(e,t,o,s){this.columns=e.map((e=>{let t=1;return e.map((e=>(e={...e,offset:t},t+=e.width,e)))})),this.rows=t,this.measures=o,this.fieldsType=s,this.maxIndent=Math.max(...this.rows.map((e=>e.indent))),this.rowTree=ut((()=>this.buildRowsTree())),this.colTree=ut((()=>this.buildColumnsTree()))}getNumberOfDataColumns(){return this.columns.at(-1)?.length||0}getPivotCells(e=!0,t=!0){const o=JSON.stringify({includeTotal:e,includeColumnHeaders:t});if(!this.pivotCells[o]){const s=this.rows.length,i=this.getNumberOfDataColumns();let n=this.columns.length+s,r=1+i;e||1===s||(n-=1),e||i===this.measures.length||(r-=this.measures.length);const a=[],l=t?0:this.columns.length;for(let t=0;t<r;t++){a.push([]);for(let o=l;o<n;o++)(e||o!==n)&&a[t].push(this.getPivotCell(t,o,e))}this.pivotCells[o]=a}return this.pivotCells[o]}getRowTree(){return this.rowTree()}getColTree(){return this.colTree()}isTotalRow(e){return this.rows[e].indent!==this.maxIndent}getPivotCell(e,t,o=!0){const s=this.columns.length;if(e>0&&t===s-1){const o=this.getColHeaderDomain(e,t);if(!o)return nF;const s=o.at(-1)?.value?.toString()||"";return{type:"MEASURE_HEADER",domain:o.slice(0,-1),measure:s}}if(t<=s-1){const o=this.getColHeaderDomain(e,t);return o?{type:"HEADER",domain:o}:nF}if(0===e){const e=t-s;return{type:"HEADER",domain:this.getRowDomain(e)}}{const i=t-s;if(!o&&this.isTotalRow(i))return nF;return{type:"VALUE",domain:[...this.getRowDomain(i),...this.getColDomain(e)],measure:this.getColMeasure(e)}}}getColHeaderDomain(e,t){if(0===e)return;const o=[],s=this.columns[t].find((t=>t.offset===e));if(s){for(let e=0;e<s.fields.length;e++){const t=s.fields[e];if("measure"===t)o.push({type:"char",field:t,value:ec({displayName:"measure",type:"char"},s.values[e])});else{const{fieldName:i,granularity:n}=Yl(t),r=this.fieldsType[i]||"char";o.push({type:r,field:t,value:ec({displayName:i,type:r,granularity:n},s.values[e])})}}return o}}getColDomain(e){const t=this.getColHeaderDomain(e,this.columns.length-1);return t?t.slice(0,-1):[]}getColMeasure(e){const t=this.getColHeaderDomain(e,this.columns.length-1),o=t?.at(-1)?.value;if(null==o)throw new Error("Measure is missing");return o.toString()}getRowDomain(e){const t=[];for(let o=0;o<this.rows[e].fields.length;o++){const s=this.rows[e].fields[o],{fieldName:i,granularity:n}=Yl(s),r=this.fieldsType[i]||"char";t.push({type:r,field:s,value:ec({displayName:i,type:r,granularity:n},this.rows[e].values[o])})}return t}buildRowsTree(){const e=[];let t=0;const o={};o[0]=e;for(const s of this.rows){if(0===s.fields.length||0===s.values.length)return e;const i=s.fields.length-1,n=s.fields[i],{fieldName:r,granularity:a}=Yl(n),l=ec({displayName:r,type:this.fieldsType[r]??"char",granularity:a},s.values[i]);if(i>t){t=i,o[t]=[];const e=o[t-1].at(-1);e&&(e.children=o[t])}t=i;const c={value:l,field:s.fields[i],children:[],type:this.fieldsType[r]||"char",width:0};o[t].push(c)}return e}buildColumnsTree(){const e=[],t=this.columns.at(-2)||[],o={};o[0]=e;for(const e of t)for(let t=0;t<e.fields.length;t++){const s=e.fields[t],{fieldName:i,granularity:n}=Yl(s),r=ec({displayName:i,type:this.fieldsType[i]??"char",granularity:n},e.values[t]),a={value:r,field:e.fields[t],children:[],width:e.width,type:this.fieldsType[i]||"char"};o[t]?.at(-1)?.value!==r&&(o[t+1]=[],a.children=o[t+1],o[t].push(a))}return e}export(){return{cols:this.columns,rows:this.rows,measures:this.measures,fieldsType:this.fieldsType}}sort(e,t,o){if(this.isSorted)return;const s=(e,t)=>{const s=o(e,t).value;return"number"==typeof s?s:-1/0},i=t.domain,n=Tl(this.rowTree(),[],((o,n)=>{const r=s(e,[...o,...i]),a=s(e,[...n,...i]);return"asc"===t.order?r-a:a-r}));this.rowTree=ut(n),this.rows=[...this.rowTreeToRows(n),this.rows[this.rows.length-1]],this.isSorted=!0}rowTreeToRows(e,t){return e.flatMap((e=>{const o={indent:t?t.indent+1:1,fields:[...t?.fields||[],e.field],values:[...t?.values||[],e.value]};return[o,...this.rowTreeToRows(e.children,o)]}))}}const nF={type:"EMPTY"};function rF(e,t){const o=t.measures.filter((e=>!e.isHidden)).map((e=>e.id)),s=lF(e,t.columns,0);cF(s,o.length);const i=function(e,t){const o=t.columns.map((e=>e.nameWithGranularity)),s=o.length,i=t.measures.filter((e=>!e.isHidden)),n=i.length,r=new Array(s).fill(0).map((()=>[]));function a(e,t,i){const n=r[t];for(const r of e){const e=i.concat([r.value]),l={fields:o.slice(0,t+1),values:e,width:r.width,offset:0};n.push(l),t<=s-1&&a(r.children,t+1,e)}}a(e,0,[]);const l=o.length>0,c=[];l&&r[r.length-1].forEach((e=>{i.forEach((t=>{const o={fields:[...e.fields,"measure"],values:[...e.values,t.id],width:1,offset:0};c.push(o)}))}));i.forEach((e=>{const t={fields:["measure"],values:[e.id],width:1,offset:0};c.push(t)})),r.push(c),1===r.length&&r.unshift([]);return r[r.length-2].push({fields:[],values:[],width:n,offset:0}),r}(s,t),n=aF(e,0,t.rows,[],[]);n.push({fields:[],values:[],indent:0});const r={};for(const e of t.columns)r[e.fieldName]=e.type;for(const e of t.rows)r[e.fieldName]=e.type;return new iF(i,n,o,r)}function aF(e,t,o,s,i){if(t>=o.length)return[];const n=o[t],r=n.nameWithGranularity,a=hF(e,n),l=dF(a,n),c=[],h=s.concat(r);for(const e of l){const s=i.concat(e);c.push({fields:h,values:s,indent:t+1});const n=a[e];n&&c.push(...aF(n,t+1,o,h,s))}return c}function lF(e,t,o){if(o>=t.length)return[];const s=t[o],i=t[o].nameWithGranularity,n=hF(e,s);return dF(n,t[o]).map((e=>({value:n[e]?.[0]?.[s.nameWithGranularity]?.value??null,field:i,children:lF(n[e]||[],t,o+1),type:s.type,width:0})))}function cF(e,t){for(const o in e){const s=e[o];0===s.children.length?s.width=t:(cF(s.children,t),s.width=s.children.reduce(((e,t)=>e+t.width),0))}}function hF(e,t){return Object.groupBy(e,function(e){const t=e.nameWithGranularity;return e=>`${e[t]?.value??null}`}(t))}function dF(e,t){return t.order?Object.keys(e).sort(((e,o)=>function(e,t,o){if("null"===t)return"asc"===e.order?1:-1;if("null"===o)return"asc"===e.order?-1:1;if("integer"===e.type||"datetime"===e.type)return"asc"===e.order?Number(t)-Number(o):Number(o)-Number(t);return"asc"===e.order?t.localeCompare(o):o.localeCompare(t)}(t,e,o))):Object.keys(e)}const uF=Symbol("NULL");function gF(e,t,o){const s=e.granularity;if(!s||!(s in pF))throw new Error(`Unknown date granularity: ${s}`);const i="number"==typeof t||"string"==typeof t?t:uF;if(!pF[s].set.has(t)){pF[s].set.add(t);let n=null;if("number"==typeof t||"string"==typeof t){const e=Ki(t,o);switch(s){case"year":n=e.getFullYear();break;case"quarter_number":n=Math.floor(e.getMonth()/3)+1;break;case"month_number":n=e.getMonth()+1;break;case"iso_week_number":n=e.getIsoWeek();break;case"day_of_month":n=e.getDate();break;case"day":n=Math.floor(Ui(t,o));break;case"day_of_week":n=(e.getDay()+7-o.weekStart)%7+1;break;case"hour_number":n=e.getHours();break;case"minute_number":n=e.getMinutes();break;case"second_number":n=e.getSeconds()}}pF[s].values[i]=ec(e,n)}return pF[s].values[i]}const pF={year:{set:new Set,values:{}},quarter_number:{set:new Set,values:{}},month_number:{set:new Set,values:{}},iso_week_number:{set:new Set,values:{}},day_of_month:{set:new Set,values:{}},day:{set:new Set,values:{}},day_of_week:{set:new Set,values:{}},hour_number:{set:new Set,values:{}},minute_number:{set:new Set,values:{}},second_number:{set:new Set,values:{}}};var mF;!function(e){e[e.NONE=0]="NONE",e[e.TABLE=1]="TABLE",e[e.DATA=2]="DATA",e[e.DEFINITION=3]="DEFINITION",e[e.ALL=4]="ALL"}(mF||(mF={}));const fF=new n,vF=["year","quarter_number","month_number","iso_week_number","day_of_month","day","day_of_week"];fF.add("SPREADSHEET",{ui:class{type="SPREADSHEET";getters;_definition;coreDefinition;metaData={fields:{},fieldKeys:[]};dataEntries=[];table;invalidRangeError;needsReevaluation=!0;constructor(e,t){this.getters=t.getters,this.coreDefinition=t.definition}init(e={}){this._definition&&!e.reload||(this.reload(mF.ALL),this.needsReevaluation=!1)}reload(e){e===mF.ALL&&(this.metaData=this.loadMetaData()),e>=mF.DEFINITION&&(this._definition=this.loadRuntimeDefinition()),e>=mF.DATA&&(this.dataEntries=this.loadData()),e>=mF.TABLE&&(this.table=void 0)}onDefinitionChange(e){const t=this.coreDefinition;if(this.coreDefinition=e,this._definition){const o=Math.max(this.computeShouldReload(t,e),mF.NONE);this.reload(o)}}computeShouldReload(e,t){return mt(e.dataSet,t.dataSet)?mF.DEFINITION:mF.ALL}get isInvalidRange(){return!!this.invalidRangeError}get invalidRangeMessage(){return this.invalidRangeError?.message}get definition(){if(this._definition||this.init(),!this._definition)throw new Error("Pivot definition should be defined at this point.");return this._definition}isValid(){if(this.invalidRangeError||!this.definition)return!1;for(const e of this.definition.measures)if(!e.isValid)return!1;for(const e of this.definition.columns)if(!e.isValid)return!1;for(const e of this.definition.rows)if(!e.isValid)return!1;return!0}assertIsValid({throwOnError:e}){if(!this.isValid()){if(e)throw this.invalidRangeError?this.invalidRangeError:new Ai(Mo("At least one measure and/or dimension is not correct."));return{value:Ri.GenericError,message:this.invalidRangeError?.message??Mo("At least one measure and/or dimension is not correct.")}}}areDomainArgsFieldsValid(e){let t=e.filter(((e,t)=>t%2==0)).map(Zi);return t.length&&"measure"===t.at(-1)&&(t=t.slice(0,-1)),Jl(t,this.definition)}parseArgsToPivotDomain(e){const t=[];for(let o=0;o<e.length-1;o+=2){const s=Zi(e[o]),i=this.getTypeOfDimension(s),n="measure"===s?Zi(e[o+1]):ec(this.getDimension(s),e[o+1]);t.push({field:s,value:n,type:i})}return t}markAsDirtyForEvaluation(){this.needsReevaluation=!0}getMeasure(e){return this.definition.getMeasure(e)}getPivotMeasureValue(e){return{value:this.getMeasure(e).displayName}}getPivotHeaderValueAndFormat(e){const t=e.at(-1);if(!t)return{value:Mo("Total")};const o=this.getDimension(t.field),s=this.filterDataEntriesFromDomain(this.dataEntries,e),i=s[0]?.[o.nameWithGranularity];if("datetime"===o.type){return _l(o.granularity).toValueAndFormat(t.value,this.getters.getLocale())}return i?null===i.value?{value:Mo("(Undefined)")}:{value:i.value,format:i.format}:{value:""}}getPivotCellValueAndFormat(e,t){const o=this.filterDataEntriesFromDomain(this.dataEntries,t);if(0===o.length)return{value:""};const s=this.getMeasure(e),i=o.map((e=>e[s.fieldName])).filter(at),n=i.filter((e=>e.type!==ri.empty)),r=s.aggregator,a=Gl[r];if(!a)throw new Error(`Aggregator ${r} does not exist`);try{const e=a([i],this.getters.getLocale());return 0===n.length?{...e,value:""}:e}catch(e){return Zb(e,r.toUpperCase())}}getPossibleFieldValues(e){const t=[],o=hF(this.dataEntries,e),s=dF(o,e);for(const i of s)t.push({value:o[i]?.[0]?.[e.nameWithGranularity]?.value??"",label:o[i]?.[0]?.[e.nameWithGranularity]?.formattedValue||""});return t}getTableStructure(){if(!this.isValid())throw new Error("Pivot is not valid !");return this.table||(this.table=rF(this.dataEntries,this.definition)),this.table}getFields(){return this.metaData.fields}get fields(){return this.getFields()}loadMetaData(){if(this.invalidRangeError=void 0,!this.coreDefinition.dataSet)return this.invalidRangeError=new Ai(Mo("The pivot cannot be created because the dataset is missing.")),{fields:{},fieldKeys:[]};{const{zone:e,sheetId:t}=this.coreDefinition.dataSet,o=this.getters.getRangeFromZone(t,e);try{return this.extractFieldsFromRange(o)}catch(e){return this.invalidRangeError=e,{fields:{},fieldKeys:[]}}}}loadRuntimeDefinition(){return new sF(this.coreDefinition,this.fields,this.getters)}loadData(){const e=this._definition?.range;return this.isValid()&&e?this.extractDataEntriesFromRange(e):[]}getTypeOfDimension(e){if("measure"===e)return"char";const{fieldName:t}=Yl(e),o=this.fields[t]?.type;if(!o)throw new Error(`Field ${t} does not exist`);return o}filterDataEntriesFromDomain(e,t){return t.reduce(((e,t)=>this.filterDataEntriesFromDomainNode(e,t)),e)}filterDataEntriesFromDomainNode(e,t){const{field:o,value:s}=t,{nameWithGranularity:i}=this.getDimension(o);return e.filter((e=>e[i]?.value===s))}getDimension(e){return this.definition.getDimension(e)}getTypeFromZone(e,t){const o=this.getters.getEvaluatedCellsInZone(e,t).filter((e=>e.type!==ri.empty));return 0===o.length?"integer":o.every((e=>e.format&&ar(e.format)))?"datetime":o.every((e=>e.type===ri.boolean))?"boolean":o.some((e=>e.type===ri.text))?"char":"integer"}assertCellIsValidField(e,t,o){if(o.type===ri.error)throw new Ai(Mo("The pivot cannot be created because cell %s contains an error",Co(e,t)));if(o.type===ri.empty||""===o.value)throw new Ai(Mo("The pivot cannot be created because cell %s is empty",Co(e,t)));if("__count"===o.value)throw new Ai(Mo("The pivot cannot be created because cell %s contains a reserved value",Co(e,t)))}extractFieldsFromRange(e){const t={},o=[],s=e.sheetId,i=e.zone.top;for(let n=e.zone.left;n<=e.zone.right;n++){const r=this.getters.getEvaluatedCell({sheetId:s,col:n,row:i});this.assertCellIsValidField(n,i,r);const a=r.value?.toString();if(a){const i=this.getTypeFromZone(s,{top:e.zone.top+1,left:n,bottom:e.zone.bottom,right:n}),r=this.findName(a,t);t[r]={name:r,type:i,string:r,aggregator:"integer"===i?"sum":"count"},o.push(r)}}return{fields:t,fieldKeys:o}}findName(e,t){return Nt(e,Object.keys(t),{compute:(e,t)=>`${e}${t}`,start:2})}extractDataEntriesFromRange(e){const t=[];for(let o=e.zone.top+1;o<=e.zone.bottom;o++){const s={top:o,bottom:o,left:e.zone.left,right:e.zone.right},i=this.getters.getEvaluatedCellsInZone(e.sheetId,s),n={};for(const e in i){const t=i[e],o=this.fields[this.metaData.fieldKeys[e]];if(!o)throw new Error(`Field ${this.metaData.fieldKeys[e]} does not exist`);""===t.value?n[o.name]={value:null,type:ri.empty,formattedValue:""}:n[o.name]=t}n.__count={value:1,type:ri.number,formattedValue:"1"},t.push(n)}const o=this.definition.columns.concat(this.definition.rows).filter((e=>"datetime"===e.type));if(o.length){const e=this.getters.getLocale();for(const s of t)for(const t of o){const o=gF(t,s[t.fieldName]?.value||null,this.getters.getLocale()),i=_l(t.granularity),{format:n,value:r}=i.toValueAndFormat(o,e);s[t.nameWithGranularity]={value:o,type:s[t.fieldName]?.type||ri.empty,format:s[t.fieldName]?.format,formattedValue:Qn(r,{locale:e,format:n})}}}return t}},definition:sF,externalData:!1,onIterationEndEvaluation:e=>e.markAsDirtyForEvaluation(),dateGranularities:[...vF],datetimeGranularities:[...vF,"hour_number","minute_number","second_number"],isMeasureCandidate:e=>"boolean"!==e.type,isGroupable:()=>!0});class bF extends _c{pivotId;mutators=["reset","deferUpdates","applyUpdate","discardPendingUpdate","update"];updatesAreDeferred;draft=null;notification=this.get(Qb);alreadyNotified=!1;constructor(e,t){super(e),this.pivotId=t,this.updatesAreDeferred=this.getters.getPivotCoreDefinition(this.pivotId).deferUpdates??!1}handle(e){if("UPDATE_PIVOT"===e.type)e.pivotId===this.pivotId&&this.getters.getPivot(this.pivotId).init()}get fields(){return this.pivot.getFields()}get pivot(){return this.getters.getPivot(this.pivotId)}get definition(){const e=fF.get(this.pivot.type).definition;return this.draft?new e(this.draft,this.fields,this.getters):this.pivot.definition}get isDirty(){return!!this.draft}get measureFields(){const e=[{name:"__count",string:Mo("Count"),type:"integer",aggregator:"sum"}],t=this.fields;for(const o in t){const s=t[o];s&&(fF.get(this.pivot.type).isMeasureCandidate(s)&&e.push(s))}return e.sort(((e,t)=>e.string.localeCompare(t.string)))}get unusedGroupableFields(){const e=[],t=this.fields;for(const o in t){const s=t[o];s&&(fF.get(this.pivot.type).isGroupable(s)&&e.push(s))}const{columns:o,rows:s,measures:i}=this.definition,n=i.concat(s).concat(o).map((e=>e.fieldName)),r=this.unusedGranularities;return e.filter((e=>Xl(e)?!n.includes(e.name)||r[e.name].size>0:!n.includes(e.name))).sort(((e,t)=>e.string.localeCompare(t.string)))}get datetimeGranularities(){return fF.get(this.pivot.type).datetimeGranularities}get dateGranularities(){return fF.get(this.pivot.type).dateGranularities}get unusedGranularities(){return this.getUnusedGranularities(this.fields,this.draft??this.getters.getPivotCoreDefinition(this.pivotId))}reset(e){this.pivotId=e,this.updatesAreDeferred=!0,this.draft=null}deferUpdates(e){!1===e&&this.draft?(this.draft.deferUpdates=!1,this.applyUpdate()):this.update({deferUpdates:e}),this.updatesAreDeferred=e}applyUpdate(){if(this.draft&&(this.model.dispatch("UPDATE_PIVOT",{pivotId:this.pivotId,pivot:this.draft}),this.draft=null,!this.alreadyNotified&&!this.isDynamicPivotInViewport()&&this.isStaticPivotInViewport())){const e=`=PIVOT(${this.getters.getPivotFormulaId(this.pivotId)})`;this.alreadyNotified=!0,this.notification.notifyUser({type:"info",text:Mo("Pivot updates only work with dynamic pivot tables. Use %s or re-insert the static pivot from the Data menu.",e),sticky:!1})}}discardPendingUpdate(){this.draft=null}update(e){const t=this.getters.getPivotCoreDefinition(this.pivotId),o={...t,...this.draft,...e},s={...o,columns:o.columns.map((e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity}))),rows:o.rows.map((e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity}))),measures:o.measures.map((e=>({id:e.id,fieldName:e.fieldName,aggregator:e.aggregator,userDefinedName:e.userDefinedName,computedBy:e.computedBy,isHidden:e.isHidden,format:e.format,display:e.display}))),sortedColumn:this.shouldKeepSortedColumn(o)?o.sortedColumn:void 0};if(!this.draft&&mt(t,s))return;const i=this.addDefaultDateTimeGranularity(this.fields,s);this.draft=i,this.updatesAreDeferred||this.applyUpdate()}isDynamicPivotInViewport(){for(const e of this.getters.getVisibleCellPositions()){if(this.getters.isSpillPivotFormula(e))return!0}return!1}isStaticPivotInViewport(){for(const e of this.getters.getVisibleCellPositions()){const t=this.getters.getCell(e);if(t?.isFormula){const e=ES(t.compiledFormula.tokens);if(e&&"PIVOT"!==e.functionName)return!0}}return!1}addDefaultDateTimeGranularity(e,t){const{columns:o,rows:s}=t,i=Be(o),n=Be(s),r=this.getUnusedGranularities(e,t);for(const t of i.concat(n)){const o=e[t.fieldName]?.type;if(("date"===o||"datetime"===o)&&!t.granularity){const e=r[t.fieldName]?.values().next().value||"year";r[t.fieldName]?.delete(e),t.granularity=e}}return{...t,columns:i,rows:n}}getUnusedGranularities(e,t){const{columns:o,rows:s,measures:i}=t,n=o.concat(s).concat(i).filter((t=>{const o=e[t.fieldName]?.type;return"date"===o||"datetime"===o})),r={};for(const t of n)r[t.fieldName]=new Set("date"===e[t.fieldName]?.type?this.dateGranularities:this.datetimeGranularities);for(const e of n)r[e.fieldName].delete(e.granularity);return r}shouldKeepSortedColumn(e){const{sortedColumn:t}=e;if(!t)return!0;const o=this.getters.getPivotCoreDefinition(this.pivotId);return e.measures.find((e=>e.id===t.measure))&&mt(o.columns,e.columns)}}class SF extends t.Component{static template="o-spreadsheet-PivotSpreadsheetSidePanel";static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:QO,Section:X_,SelectionInput:lD,Checkbox:HI,PivotDeferUpdate:$O,PivotTitleSection:eF};store;state;pivotSidePanelRef=t.useRef("pivotSidePanel");setup(){this.store=wc(bF,this.props.pivotId),this.state=t.useState({range:void 0,rangeHasChanged:!1})}get shouldDisplayInvalidRangeError(){return(!this.store.isDirty||!this.state.rangeHasChanged)&&this.pivot.isInvalidRange}get ranges(){return this.state.range?[this.state.range]:this.definition.range?[this.env.model.getters.getRangeString(this.definition.range,"forceSheetReference")]:[]}get pivot(){return this.store.pivot}get definition(){return this.store.definition}getScrollableContainerEl(){return this.pivotSidePanelRef.el}onSelectionChanged(e){this.state.rangeHasChanged=!0,this.state.range=e[0]}onSelectionConfirmed(){if(this.state.range){const e=this.env.model.getters.getRangeFromSheetXC(this.env.model.getters.getActiveSheetId(),this.state.range);if(e.invalidSheetName||e.invalidXc)return;const t={sheetId:e.sheetId,zone:e.zone};this.store.update({dataSet:t}),this.store.applyUpdate()}}flipAxis(){const{rows:e,columns:t}=this.definition;this.onDimensionsUpdated({rows:t,columns:e})}onDimensionsUpdated(e){this.store.update(e)}}const yF=new n;yF.add("SPREADSHEET",{editor:SF});class CF extends t.Component{static template="o-spreadsheet-PivotSidePanel";static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:QO,Section:X_};setup(){dO(this)}get sidePanelEditor(){const e=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);if(!e)throw new Error("pivotId does not correspond to a pivot.");return yF.get(e.type).editor}get highlights(){return Z_(this.env.model.getters,this.props.pivotId)}}Pc`
|
|
1279
1279
|
.o-checkbox-selection {
|
|
1280
1280
|
max-height: 300px;
|
|
1281
1281
|
}
|
|
1282
|
-
`;class
|
|
1282
|
+
`;class wF extends t.Component{static template="o-spreadsheet-RemoveDuplicatesPanel";static components={ValidationMessages:hD,Section:X_,Checkbox:HI};static props={onCloseSidePanel:Function};state=t.useState({hasHeader:!1,columns:{}});setup(){t.onWillUpdateProps((()=>this.updateColumns()))}toggleHasHeader(){this.state.hasHeader=!this.state.hasHeader}toggleAllColumns(){const e=!this.isEveryColumnSelected;for(const t in this.state.columns)this.state.columns[t]=e}toggleColumn(e){this.state.columns[e]=!this.state.columns[e]}onRemoveDuplicates(){this.env.model.dispatch("REMOVE_DUPLICATES",{hasHeader:this.state.hasHeader,columns:this.getColsToAnalyze()})}getColLabel(e){const t=parseInt(e);let o=Mo("Column %s",vo(t));if(this.state.hasHeader){const e=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getSelectedZone().top,i=this.env.model.getters.getEvaluatedCell({sheetId:e,col:t,row:s});"empty"!==i.type&&(o+=` - ${i.value}`)}return o}get isEveryColumnSelected(){return Object.values(this.state.columns).every((e=>e))}get errorMessages(){const e=this.env.model.canDispatch("REMOVE_DUPLICATES",{hasHeader:this.state.hasHeader,columns:this.getColsToAnalyze()}).reasons,t=new Set;for(const o of e)t.add(SE.Errors[o]||SE.Errors.Unexpected);return Array.from(t)}get selectionStatisticalInformation(){const e=hs(this.env.model.getters.getSelectedZone());return Mo("%(row_count)s rows and %(column_count)s columns selected",{row_count:e.numberOfRows,column_count:e.numberOfCols})}get canConfirm(){return 0===this.errorMessages.length}updateColumns(){const e=this.env.model.getters.getSelectedZone(),t=this.state.columns,o={};for(let s=e.left;s<=e.right;s++)o[s]=!(s in t)||t[s];this.state.columns=o}getColsToAnalyze(){return Object.keys(this.state.columns).filter((e=>this.state.columns[e])).map((e=>parseInt(e)))}}Pc`
|
|
1283
1283
|
.o-locale-preview {
|
|
1284
1284
|
border: 1px solid ${D};
|
|
1285
1285
|
background-color: ${F};
|
|
1286
1286
|
}
|
|
1287
|
-
`;class
|
|
1287
|
+
`;class EF extends t.Component{static template="o-spreadsheet-SettingsPanel";static components={Section:X_,ValidationMessages:hD};static props={onCloseSidePanel:Function};loadedLocales=[];setup(){t.onWillStart((()=>this.loadLocales()))}onLocaleChange(e){const t=this.loadedLocales.find((t=>t.code===e));t&&this.env.model.dispatch("UPDATE_LOCALE",{locale:t})}async loadLocales(){this.loadedLocales=(await this.env.loadLocales()).filter((e=>{const t=Da(e);return t||console.warn(`Invalid locale: ${e.code} ${e}`),t})).sort(((e,t)=>e.name.localeCompare(t.name)))}get numberFormatPreview(){return Qn(1234567.89,{format:"#,##0.00",locale:this.env.model.getters.getLocale()})}get dateFormatPreview(){const e=this.env.model.getters.getLocale();return Qn(1.6,{format:e.dateFormat,locale:e})}get dateTimeFormatPreview(){const e=this.env.model.getters.getLocale();return Qn(1.6,{format:$a(e),locale:e})}get firstDayOfWeek(){const e=this.env.model.getters.getLocale().weekStart;return Jn[e%7]}get currentLocale(){return this.env.model.getters.getLocale()}get supportedLocales(){const e=this.currentLocale,t=this.loadedLocales.find((t=>t.code===e.code));if(!t)return[...this.loadedLocales,e].sort(((e,t)=>e.name.localeCompare(t.name)));if(!mt(e,t)){const o=this.loadedLocales.indexOf(t),s=[...this.loadedLocales];return s[o]=e,s.sort(((e,t)=>e.name.localeCompare(t.name))),s}return this.loadedLocales}}const xF={SplitIsDestructive:Mo("This will overwrite data in the subsequent columns. Split anyway?")};const IF=[{name:Mo("Detect automatically"),value:"auto"},{name:Mo("Custom separator"),value:"custom"},{name:Mo("Space"),value:" "},{name:Mo("Comma"),value:","},{name:Mo("Semicolon"),value:";"},{name:Mo("Line Break"),value:Pe}];class RF extends t.Component{static template="o-spreadsheet-SplitIntoColumnsPanel";static components={ValidationMessages:hD,Section:X_,Checkbox:HI};static props={onCloseSidePanel:Function};state=t.useState({separatorValue:"auto",addNewColumns:!1,customSeparator:""});setup(){const e=Cc(Oc);t.useEffect((e=>{"inactive"!==e&&this.props.onCloseSidePanel()}),(()=>[e.focusMode])),t.onMounted((()=>{e.activeComposer.stopEdition()}))}onSeparatorChange(e){this.state.separatorValue=e}updateCustomSeparator(e){e.target&&(this.state.customSeparator=e.target.value)}updateAddNewColumnsCheckbox(e){this.state.addNewColumns=e}confirm(){(function(e,t,o){let s=e.model.dispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:t,addNewColumns:o});return s.isCancelledBecause("SplitWillOverwriteContent")&&e.askConfirmation(xF.SplitIsDestructive,(()=>{s=e.model.dispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:t,addNewColumns:o,force:!0})})),s})(this.env,this.separatorValue,this.state.addNewColumns).isSuccessful&&this.props.onCloseSidePanel()}get errorMessages(){const e=this.env.model.canDispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!0}).reasons,t=new Set;for(const o of e)switch(o){case"SplitWillOverwriteContent":case"EmptySplitSeparator":break;default:t.add(bE.Errors[o]||bE.Errors.Unexpected)}return Array.from(t)}get warningMessages(){const e=[];return this.env.model.canDispatch("SPLIT_TEXT_INTO_COLUMNS",{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!1}).reasons.includes("SplitWillOverwriteContent")&&e.push(bE.Errors.SplitWillOverwriteContent),e}get separatorValue(){return"custom"===this.state.separatorValue?this.state.customSeparator:"auto"===this.state.separatorValue?this.env.model.getters.getAutomaticSeparator():this.state.separatorValue}get separators(){return IF}get isConfirmDisabled(){return!this.separatorValue||this.errorMessages.length>0}}const TF=["wholeTable","firstColumnStripe","secondColumnStripe","firstRowStripe","secondRowStripe","firstColumn","lastColumn","headerRow","totalRow"];function AF(e){const t=e.range;return{row:t.zone.top,col:t.zone.left,sheetId:t.sheetId}}function _F(e,t,o,s){const i=t.zone;if(i.left!==i.right)throw new Error("Can only define a filter on a single column");const n={...i,top:i.top+o.numberOfHeaders},r=s(t.sheetId,n);return{id:e,rangeWithHeaders:t,col:i.left,filteredRange:n.top>n.bottom?void 0:r}}function DF(e){return"static"===e.type||"forceStatic"===e.type}function OF(e,t,o,s){return{borders:FF(e,t,o,s),styles:PF(e,t,o,s)}}function FF(e,t,o,s){const i=an(o,s,(()=>({})));for(const n of TF){const r=t[n]?.border;if(!r)continue;const a=kF(n,e,o,s);for(const t of a)for(let a=t.left;a<=t.right;a++)for(let l=t.top;l<=t.bottom;l++){const c="wholeTable"===n&&l<=e.numberOfHeaders-1;l===t.top&&r?.top?MF(i,"top",r.top,a,l,o,s):l!==t.top&&!c&&r?.horizontal&&MF(i,"top",r.horizontal,a,l,o,s),l===t.bottom&&r?.bottom&&MF(i,"bottom",r.bottom,a,l,o,s),a===t.left&&r?.left&&MF(i,"left",r.left,a,l,o,s),a===t.right&&r?.right?MF(i,"right",r.right,a,l,o,s):a!==t.right&&!c&&r?.vertical&&MF(i,"right",r.vertical,a,l,o,s)}}return i}function MF(e,t,o,s,i,n,r){switch(t){case"top":return e[s][i].top=o,void(0!==i&&(e[s][i-1].bottom=o));case"bottom":return e[s][i].bottom=o,void(i!==r-1&&(e[s][i+1].top=o));case"left":return e[s][i].left=o,void(0!==s&&(e[s-1][i].right=o));case"right":return e[s][i].right=o,void(s!==n-1&&(e[s+1][i].left=o))}}function PF(e,t,o,s){const i=an(o,s,(()=>({})));for(const n of TF){const r=t[n],a=NF(n);if(!r&&!a)continue;const l=kF(n,e,o,s);for(const e of l)for(let t=e.left;t<=e.right;t++)for(let o=e.top;o<=e.bottom;o++)i[t][o]||(i[t][o]={}),i[t][o]={...i[t][o],...r?.style},a&&(i[t][o].bold=!0)}return i}function NF(e){return"firstColumn"===e||"lastColumn"===e||"headerRow"===e||"totalRow"===e}function kF(e,t,o,s){const i=[],n=Math.min(t.numberOfHeaders,s),r=t.totalRow?1:0,a=o-1,l=s-1;switch(e){case"wholeTable":i.push({top:0,left:0,bottom:l,right:a});break;case"firstColumn":if(!t.firstColumn)break;i.push({top:0,left:0,bottom:l,right:0});break;case"lastColumn":if(!t.lastColumn)break;i.push({top:0,left:a,bottom:l,right:a});break;case"headerRow":if(!t.numberOfHeaders)break;i.push({top:0,left:0,bottom:n-1,right:a});break;case"totalRow":if(!t.totalRow)break;i.push({top:l,left:0,bottom:l,right:a});break;case"firstRowStripe":if(!t.bandedRows)break;for(let e=n;e<s-r;e+=2)i.push({top:e,left:0,bottom:e,right:a});break;case"secondRowStripe":if(!t.bandedRows)break;for(let e=n+1;e<s-r;e+=2)i.push({top:e,left:0,bottom:e,right:a});break;case"firstColumnStripe":if(!t.bandedColumns)break;for(let e=0;e<o;e+=2)i.push({top:n,left:e,bottom:l-r,right:e});break;case"secondColumnStripe":if(!t.bandedColumns)break;for(let e=1;e<o;e+=2)i.push({top:n,left:e,bottom:l-r,right:e})}return i}function LF(e,t,o,s){e.resetTransform(),function(e,t,o,s){e.save();for(let i=0;i<5;i++)for(let n=0;n<5;n++)e.fillStyle=t.styles[i][n].fillColor||"#fff",e.fillRect(i*o,n*s,o,s);e.restore()}(e,t,o,s),function(e,t,o,s){e.save(),e.translate(0,.5),e.lineWidth=1;for(let i=0;i<5;i++)for(let n=0;n<5;n++){const r=t.borders[i][n];r.top&&(e.strokeStyle=r.top.color,e.beginPath(),e.moveTo(i*o,n*s),e.lineTo(i*o+o,n*s),e.stroke()),r.bottom&&(e.strokeStyle=r.bottom.color,e.beginPath(),e.moveTo(i*o,n*s+s),e.lineTo(i*o+o,n*s+s),e.stroke())}e.resetTransform(),e.translate(.5,0);for(let i=0;i<5;i++)for(let n=0;n<5;n++){const r=t.borders[i][n];r.left&&(e.strokeStyle=r.left.color,e.beginPath(),e.moveTo(i*o,n*s),e.lineTo(i*o,n*s+s),e.stroke()),r.right&&(e.strokeStyle=r.right.color,e.beginPath(),e.moveTo(i*o+o,n*s),e.lineTo(i*o+o,n*s+s+1),e.stroke())}e.restore()}(e,t,o,s),function(e,t,o,s){e.save(),e.translate(0,.5),e.lineWidth=1;const i=Math.floor(o/4),n=Math.floor(s/2);for(let r=0;r<5;r++)for(let a=0;a<5;a++)e.strokeStyle=t.styles[r][a].textColor||"#000",e.beginPath(),e.moveTo(r*o+i+1,a*s+n),e.lineTo(r*o+o-i,a*s+n),e.stroke();e.restore()}(e,t,o,s)}Pc`
|
|
1288
1288
|
.o-table-style-list-item {
|
|
1289
1289
|
border: 1px solid transparent;
|
|
1290
1290
|
border-radius: 4px;
|
|
@@ -1311,7 +1311,7 @@
|
|
|
1311
1311
|
}
|
|
1312
1312
|
}
|
|
1313
1313
|
}
|
|
1314
|
-
`;class
|
|
1314
|
+
`;class VF extends t.Component{static template="o-spreadsheet-TableStylePreview";static components={Menu:mR};static props={tableConfig:Object,tableStyle:Object,class:String,styleId:{type:String,optional:!0},selected:{type:Boolean,optional:!0},onClick:{type:Function,optional:!0}};canvasRef=t.useRef("canvas");menu=t.useState({isOpen:!1,position:null,menuItems:[]});setup(){t.onWillUpdateProps((e=>{mt(this.props.tableConfig,e.tableConfig)&&mt(this.props.tableStyle,e.tableStyle)||this.drawTable(e)})),t.onMounted((()=>this.drawTable(this.props)))}drawTable(e){const t=this.canvasRef.el.getContext("2d"),{width:o,height:s}=this.canvasRef.el.getBoundingClientRect();this.canvasRef.el.width=o,this.canvasRef.el.height=s;LF(t,OF(e.tableConfig,e.tableStyle,5,5),(o-1)/5,(s-1)/5)}onContextMenu(e){var t,s;this.props.styleId&&(this.menu.menuItems=(t=this.env,s=this.props.styleId,t.model.getters.isTableStyleEditable(s)?o([{id:"editTableStyle",name:Mo("Edit table style"),execute:e=>e.openSidePanel("TableStyleEditorPanel",{styleId:s}),icon:"o-spreadsheet-Icon.EDIT"},{id:"deleteTableStyle",name:Mo("Delete table style"),execute:e=>e.model.dispatch("REMOVE_TABLE_STYLE",{tableStyleId:s}),icon:"o-spreadsheet-Icon.TRASH"}]):[]),this.menu.isOpen=!0,this.menu.position={x:e.clientX,y:e.clientY})}closeMenu(){this.menu.isOpen=!1,this.menu.position=null,this.menu.menuItems=[]}get styleName(){return this.props.styleId?this.env.model.getters.getTableStyle(this.props.styleId).displayName:""}get isStyleEditable(){return!!this.props.styleId&&this.env.model.getters.isTableStyleEditable(this.props.styleId)}editTableStyle(){this.env.openSidePanel("TableStyleEditorPanel",{styleId:this.props.styleId})}}Pc`
|
|
1315
1315
|
.o-table-style-popover {
|
|
1316
1316
|
/* 7 tables preview + padding by line */
|
|
1317
1317
|
width: calc((66px + 4px * 2) * 7 + 1.5rem * 2);
|
|
@@ -1356,7 +1356,7 @@
|
|
|
1356
1356
|
}
|
|
1357
1357
|
}
|
|
1358
1358
|
}
|
|
1359
|
-
`;class
|
|
1359
|
+
`;class UF extends t.Component{static template="o-spreadsheet-TableStylesPopover";static components={Popover:PI,TableStylePreview:VF};static props={tableConfig:Object,popoverProps:{type:Object,optional:!0},closePopover:Function,onStylePicked:Function,selectedStyleId:{type:String,optional:!0}};categories=ew;tableStyleListRef=t.useRef("tableStyleList");state=t.useState({selectedCategory:this.initialSelectedCategory});menu=t.useState({isOpen:!1,position:null,menuItems:[]});setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0})}onExternalClick(e){this.tableStyleListRef.el&&!ZI(this.tableStyleListRef.el,e)&&(this.props.closePopover(),e.hasClosedTableStylesPopover=!0)}get displayedStyles(){const e=this.env.model.getters.getTableStyles();return Object.keys(e).filter((t=>e[t].category===this.state.selectedCategory))}get initialSelectedCategory(){return this.props.selectedStyleId?this.env.model.getters.getTableStyle(this.props.selectedStyleId).category:"medium"}newTableStyle(){this.props.closePopover(),this.env.openSidePanel("TableStyleEditorPanel",{onStylePicked:this.props.onStylePicked})}}Pc`
|
|
1360
1360
|
.o-table-style-picker {
|
|
1361
1361
|
border: 1px solid ${D};
|
|
1362
1362
|
border-radius: 3px;
|
|
@@ -1380,7 +1380,7 @@
|
|
|
1380
1380
|
}
|
|
1381
1381
|
}
|
|
1382
1382
|
}
|
|
1383
|
-
`;class
|
|
1383
|
+
`;class HF extends t.Component{static template="o-spreadsheet-TableStylePicker";static components={TableStylesPopover:UF,TableStylePreview:VF};static props={table:Object};state=t.useState({popoverProps:void 0});getDisplayedTableStyles(){const e=this.env.model.getters.getTableStyles(),t=e[this.props.table.config.styleId].category,o=Object.keys(e).filter((o=>e[o].category===t)),s=o.indexOf(this.props.table.config.styleId);if(-1===s)return s;const i=4*Math.floor(s/4);return o.slice(i)}onStylePicked(e){const t=this.env.model.getters.getActiveSheetId();this.env.model.dispatch("UPDATE_TABLE",{sheetId:t,zone:this.props.table.range.zone,config:{styleId:e}}),this.closePopover()}onArrowButtonClick(e){if(e.hasClosedTableStylesPopover||this.state.popoverProps)return void this.closePopover();const t=e.currentTarget,{bottom:o,right:s}=t.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:s,y:o,width:0,height:0},positioning:"TopRight",verticalOffset:0}}closePopover(){this.state.popoverProps=void 0}}Pc`
|
|
1384
1384
|
.o-table-panel {
|
|
1385
1385
|
input.o-table-n-of-headers {
|
|
1386
1386
|
width: 14px;
|
|
@@ -1392,7 +1392,7 @@
|
|
|
1392
1392
|
height: 14px;
|
|
1393
1393
|
}
|
|
1394
1394
|
}
|
|
1395
|
-
`;class
|
|
1395
|
+
`;class BF extends t.Component{static template="o-spreadsheet-TablePanel";static components={TableStylePicker:HF,SelectionInput:lD,ValidationMessages:hD,Checkbox:HI,Section:X_};static props={onCloseSidePanel:Function,table:Object};state;setup(){const e=this.env.model.getters.getActiveSheetId();this.state=t.useState({tableZoneErrors:[],tableXc:this.env.model.getters.getRangeString(this.props.table.range,e),filtersEnabledIfPossible:this.props.table.config.hasFilters})}updateHasFilters(e){this.state.filtersEnabledIfPossible=e,this.updateTableConfig("hasFilters",e)}updateTableConfig(e,t){const o=this.env.model.getters.getActiveSheetId();return this.env.model.dispatch("UPDATE_TABLE",{sheetId:o,zone:this.props.table.range.zone,config:{[e]:t}})}updateHasHeaders(e){const t=e?1:0;this.updateNumberOfHeaders(t)}updateTableIsDynamic(e){const t=e?"dynamic":"forceStatic";if(t===this.props.table.type)return;const o=this.env.model.getters.getTable(AF(this.props.table));if(!o)return;const s=this.env.model.getters.getActiveSheetId(),i=this.env.model.dispatch("UPDATE_TABLE",{sheetId:s,zone:this.props.table.range.zone,newTableRange:o.range.rangeData,tableType:t}),n=this.env.model.getters.getCoreTable(AF(this.props.table));if(i.isSuccessful&&n){const e=n.range;this.state.tableXc=this.env.model.getters.getRangeString(e,s),this.state.tableZoneErrors=[]}}onChangeNumberOfHeaders(e){const t=e.target,o=parseInt(t.value);this.updateNumberOfHeaders(o).isSuccessful||(t.value=this.props.table.config.numberOfHeaders.toString())}updateNumberOfHeaders(e){const t=e>0&&(this.tableConfig.hasFilters||this.state.filtersEnabledIfPossible);return this.env.model.dispatch("UPDATE_TABLE",{sheetId:this.env.model.getters.getActiveSheetId(),zone:this.props.table.range.zone,config:{numberOfHeaders:e,hasFilters:t}})}onRangeChanged(e){const t=this.env.model.getters.getActiveSheetId();this.state.tableXc=e[0];const o=this.env.model.getters.getRangeFromSheetXC(t,this.state.tableXc);this.state.tableZoneErrors=this.env.model.canDispatch("UPDATE_TABLE",{sheetId:t,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeDataFromXc(t,this.state.tableXc),tableType:this.getNewTableType(o.zone)}).reasons}onRangeConfirmed(){const e=this.env.model.getters.getActiveSheetId();let t=this.env.model.getters.getRangeFromSheetXC(e,this.state.tableXc);if(1===ys(t.zone)){const o=this.env.model.getters.getContiguousZone(e,t.zone);t=this.env.model.getters.getRangeFromZone(e,o)}const o=t.zone,s=this.props.table.range.zone,i=o.top===s.top&&o.left===s.left?"RESIZE_TABLE":"UPDATE_TABLE",n=this.env.model.dispatch(i,{sheetId:e,zone:this.props.table.range.zone,newTableRange:t.rangeData,tableType:this.getNewTableType(t.zone)}),r={sheetId:e,col:t.zone.left,row:t.zone.top},a=this.env.model.getters.getCoreTable(r);if(n.isSuccessful&&a){const t=AF(a);this.env.model.selection.selectZone({zone:vs(t),cell:t});const o=a.range;this.state.tableXc=this.env.model.getters.getRangeString(o,e)}}deleteTable(){const e=this.env.model.getters.getActiveSheetId();this.env.model.dispatch("REMOVE_TABLE",{sheetId:e,target:[this.props.table.range.zone]})}getNewTableType(e){if("forceStatic"===this.props.table.type)return"forceStatic";const t=this.env.model.getters.getActiveSheetId();return this.env.model.getters.canCreateDynamicTableOnZones(t,[e])?"dynamic":"static"}get tableConfig(){return this.props.table.config}get errorMessages(){return(this.state.tableZoneErrors||[]).map((e=>CE.Errors[e]||CE.Errors.Unexpected))}getCheckboxLabel(e){return CE.Checkboxes[e]}get canHaveFilters(){return this.tableConfig.numberOfHeaders>0}get hasFilterCheckboxTooltip(){return this.canHaveFilters?void 0:CE.Tooltips.filterWithoutHeader}get canBeDynamic(){const e=this.env.model.getters.getActiveSheetId();return"dynamic"===this.props.table.type||this.env.model.getters.canCreateDynamicTableOnZones(e,[this.props.table.range.zone])}get dynamicTableTooltip(){return CE.Tooltips.isDynamic}}Pc`
|
|
1396
1396
|
.o-table-style-editor-panel {
|
|
1397
1397
|
.o-table-style-list-item {
|
|
1398
1398
|
margin: 2px 7px;
|
|
@@ -1404,7 +1404,7 @@
|
|
|
1404
1404
|
}
|
|
1405
1405
|
}
|
|
1406
1406
|
}
|
|
1407
|
-
`;const
|
|
1407
|
+
`;const zF="#3C78D8";class $F extends t.Component{static template="o-spreadsheet-TableStyleEditorPanel";static components={Section:X_,RoundColorPicker:ID,TableStylePreview:VF};static props={onCloseSidePanel:Function,onStylePicked:{type:Function,optional:!0},styleId:{type:String,optional:!0}};state=t.useState(this.getInitialState());setup(){t.useExternalListener(window,"click",(()=>this.state.pickerOpened=!1))}getInitialState(){const e=this.props.styleId?this.env.model.getters.getTableStyle(this.props.styleId):null;return{pickerOpened:!1,primaryColor:e?.primaryColor||zF,selectedTemplateName:e?.templateName||"lightColoredText",styleName:e?.displayName||this.env.model.getters.getNewCustomTableStyleName()}}togglePicker(){this.state.pickerOpened=!this.state.pickerOpened}onColorPicked(e){this.state.primaryColor=$t(e)?e:zF,this.state.pickerOpened=!1}onTemplatePicked(e){this.state.selectedTemplateName=e}onConfirm(){const e=this.props.styleId||this.env.model.uuidGenerator.smallUuid();this.env.model.dispatch("CREATE_TABLE_STYLE",{tableStyleId:e,tableStyleName:this.state.styleName,templateName:this.state.selectedTemplateName,primaryColor:this.state.primaryColor}),this.props.onStylePicked?.(e),this.props.onCloseSidePanel()}onCancel(){this.props.onCloseSidePanel()}onDelete(){this.props.styleId&&(this.env.model.dispatch("REMOVE_TABLE_STYLE",{tableStyleId:this.props.styleId}),this.props.onCloseSidePanel())}get colorPreviewStyle(){return Lc({background:this.state.primaryColor})}get tableTemplates(){return Object.keys(bw).filter((e=>"none"!==e))}get previewTableConfig(){return{bandedColumns:!1,bandedRows:!0,firstColumn:!1,lastColumn:!1,numberOfHeaders:1,totalRow:!0,hasFilters:!0,styleId:""}}get selectedStyle(){return this.computeTableStyle(this.state.selectedTemplateName)}computeTableStyle(e){return Sw(this.state.styleName,e,this.state.primaryColor)}}const WF=new n;WF.add("ConditionalFormatting",{title:Mo("Conditional formatting"),Body:mO}),WF.add("ChartPanel",{title:Mo("Chart"),Body:aO,computeState:(e,t)=>{const o=e.getSelectedFigureId()??t.figureId;return e.isChartDefined(o)?{isOpen:!0,props:{figureId:o}}:{isOpen:!1}}}),WF.add("FindAndReplace",{title:Mo("Find and Replace"),Body:VO}),WF.add("CustomCurrency",{title:Mo("Custom currency format"),Body:fO}),WF.add("SplitToColumns",{title:Mo("Split text into columns"),Body:RF}),WF.add("Settings",{title:Mo("Spreadsheet settings"),Body:EF}),WF.add("RemoveDuplicates",{title:Mo("Remove duplicates"),Body:wF}),WF.add("DataValidation",{title:Mo("Data validation"),Body:PO}),WF.add("DataValidationEditor",{title:Mo("Data validation"),Body:FO}),WF.add("MoreFormats",{title:Mo("More date formats"),Body:HO}),WF.add("TableSidePanel",{title:Mo("Edit table"),Body:BF,computeState:e=>{const t=e.getFirstTableInSelection();if(!t)return{isOpen:!1};return{isOpen:!0,props:{table:e.getCoreTable(AF(t))},key:t.id}}}),WF.add("TableStyleEditorPanel",{title:Mo("Create custom table style"),Body:$F,computeState:(e,t)=>({isOpen:!0,props:{...t},key:t.styleId??"new"})}),WF.add("PivotSidePanel",{title:(e,t)=>Mo("Pivot #%s",e.model.getters.getPivotFormulaId(t.pivotId)),Body:CF,computeState:(e,t)=>({isOpen:e.isExistingPivot(t.pivotId),props:t,key:`pivot_key_${t.pivotId}`})}),WF.add("PivotMeasureDisplayPanel",{title:(e,t)=>{const o=e.model.getters.getPivot(t.pivotId).getMeasure(t.measure.id);return Mo('Measure "%s" options',o.displayName)},Body:zO,computeState:(e,t)=>{try{return e.getPivot(t.pivotId).getMeasure(t.measure.id),{isOpen:!0,props:t,key:"pivot_measure_display"}}catch(e){return{isOpen:!1}}}});const GF=new class extends n{mapping={};uuidGenerator=new la;add(e,t){const o={...t,id:this.uuidGenerator.uuidv4()};return super.add(e,o)}getAllOrdered(){return this.getAll().sort(((e,t)=>e.sequence-t.sequence))}};Pc`
|
|
1408
1408
|
div.o-figure {
|
|
1409
1409
|
position: absolute;
|
|
1410
1410
|
width: 100%;
|
|
@@ -1475,7 +1475,7 @@
|
|
|
1475
1475
|
}
|
|
1476
1476
|
}
|
|
1477
1477
|
}
|
|
1478
|
-
`;class
|
|
1478
|
+
`;class qF extends t.Component{static template="o-spreadsheet-FigureComponent";static props={figure:Object,style:{type:String,optional:!0},onFigureDeleted:{type:Function,optional:!0},onMouseDown:{type:Function,optional:!0},onClickAnchor:{type:Function,optional:!0}};static components={Menu:mR};static defaultProps={onFigureDeleted:()=>{},onMouseDown:()=>{},onClickAnchor:()=>{}};menuState=t.useState({isOpen:!1,position:null,menuItems:[]});figureRef=t.useRef("figure");menuButtonRef=t.useRef("menuButton");menuButtonRect=MI(this.menuButtonRef);borderWidth;get isSelected(){return this.env.model.getters.getSelectedFigureId()===this.props.figure.id}get figureRegistry(){return bI}getBorderWidth(){return this.env.isDashboard()?0:this.isSelected?2:this.borderWidth}get borderStyle(){return`border: ${this.getBorderWidth()}px solid ${this.isSelected?p:g};`}get wrapperStyle(){const{x:e,y:t,width:o,height:s}=this.props.figure;return Lc({left:`${e}px`,top:`${t}px`,width:`${o}px`,height:`${s}px`,"z-index":String(Oe.Figure+(this.isSelected?1:0))})}getResizerPosition(e){let t={};return e.includes("top")?t.top="-3px":e.includes("bottom")?t.bottom="-3px":t.bottom="calc(50% - 3px)",e.includes("left")?t.left="-3px":e.includes("right")?t.right="-3px":t.right="calc(50% - 3px)",Lc(t)}setup(){const e=bI.get(this.props.figure.tag).borderWidth;this.borderWidth=void 0!==e?e:1,t.useEffect(((e,t,o)=>{e===t&&o?.focus({preventScroll:!0})}),(()=>[this.env.model.getters.getSelectedFigureId(),this.props.figure.id,this.figureRef.el])),t.onWillUnmount((()=>{this.props.onFigureDeleted()}))}clickAnchor(e,t,o){this.props.onClickAnchor(e,t,o)}onMouseDown(e){this.props.onMouseDown(e)}onKeyDown(e){const t=this.props.figure,o=eR(e);switch(o){case"Delete":case"Backspace":this.env.model.dispatch("DELETE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:t.id}),this.props.onFigureDeleted(),e.preventDefault(),e.stopPropagation();break;case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":const s={ArrowDown:[0,1],ArrowLeft:[-1,0],ArrowRight:[1,0],ArrowUp:[0,-1]}[e.key];this.env.model.dispatch("UPDATE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:t.id,x:t.x+s[0],y:t.y+s[1]}),e.preventDefault(),e.stopPropagation();break;case"Ctrl+A":e.preventDefault(),e.stopPropagation();break;case"Ctrl+Y":case"Ctrl+Z":"Ctrl+Y"===o?this.env.model.dispatch("REQUEST_REDO"):"Ctrl+Z"===o&&this.env.model.dispatch("REQUEST_UNDO"),e.preventDefault(),e.stopPropagation()}}onContextMenu(e){if(this.env.isDashboard())return;const t={x:e.clientX,y:e.clientY};this.openContextMenu(t)}showMenu(){const{x:e,y:t,width:o}=this.menuButtonRect,s={x:e>=he?e-he:e+o,y:t};this.openContextMenu(s)}openContextMenu(e){this.menuState.isOpen=!0,this.menuState.position=e,this.menuState.menuItems=bI.get(this.props.figure.tag).menuBuilder(this.props.figure.id,this.props.onFigureDeleted,this.env)}}const ZF={CannotHideAllRows:Mo("Cannot hide all the rows of a sheet."),CannotHideAllColumns:Mo("Cannot hide all the columns of a sheet.")};function jF(e,t,o,s,i){const n=e.model.getters.getHeaderGroup(t,o,s,i);if(!n)return;const r=n.isFolded?"UNFOLD_HEADER_GROUP":"FOLD_HEADER_GROUP",a=e.model.dispatch(r,{sheetId:t,dimension:o,start:n.start,end:n.end});if(!a.isSuccessful&&a.isCancelledBecause("NotEnoughElements")){const t="ROW"===o?ZF.CannotHideAllRows:ZF.CannotHideAllColumns;e.raiseError(t)}}function YF(e,t){return o([{id:"unfold_all",name:Mo("ROW"===t?"Expand all row groups":"Expand all column groups"),execute:o=>{o.model.dispatch("UNFOLD_ALL_HEADER_GROUPS",{sheetId:e,dimension:t})}},{id:"fold_all",name:Mo("ROW"===t?"Collapse all row groups":"Collapse all column groups"),execute:o=>{o.model.dispatch("FOLD_ALL_HEADER_GROUPS",{sheetId:e,dimension:t})}}])}const XF=new xI;XF.add("group_columns",{sequence:10,...N_,isVisible:()=>!0,isEnabled:N_.isVisible}).add("group_rows",{sequence:20,...k_,isVisible:()=>!0,isEnabled:k_.isVisible});const KF=new xI;KF.add("ungroup_columns",{sequence:10,...L_,isEnabled:e=>B_(e,"COL")}).add("ungroup_rows",{sequence:20,...V_,isEnabled:e=>B_(e,"ROW")});class JF extends _c{highlightStore=this.get(Jb);constructor(e){super(e),this.highlightStore.register(this)}get highlights(){let e;const t=this.model.getters.getActivePosition(),o=this.getters.getEvaluatedCell(t),s=this.model.getters.getArrayFormulaSpreadingOn(t);return e=s?this.model.getters.getSpreadZone(s,{ignoreSpillError:!0}):this.model.getters.getSpreadZone(t,{ignoreSpillError:!0}),e?[{sheetId:t.sheetId,zone:e,dashed:o.value===Ri.SpilledBlocked,color:"#17A2B8",noFill:!0,thinLine:!0}]:[]}}Pc`
|
|
1479
1479
|
.o-autofill {
|
|
1480
1480
|
position: absolute;
|
|
1481
1481
|
height: ${8}px;
|
|
@@ -1502,7 +1502,7 @@
|
|
|
1502
1502
|
pointer-events: none;
|
|
1503
1503
|
white-space: nowrap;
|
|
1504
1504
|
}
|
|
1505
|
-
`;class
|
|
1505
|
+
`;class QF extends t.Component{static template="o-spreadsheet-Autofill";static props={position:Object,isVisible:Boolean};state=t.useState({position:{left:0,top:0},handler:!1});get style(){const{left:e,top:t}=this.props.position;return Lc({top:`${t}px`,left:`${e}px`,visibility:this.props.isVisible?"visible":"hidden"})}get handlerStyle(){const{left:e,top:t}=this.state.handler?this.state.position:this.props.position;return Lc({top:`${t}px`,left:`${e}px`})}get styleNextValue(){const{left:e,top:t}=this.state.position;return Lc({top:`${t+5}px`,left:`${e+15}px`})}getTooltip(){const e=this.env.model.getters.getAutofillTooltip();return e&&!e.component&&(e.component=eM),e}onMouseDown(e){let t,o;this.state.handler=!0;const s=e.clientX-this.props.position.left,i=e.clientY-this.props.position.top;J_(this.env,((e,n,r)=>{if(this.state.position={left:r.clientX-s,top:r.clientY-i},t!==e||o!==n){const s=this.env.model.getters.getActiveSheetId(),i=this.env.model.getters.getNumberCols(s),r=this.env.model.getters.getNumberRows(s);t=-1===e?t:qe(e,0,i),o=-1===n?o:qe(n,0,r),void 0!==t&&void 0!==o&&this.env.model.dispatch("AUTOFILL_SELECT",{col:t,row:o})}}),(()=>{this.state.handler=!1,this.state.position={...this.props.position},this.env.model.dispatch("AUTOFILL")}))}onDblClick(){this.env.model.dispatch("AUTOFILL_AUTO")}}class eM extends t.Component{static props={content:String};static template=t.xml`
|
|
1506
1506
|
<div t-esc="props.content"/>
|
|
1507
1507
|
`}Pc`
|
|
1508
1508
|
.o-client-tag {
|
|
@@ -1513,11 +1513,11 @@
|
|
|
1513
1513
|
color: white;
|
|
1514
1514
|
pointer-events: none;
|
|
1515
1515
|
}
|
|
1516
|
-
`;class
|
|
1516
|
+
`;class tM extends t.Component{static template="o-spreadsheet-ClientTag";static props={active:Boolean,name:String,color:String,col:Number,row:Number};get tagStyle(){const{col:e,row:t,color:o}=this.props,{height:s}=this.env.model.getters.getSheetViewDimensionWithHeaders(),{x:i,y:n}=this.env.model.getters.getVisibleRect({left:e,top:t,right:e,bottom:t});return Lc({bottom:s-n+15+"px",left:i-1+"px",border:`1px solid ${o}`,"background-color":o})}}const oM=Mo("The cell you are trying to edit has been deleted.");class sM extends sS{canStopEdition(){return"inactive"===this.editionMode||this.checkDataValidation()}stopEdition(e){if(this.canStopEdition())return this._stopEdition(),void(e&&this.model.selection.moveAnchorCell(e,1));const t=this.currentEditedCell,o=Co(t.col,t.row),s=this.getters.getValidationRuleForCell(t);if(!s)return;const i=vO.get(s.criterion.type).getErrorString(s.criterion,this.getters,t.sheetId);this.notificationStore.raiseError(Mo("The data you entered in %s violates the data validation rule set on the cell:\n%s",o,i)),this.cancelEdition()}handle(e){switch(super.handle(e),e.type){case"SET_FORMATTING":this.cancelEdition();break;case"ADD_COLUMNS_ROWS":this.onAddElements(e);break;case"REMOVE_COLUMNS_ROWS":"COL"===e.dimension?this.onColumnsRemoved(e):this.onRowsRemoved(e);break;case"ACTIVATE_SHEET":if(kt(this._currentContent)||(this._cancelEdition(),this.resetContent()),e.sheetIdFrom!==e.sheetIdTo){const t=this.getters.getActivePosition(),{col:o,row:s}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:t.col,row:t.row}),i=this.getters.expandZone(e.sheetIdTo,vs({col:o,row:s}));this.model.selection.resetAnchor(this,{cell:{col:o,row:s},zone:i})}break;case"DELETE_SHEET":case"UNDO":case"REDO":!!this.getters.tryGetSheet(this.sheetId)||"inactive"===this.editionMode||(this.sheetId=this.getters.getActiveSheetId(),this.cancelEditionAndActivateSheet(),this.resetContent(),this.notificationStore.raiseError(oM))}}get placeholder(){const e=this.getters.getActivePosition(),t=this.model.getters.getArrayFormulaSpreadingOn(e);if(!t)return;const o=this.getters.getCell(t);return o?.content}get currentEditedCell(){return{sheetId:this.sheetId,col:this.col,row:this.row}}onColumnsRemoved(e){if(e.elements.includes(this.col)&&"inactive"!==this.editionMode)return this.cancelEdition(),void this.notificationStore.raiseError(oM);const{top:t,left:o}=os({left:this.col,right:this.col,top:this.row,bottom:this.row},"left",[...e.elements]);this.col=o,this.row=t}onRowsRemoved(e){if(e.elements.includes(this.row)&&"inactive"!==this.editionMode)return this.cancelEdition(),void this.notificationStore.raiseError(oM);const{top:t,left:o}=os({left:this.col,right:this.col,top:this.row,bottom:this.row},"top",[...e.elements]);this.col=o,this.row=t}onAddElements(e){const{top:t,left:o}=ts({left:this.col,right:this.col,top:this.row,bottom:this.row},"COL"===e.dimension?"left":"top",e.base,e.position,e.quantity);this.col=o,this.row=t}confirmEdition(e){if(e){const t=this.getters.getActiveSheetId(),o=this.getters.getEvaluatedCell({sheetId:t,col:this.col,row:this.row});o.link&&!kt(e)&&(e=tt(e,o.link.url)),this.addHeadersForSpreadingFormula(e),this.model.dispatch("UPDATE_CELL",{...this.currentEditedCell,content:e})}else this.model.dispatch("UPDATE_CELL",{...this.currentEditedCell,content:""});this.model.dispatch("AUTOFILL_TABLE_COLUMN",{...this.currentEditedCell}),this.setContent("")}getComposerContent(e){const t=this.getters.getLocale(),o=this.getters.getCell(e);if(o?.isFormula)return Na(o.content,t);if(this.model.getters.getArrayFormulaSpreadingOn(e))return"";const{format:s,value:i,type:n,formattedValue:r}=this.getters.getEvaluatedCell(e);switch(n){case ri.empty:return"";case ri.text:case ri.error:return i;case ri.boolean:return r;case ri.number:if(s&&ar(s)){if(null!==Bs(r,t))return r;return Qn(i,{locale:t,format:Number.isInteger(i)?t.dateFormat:$a(t)})}return this.numberComposerContent(i,s,t)}}numberComposerContent(e,t,o){return t?.includes("%")?`${rr(100*e,o.decimalSeparator)}%`:rr(e,o.decimalSeparator)}addHeadersForSpreadingFormula(e){if(!kt(e))return;const t=this.getters.evaluateFormula(this.sheetId,e);if(!wi(t))return;const o=this.getters.getNumberRows(this.sheetId),s=this.getters.getNumberCols(this.sheetId),i=this.row+t[0].length-o,n=this.col+t.length-s;n>0&&this.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:this.sheetId,dimension:"COL",base:s-1,position:"after",quantity:n+20}),i>0&&this.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:this.sheetId,dimension:"ROW",base:o-1,position:"after",quantity:i+50})}checkDataValidation(){const e={sheetId:this.sheetId,col:this.col,row:this.row},t=this.getCurrentCanonicalContent(),o=kt(t)?this.getters.evaluateFormula(this.sheetId,t):Tr(t,this.getters.getLocale());if(wi(o))return!0;const s=this.getters.getValidationResultForCellValue(o,e);return!(!s.isValid&&s.rule.isBlocking)}}const iM=3*.4*window.devicePixelRatio||1;Pc`
|
|
1517
1517
|
div.o-grid-composer {
|
|
1518
1518
|
z-index: ${Oe.GridComposer};
|
|
1519
1519
|
position: absolute;
|
|
1520
|
-
border: ${
|
|
1520
|
+
border: ${iM}px solid ${p};
|
|
1521
1521
|
font-family: ${fe};
|
|
1522
1522
|
|
|
1523
1523
|
display: flex;
|
|
@@ -1534,18 +1534,18 @@
|
|
|
1534
1534
|
padding: 6px 7px;
|
|
1535
1535
|
border-radius: 4px;
|
|
1536
1536
|
}
|
|
1537
|
-
`;class
|
|
1537
|
+
`;class nM extends t.Component{static template="o-spreadsheet-GridComposer";static props={gridDims:Object,onInputContextMenu:Function};static components={Composer:WD};rect=this.defaultRect;isEditing=!1;isCellReferenceVisible=!1;composerStore;composerFocusStore;composerInterface;get defaultRect(){return{x:0,y:0,width:0,height:0}}setup(){const e=Cc(sM);this.composerStore=e,this.composerFocusStore=Cc(Oc),this.composerInterface={id:"gridComposer",get editionMode(){return e.editionMode},startEdition:this.composerStore.startEdition,setCurrentContent:this.composerStore.setCurrentContent,stopEdition:this.composerStore.stopEdition},this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"inactive"}),t.onWillUpdateProps((()=>{this.updateComponentPosition(),this.updateCellReferenceVisibility()}))}get shouldDisplayCellReference(){return this.isCellReferenceVisible}get cellReference(){const{col:e,row:t,sheetId:o}=this.composerStore.currentEditedCell;return jo(o!==this.env.model.getters.getActiveSheetId()?this.env.model.getters.getSheetName(o):void 0,Co(e,t))}get cellReferenceStyle(){const{x:e,y:t}=this.rect;return Lc({left:e-iM+"px",top:t-28+"px"})}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:"inactive"}get composerProps(){const{width:e,height:t}=this.env.model.getters.getSheetViewDimensionWithHeaders();return{rect:{...this.rect},delimitation:{width:e,height:t},focus:this.focus,isDefaultFocus:!0,onComposerContentFocused:()=>this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"contentFocus"}),onComposerCellFocused:e=>this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"cellFocus",content:e}),onInputContextMenu:this.props.onInputContextMenu,composerStore:this.composerStore}}get containerStyle(){if("inactive"===this.composerStore.editionMode)return"z-index: -1000;";const e=kt(this.composerStore.currentContent),t=this.env.model.getters.getActiveCell(),o=this.env.model.getters.getActivePosition(),s=this.env.model.getters.getCellComputedStyle(o),{x:i,y:n,width:r,height:a}=this.rect,l=!e&&s.fillColor||"#ffffff",c=!e&&s.textColor||"#000000",h=!e&&s.fontSize||10,d=!e&&s.bold?"bold":void 0,u=!e&&s.italic?"italic":"normal",g=e?"none":Nc(s);let p="left";e||(p=s.align||t.defaultAlign);const m=this.props.gridDims.height-this.rect.y;return Lc({left:i-1+"px",top:`${n}px`,"min-width":`${r+1}px`,"min-height":`${a+1}px`,"max-width":`${this.props.gridDims.width-this.rect.x}px`,"max-height":`${m}px`,background:l,color:c,"font-size":`${Qr(h)}px`,"font-weight":d,"font-style":u,"text-decoration":g,"text-align":p})}updateComponentPosition(){const e="inactive"!==this.composerFocusStore.activeComposer.editionMode;if(e||this.composerFocusStore.activeComposer===this.composerInterface||this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"inactive"}),this.isEditing!==e){if(this.isEditing=e,!e)return void(this.rect=this.defaultRect);const t=this.env.model.getters.getActivePosition(),o=this.env.model.getters.expandZone(t.sheetId,vs(t));this.rect=this.env.model.getters.getVisibleRect(o)}}updateCellReferenceVisibility(){if("inactive"===this.composerStore.editionMode)return void(this.isCellReferenceVisible=!1);if(this.isCellReferenceVisible)return;const e=this.env.model.getters.getActiveSheetId(),t=vs(this.env.model.getters.getSelection().anchor.cell);mt(this.env.model.getters.getVisibleRect(t),this.rect)&&e===this.composerStore.currentEditedCell.sheetId||(this.isCellReferenceVisible=!0)}onFocus(){this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:"contentFocus"})}}Pc`
|
|
1538
1538
|
.o-grid-cell-icon {
|
|
1539
1539
|
width: ${le}px;
|
|
1540
1540
|
height: ${le}px;
|
|
1541
1541
|
}
|
|
1542
|
-
`;class
|
|
1542
|
+
`;class rM extends t.Component{static template="o-spreadsheet-GridCellIcon";static props={cellPosition:Object,horizontalAlign:{type:String,optional:!0},verticalAlign:{type:String,optional:!0},slots:Object};get iconStyle(){const e=this.props.cellPosition,t=this.env.model.getters.getMerge(e)||vs(e),o=this.env.model.getters.getVisibleRectWithoutHeaders(t),s=this.getIconHorizontalPosition(o,e);return Lc({top:`${this.getIconVerticalPosition(o,e)}px`,left:`${s}px`})}getIconVerticalPosition(e,t){const o=e.y,s=e.y+e.height,i=this.env.model.getters.getCell(t);switch(this.props.verticalAlign||i?.style?.verticalAlign||ue){case"bottom":return s-2-le;case"top":return o+2;default:const e=Math.floor((s-o-le)/2);return s-le-e}}getIconHorizontalPosition(e,t){const o=e.x,s=e.x+e.width,i=this.env.model.getters.getCell(t),n=this.env.model.getters.getEvaluatedCell(t);switch(this.props.horizontalAlign||i?.style?.align||n.defaultAlign){case"right":return s-2-le;case"left":return o+2;default:const e=Math.floor((s-o-le)/2);return s-le-e}}isPositionVisible(e){const t=this.env.model.getters.getVisibleRect(vs(e));return!(0===t.width||0===t.height)}}Pc`
|
|
1543
1543
|
.o-dv-checkbox {
|
|
1544
1544
|
margin: ${1.5}px;
|
|
1545
1545
|
/* required to prevent the checkbox position to be sensible to the font-size (affects Firefox) */
|
|
1546
1546
|
position: absolute;
|
|
1547
1547
|
}
|
|
1548
|
-
`;class
|
|
1548
|
+
`;class aM extends t.Component{static template="o-spreadsheet-DataValidationCheckbox";static components={Checkbox:HI};static props={cellPosition:Object};onCheckboxChange(e){const{sheetId:t,col:o,row:s}=this.props.cellPosition,i=e?"TRUE":"FALSE";this.env.model.dispatch("UPDATE_CELL",{sheetId:t,col:o,row:s,content:i})}get checkBoxValue(){return!!this.env.model.getters.getEvaluatedCell(this.props.cellPosition).value}get isDisabled(){const e=this.env.model.getters.getCell(this.props.cellPosition);return this.env.model.getters.isReadonly()||!!e?.isFormula}}Pc`
|
|
1549
1549
|
.o-dv-list-icon {
|
|
1550
1550
|
color: ${P};
|
|
1551
1551
|
border-radius: 1px;
|
|
@@ -1562,7 +1562,7 @@
|
|
|
1562
1562
|
height: ${13}px;
|
|
1563
1563
|
}
|
|
1564
1564
|
}
|
|
1565
|
-
`;class
|
|
1565
|
+
`;class lM extends t.Component{static template="o-spreadsheet-DataValidationListIcon";static props={cellPosition:Object};onClick(){const{col:e,row:t}=this.props.cellPosition;this.env.model.selection.selectCell(e,t),this.env.startCellEdition()}}class cM extends t.Component{static template="o-spreadsheet-DataValidationOverlay";static props={};static components={GridCellIcon:rM,DataValidationCheckbox:aM,DataValidationListIcon:lM};get checkBoxCellPositions(){return this.env.model.getters.getVisibleCellPositions().filter((e=>this.env.model.getters.isCellValidCheckbox(e)&&!this.env.model.getters.isFilterHeader(e)))}get listIconsCellPositions(){return this.env.model.getters.isReadonly()?[]:this.env.model.getters.getVisibleCellPositions().filter((e=>this.env.model.getters.cellHasListDataValidationIcon(e)&&!this.env.model.getters.isFilterHeader(e)))}}function hM(e,t){return{...t,...uM(e,{x:t.x,y:t.y})}}function dM(e,t){return{...t,...gM(e,{x:t.x,y:t.y})}}function uM(e,{x:t,y:o}){const{x:s,y:i}=e.getMainViewportCoordinates(),{scrollX:n,scrollY:r}=e.getActiveSheetScrollInfo();return{x:t=t<s?t:t-n,y:o=o<i?o:o-r}}function gM(e,{x:t,y:o}){const{x:s,y:i}=e.getMainViewportCoordinates(),{scrollX:n,scrollY:r}=e.getActiveSheetScrollInfo();return{x:t=s&&t<s?t:t+n,y:o=i&&o<i?o:o+r}}const pM=5;function mM(e,t,o){return o.map((e=>vM(t,e))).filter((o=>function(e,t,o){const{x:s,y:i}=e.getMainViewportCoordinates(),n=[];switch(o.axisType){case"top":case"bottom":case"vCenter":if(t.y<i)return!0;n.push({x:t.x,y:o.position}),n.push({x:t.x+t.width,y:o.position});break;case"left":case"right":case"hCenter":if(t.x<s)return!0;n.push({x:o.position,y:t.y}),n.push({x:o.position,y:t.y+t.height})}return n.some(e.isPixelPositionVisible)}(e,t,o))).map((o=>function(e,t,o){const s=hM(e,t);return vM(s,o.axisType)}(e,t,o)))}function fM(e,t,o,s,i){const n=mM(e,t,o);let r;for(const t of s){const o=mM(e,t,i);for(const e of n)for(const s of o){if(a=e.position,l=s.position,!(Math.abs(a-l)<=pM))continue;const o=e.position-s.position;r&&o===r.snapOffset?r.matchedFigIds.push(t.id):(!r||Math.abs(o)<=Math.abs(r.snapOffset))&&(r={matchedFigIds:[t.id],snapOffset:o,snappedAxisType:e.axisType,position:s.position})}}var a,l;return r}function vM(e,t){let o=0;switch(t){case"top":o=e.y;break;case"bottom":o=e.y+e.height-ye;break;case"vCenter":o=e.y+Math.floor(e.height/2)-ye;break;case"left":o=e.x;break;case"right":o=e.x+e.width-ye;break;case"hCenter":o=e.x+Math.floor(e.width/2)-ye}return{position:o,axisType:t}}Pc`
|
|
1566
1566
|
.o-figure-snap-line {
|
|
1567
1567
|
position: relative;
|
|
1568
1568
|
z-index: ${Oe.FigureSnapLine};
|
|
@@ -1579,7 +1579,7 @@
|
|
|
1579
1579
|
-webkit-user-select: none; /* safari */
|
|
1580
1580
|
user-select: none;
|
|
1581
1581
|
}
|
|
1582
|
-
`;class
|
|
1582
|
+
`;class bM extends t.Component{static template="o-spreadsheet-FiguresContainer";static props={onFigureDeleted:Function};static components={FigureComponent:qF};dnd=t.useState({draggedFigure:void 0,horizontalSnap:void 0,verticalSnap:void 0,cancelDnd:void 0});setup(){t.onMounted((()=>{this.render()})),t.onWillUpdateProps((()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.dnd.draggedFigure?.id;t&&!this.env.model.getters.getFigure(e,t)&&(this.dnd.cancelDnd&&this.dnd.cancelDnd(),this.dnd.draggedFigure=void 0,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0,this.dnd.cancelDnd=void 0)}))}getVisibleFigures(){const e=this.env.model.getters.getVisibleFigures();if(this.dnd.draggedFigure&&!e.some((e=>e.id===this.dnd.draggedFigure?.id))){const t=this.env.model.getters.getFigure(this.env.model.getters.getActiveSheetId(),this.dnd.draggedFigure?.id);t&&e.push(t)}return e}get containers(){const e=this.getVisibleFigures(),t=[];for(const o of["topLeft","topRight","bottomLeft","bottomRight"]){const s=e.filter((e=>this.getFigureContainer(e)===o));s.length>0&&t.push({type:o,figures:s,style:this.getContainerStyle(o),inverseViewportStyle:this.getInverseViewportPositionStyle(o)})}return this.dnd.draggedFigure&&t.push({type:"dnd",figures:[this.getDndFigure()],style:this.getContainerStyle("dnd"),inverseViewportStyle:this.getInverseViewportPositionStyle("dnd")}),t}getContainerStyle(e){return this.rectToCss(this.getContainerRect(e))}rectToCss(e){return Lc({left:`${e.x}px`,top:`${e.y}px`,width:`${e.width}px`,height:`${e.height}px`})}getContainerRect(e){const{width:t,height:o}=this.env.model.getters.getSheetViewDimension(),{x:s,y:i}=this.env.model.getters.getMainViewportCoordinates(),n=["bottomRight","topRight"].includes(e)?s:0,r=t-n,a=["bottomRight","bottomLeft"].includes(e)?i:0;return{x:n,y:a,width:r,height:o-a}}getInverseViewportPositionStyle(e){const{scrollX:t,scrollY:o}=this.env.model.getters.getActiveSheetScrollInfo(),{x:s,y:i}=this.env.model.getters.getMainViewportCoordinates();return Lc({left:`${["bottomRight","topRight"].includes(e)?-(s+t):0}px`,top:`${["bottomRight","bottomLeft"].includes(e)?-(i+o):0}px`})}getFigureContainer(e){const{x:t,y:o}=this.env.model.getters.getMainViewportCoordinates();return e.id===this.dnd.draggedFigure?.id?"dnd":e.x<t&&e.y<o?"topLeft":e.x<t?"bottomLeft":e.y<o?"topRight":"bottomRight"}startDraggingFigure(e,t){if(t.button>0||this.env.model.getters.isReadonly())return;if(!this.env.model.dispatch("SELECT_FIGURE",{id:e.id}).isSuccessful)return;const o=this.env.model.getters.getActiveSheetId(),s={x:t.clientX,y:t.clientY},i={maxX:this.env.model.getters.getColDimensions(o,this.env.model.getters.getNumberCols(o)-1).end,maxY:this.env.model.getters.getRowDimensions(o,this.env.model.getters.getNumberRows(o)-1).end},{x:n,y:r}=hM(this.env.model.getters,e),a={...e,x:n,y:r};this.dnd.cancelDnd=K_((t=>{const o=this.env.model.getters,n=function({x:e,y:t},{x:o,y:s},i,{x:n,y:r},{maxX:a,maxY:l},{scrollX:c,scrollY:h}){const d=n?0:-c,u=r?0:-h,g=e-o,p=qe(i.x+g,d,a-i.width-c),m=t-s,f=qe(i.y+m,u,l-i.height-h);return{...i,x:p,y:f}}({x:t.clientX,y:t.clientY},s,a,this.env.model.getters.getMainViewportCoordinates(),i,o.getActiveSheetScrollInfo()),r=this.getOtherFigures(e.id),l=function(e,t,o){const s={...t},i=fM(e,s,["hCenter","right","left"],o,["hCenter","right","left"]),n=fM(e,s,["vCenter","bottom","top"],o,["vCenter","bottom","top"]),{y:r,x:a}=e.getMainViewportCoordinates(),{scrollY:l,scrollX:c}=e.getActiveSheetScrollInfo();if(n){s.y-=n.snapOffset;const e=t.y<r,o=s.y<r;e&&!o?s.y+=l:!e&&o&&(s.y-=l)}if(i){s.x-=i.snapOffset;const e=t.x<a,o=s.x<a;e&&!o?s.x+=c:!e&&o&&(s.x-=c)}return{snappedFigure:s,verticalSnapLine:i,horizontalSnapLine:n}}(o,dM(o,n),r);this.dnd.draggedFigure=hM(o,l.snappedFigure),this.dnd.horizontalSnap=this.getSnap(l.horizontalSnapLine),this.dnd.verticalSnap=this.getSnap(l.verticalSnapLine)}),(t=>{if(!this.dnd.draggedFigure)return;let{x:s,y:i}=dM(this.env.model.getters,this.dnd.draggedFigure);this.dnd.draggedFigure=void 0,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0,this.env.model.dispatch("UPDATE_FIGURE",{sheetId:o,id:e.id,x:s,y:i})}))}startResize(e,t,o,s){s.stopPropagation();const i={x:s.clientX,y:s.clientY},{x:n,y:r}=hM(this.env.model.getters,e),a={...e,x:n,y:r},l=bI.get(e.tag).keepRatio||!1,c=bI.get(e.tag).minFigSize||80;this.dnd.cancelDnd=K_((s=>{const n={x:s.clientX,y:s.clientY},r=function(e,t,o,{x:s,y:i},{x:n,y:r},a,l,{scrollX:c,scrollY:h}){let{x:d,y:u,width:g,height:p}=e;if(a&&0!=t&&0!=o){const a=Math.min(t*(n-s),e.width-l),c=Math.min(o*(r-i),e.height-l),h=Math.min(a/e.width,c/e.height);g=e.width*(1-h),p=e.height*(1-h),t<0&&(d=e.x+e.width*h),o<0&&(u=e.y+e.height*h)}else{const a=Math.max(t*(s-n),l-e.width),c=Math.max(o*(i-r),l-e.height);g=e.width+a,p=e.height+c,t<0&&(d=e.x-a),o<0&&(u=e.y-c)}return d+c<=0&&(g=g+d+c,d=-c),u+h<=0&&(p=p+u+h,u=-h),{...e,x:d,y:u,width:g,height:p}}(a,t,o,n,i,l,c,this.env.model.getters.getActiveSheetScrollInfo()),h=this.getOtherFigures(e.id),d=function(e,t,o,s,i){const n={...s},r=fM(e,n,[-1===t?"left":"right"],i,["right","left"]);r&&(1===t?n.width-=r.snapOffset:-1===t&&(n.x-=r.snapOffset,n.width+=r.snapOffset));const a=fM(e,n,[-1===o?"top":"bottom"],i,["bottom","top"]);return a&&(1===o?n.height-=a.snapOffset:-1===o&&(n.y-=a.snapOffset,n.height+=a.snapOffset)),n.x=Math.round(n.x),n.y=Math.round(n.y),n.height=Math.round(n.height),n.width=Math.round(n.width),{snappedFigure:n,verticalSnapLine:r,horizontalSnapLine:a}}(this.env.model.getters,t,o,r,h);this.dnd.draggedFigure=d.snappedFigure,this.dnd.horizontalSnap=this.getSnap(d.horizontalSnapLine),this.dnd.verticalSnap=this.getSnap(d.verticalSnapLine)}),(s=>{if(!this.dnd.draggedFigure)return;let{x:i,y:n}=dM(this.env.model.getters,this.dnd.draggedFigure);const r={x:i,y:n};t&&(r.width=this.dnd.draggedFigure.width),o&&(r.height=this.dnd.draggedFigure.height),this.env.model.dispatch("UPDATE_FIGURE",{sheetId:this.env.model.getters.getActiveSheetId(),id:e.id,...r}),this.dnd.draggedFigure=void 0,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0}))}getOtherFigures(e){return this.getVisibleFigures().filter((t=>t.id!==e))}getDndFigure(){const e=this.getVisibleFigures().find((e=>e.id===this.dnd.draggedFigure?.id));if(!e)throw new Error("Dnd figure not found");return{...e,...this.dnd.draggedFigure}}getFigureStyle(e){return e.id!==this.dnd.draggedFigure?.id?"":Lc({opacity:"0.9",cursor:"grabbing"})}getSnap(e){if(!e||!this.dnd.draggedFigure)return;const t=e.matchedFigIds.map((e=>this.getVisibleFigures().find((t=>t.id===e)))).filter(at).map((e=>{const t=hM(this.env.model.getters,e),o=this.getFigureContainer(e);return _I(t,this.getContainerRect(o))})).filter(at),o=function(...e){return OI(is(...e.map(DI)))}(this.dnd.draggedFigure,...t);return{line:e,containerStyle:this.rectToCss(o),lineStyle:this.getSnapLineStyle(e,o)}}getSnapLineStyle(e,t){return e?["top","vCenter","bottom"].includes(e.snappedAxisType)?Lc({top:e.position-t.y+"px",left:"0px",width:"100%"}):Lc({top:"0px",left:e.position-t.x+"px",height:"100%"}):""}}Pc`
|
|
1583
1583
|
.o-filter-icon {
|
|
1584
1584
|
color: ${S};
|
|
1585
1585
|
display: flex;
|
|
@@ -1605,7 +1605,7 @@
|
|
|
1605
1605
|
background: ${S};
|
|
1606
1606
|
color: #fff;
|
|
1607
1607
|
}
|
|
1608
|
-
`;class
|
|
1608
|
+
`;class SM extends t.Component{static template="o-spreadsheet-FilterIcon";static props={cellPosition:Object};cellPopovers;setup(){this.cellPopovers=Cc(AI)}onClick(){const e=this.props.cellPosition,t=this.cellPopovers.persistentCellPopover,{col:o,row:s}=e;t.isOpen&&t.col===o&&t.row===s&&"FilterMenu"===t.type?this.cellPopovers.close():this.cellPopovers.open({col:o,row:s},"FilterMenu")}get isFilterActive(){return this.env.model.getters.isFilterActive(this.props.cellPosition)}get iconClass(){return qt(this.env.model.getters.getCellComputedStyle(this.props.cellPosition).fillColor||"#fff")<.45?"o-high-contrast":""}}class yM extends t.Component{static template="o-spreadsheet-FilterIconsOverlay";static props={};static components={GridCellIcon:rM,FilterIcon:SM};getFilterHeadersPositions(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getFilterHeaders(e)}}Pc`
|
|
1609
1609
|
.o-grid-add-rows {
|
|
1610
1610
|
input.o-input {
|
|
1611
1611
|
width: 60px;
|
|
@@ -1618,11 +1618,11 @@
|
|
|
1618
1618
|
margin-left: 8px;
|
|
1619
1619
|
}
|
|
1620
1620
|
}
|
|
1621
|
-
`;class
|
|
1621
|
+
`;class CM extends t.Component{static template="o-spreadsheet-GridAddRowsFooter";static props={focusGrid:Function};static components={ValidationMessages:hD};inputRef=t.useRef("inputRef");state=t.useState({inputValue:"100",errorFlag:!1});setup(){t.useExternalListener(window,"click",this.onExternalClick,{capture:!0})}get addRowsPosition(){const e=this.env.model.getters.getActiveSheetId(),{numberOfRows:t}=this.env.model.getters.getSheetSize(e),{scrollY:o}=this.env.model.getters.getActiveSheetScrollInfo();return Lc({top:`${this.env.model.getters.getRowDimensions(e,t-1).end-o}px`})}get errorMessages(){return[Mo("Please enter a number between 0 and 10000.")]}onKeydown(e){"ESCAPE"===e.key.toUpperCase()?this.props.focusGrid():"ENTER"===e.key.toUpperCase()&&this.onConfirm()}onInput(e){const t=e.target.value;this.state.inputValue=t;const o=Number(t);this.state.errorFlag=Number.isNaN(o)||o<=0||o>1e4}onConfirm(){if(this.state.errorFlag)return;const e=Number(this.state.inputValue),t=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getNumberRows(t);this.env.model.dispatch("ADD_COLUMNS_ROWS",{sheetId:t,position:"after",base:o-1,quantity:e,dimension:"ROW"}),this.props.focusGrid();const{scrollX:s}=this.env.model.getters.getActiveSheetScrollInfo(),{end:i}=this.env.model.getters.getRowDimensions(t,o+e-1);this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:s,offsetY:i})}onExternalClick(e){this.inputRef.el===document.activeElement&&e.target!==this.inputRef.el&&this.props.focusGrid()}}class wM extends _c{mutators=["activate","cancel","pasteFormat"];highlightStore=this.get(Jb);clipboardHandlers=[new cc(this.getters,this.model.dispatch),new pa(this.getters,this.model.dispatch),new uc(this.getters,this.model.dispatch),new dc(this.getters,this.model.dispatch)];status="inactive";copiedData;constructor(e){super(e),this.highlightStore.register(this),this.onDispose((()=>{this.highlightStore.unRegister(this)}))}handle(e){if("PAINT_FORMAT"===e.type)this.paintFormat(e.sheetId,e.target)}activate(e){this.copiedData=this.copyFormats(),this.status=e.persistent?"persistent":"oneOff"}cancel(){this.status="inactive",this.copiedData=void 0}pasteFormat(e){this.model.dispatch("PAINT_FORMAT",{target:e,sheetId:this.getters.getActiveSheetId()})}get isActive(){return"inactive"!==this.status}copyFormats(){const e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZones(),o={};for(const s of this.clipboardHandlers)Object.assign(o,s.copy(ca(e,t)));return o}paintFormat(e,t){if(this.copiedData)for(const o of this.clipboardHandlers)o.paste({zones:t,sheetId:e},this.copiedData,{isCutOperation:!1,pasteOption:"onlyFormat"});"oneOff"===this.status&&this.cancel()}get highlights(){const e=this.copiedData;return e?e.zones.map((t=>({zone:t,color:p,dashed:!0,sheetId:e.sheetId,noFill:!0,thinLine:!0,interactive:!1}))):[]}}function EM(e,o,s){let i={col:void 0,row:void 0};const{Date:n}=window;let r,a,l=0;function c(){if(void 0===r||void 0===a)return{col:-1,row:-1};return{col:e.model.getters.getColIndex(r),row:e.model.getters.getRowIndex(a)}}const{pause:h,resume:d}=function(e,o){let s;const{setInterval:i,clearInterval:n}=window;return t.useEffect((()=>(s=i(e,o),()=>n(s))),(()=>[o])),{pause:()=>{n(s),s=void 0},resume:()=>{void 0===s&&(s=i(e,o))}}}((function(){const{col:e,row:t}=c(),o=n.now()-l;o>300&&(e!==i.col||t!==i.row)&&g(void 0,void 0);if(o>300){if(e<0||t<0)return;g(e,t)}}),200);function u(e){o.el===e.target&&(r=e.offsetX,a=e.offsetY,l=n.now())}function g(e,t){e===i.col&&t===i.row||(i.col=e,i.row=t,s({col:e,row:t}))}return cO(o,"pointermove",u),cO(o,"mouseleave",(function(e){const t=e.offsetX,s=e.offsetY,i=YI(o.el);return s<0||s>i.height||t<0||t>i.width?u(e):h()})),cO(o,"mouseenter",d),cO(o,"pointerdown",(function(){const{col:e,row:t}=c();e===i.col&&t===i.row||g(void 0,void 0)})),t.useExternalListener(window,"click",(function(e){const t=e.target;o.el.contains(t)||g(void 0,void 0)})),i}Pc`
|
|
1622
1622
|
.o-paint-format-cursor {
|
|
1623
1623
|
cursor: url("data:image/svg+xml,${encodeURIComponent('\n<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="14" height="16"><path d="M6.5.4c1.3-.8 2.9-.1 3.8 1.4l2.9 5.1c.2.4.9 1.6-.4 2.3l-1.6.9 1.8 3.1c.2.4.1 1-.2 1.2l-1.6 1c-.3.1-.9 0-1.1-.4l-1.8-3.1-1.6 1c-.6.4-1.7 0-2.2-.8L0 4.3"/><path fill="#fff" d="M9.1 2a1.4 1.1 60 0 0-1.7-.6L5.5 2.5l.9 1.6-1 .6-.9-1.6-.6.4 1.8 3.1-1.3.7-1.8-3.1-1 .6 3.8 6.6 6.8-3.98M3.9 8.8 10.82 5l.795 1.4-6.81 3.96"/></svg>\n')}"), auto;
|
|
1624
1624
|
}
|
|
1625
|
-
`;class
|
|
1625
|
+
`;class xM extends t.Component{static template="o-spreadsheet-GridOverlay";static props={onCellHovered:{type:Function,optional:!0},onCellDoubleClicked:{type:Function,optional:!0},onCellClicked:{type:Function,optional:!0},onCellRightClicked:{type:Function,optional:!0},onGridResized:{type:Function,optional:!0},onFigureDeleted:{type:Function,optional:!0},onGridMoved:Function,gridOverlayDimensions:String};static components={FiguresContainer:bM,DataValidationOverlay:cM,GridAddRowsFooter:CM,FilterIconsOverlay:yM};static defaultProps={onCellHovered:()=>{},onCellDoubleClicked:()=>{},onCellClicked:()=>{},onCellRightClicked:()=>{},onGridResized:()=>{},onFigureDeleted:()=>{}};gridOverlay=t.useRef("gridOverlay");gridOverlayRect=MI(this.gridOverlay);cellPopovers;paintFormatStore;setup(){EM(this.env,this.gridOverlay,this.props.onCellHovered);const e=new ResizeObserver((()=>{const e=this.gridOverlayEl.getBoundingClientRect();this.props.onGridResized({x:e.left,y:e.top,height:this.gridOverlayEl.clientHeight,width:this.gridOverlayEl.clientWidth})}));t.onMounted((()=>{e.observe(this.gridOverlayEl)})),t.onWillUnmount((()=>{e.disconnect()})),function(e,t,o){let s=null,i=null;cO(e,"touchstart",(function(e){1===e.touches.length&&(s=e.touches[0].clientX,i=e.touches[0].clientY)})),cO(e,"touchend",(function(){s=null,i=null})),cO(e,"touchmove",(function(e){if(1!==e.touches.length)return;o()&&(e.preventDefault(),e.stopPropagation());const n=e.touches[0].clientX,r=e.touches[0].clientY;t(s-n,i-r),s=n,i=r}))}(this.gridOverlay,this.props.onGridMoved,(()=>{const{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0})),this.cellPopovers=Cc(AI),this.paintFormatStore=Cc(wM)}get gridOverlayEl(){if(!this.gridOverlay.el)throw new Error("GridOverlay el is not defined.");return this.gridOverlay.el}get style(){return this.props.gridOverlayDimensions}get isPaintingFormat(){return this.paintFormatStore.isActive}onMouseDown(e){if(e.button>0)return;e.target===this.gridOverlay.el&&this.cellPopovers.isOpen&&this.cellPopovers.close();const[t,o]=this.getCartesianCoordinates(e);this.props.onCellClicked(t,o,{expandZone:e.shiftKey,addZone:oR(e)})}onDoubleClick(e){const[t,o]=this.getCartesianCoordinates(e);this.props.onCellDoubleClicked(t,o)}onContextMenu(e){const[t,o]=this.getCartesianCoordinates(e);this.props.onCellRightClicked(t,o,{x:e.clientX,y:e.clientY})}getCartesianCoordinates(e){const t=e.clientX-this.gridOverlayRect.x,o=e.clientY-this.gridOverlayRect.y;return[this.env.model.getters.getColIndex(t),this.env.model.getters.getRowIndex(o)]}}class IM extends t.Component{static template="o-spreadsheet-GridPopover";static props={onClosePopover:Function,onMouseWheel:Function,gridRect:Object};static components={Popover:PI};cellPopovers;zIndex=Oe.GridPopover;setup(){this.cellPopovers=Cc(AI)}get cellPopover(){const e=this.cellPopovers.cellPopover;if(!e.isOpen)return{isOpen:!1};const t=e.anchorRect;return{...e,anchorRect:{...t,x:t.x+this.props.gridRect.x,y:t.y+this.props.gridRect.y}}}}class RM extends t.Component{static props={onOpenContextMenu:Function};composerFocusStore;PADDING=0;MAX_SIZE_MARGIN=0;MIN_ELEMENT_SIZE=0;lastSelectedElementIndex=null;state=t.useState({resizerIsActive:!1,isResizing:!1,isMoving:!1,isSelecting:!1,waitingForMove:!1,activeElement:0,draggerLinePosition:0,draggerShadowPosition:0,draggerShadowThickness:0,delta:0,base:0,position:"before"});setup(){this.composerFocusStore=Cc(Oc)}_computeHandleDisplay(e){const t=this._getEvOffset(e),o=this._getElementIndex(t);if(o<0)return;const s=this._getDimensionsInViewport(o);t-s.start<this.PADDING&&o!==this._getViewportOffset()?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=s.start,this.state.activeElement=this._getPreviousVisibleElement(o)):s.end-t<this.PADDING?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=s.end,this.state.activeElement=o):this.state.resizerIsActive=!1}_computeGrabDisplay(e){const t=this._getElementIndex(this._getEvOffset(e)),o=this._getActiveElements(),s=this._getSelectedZoneStart(),i=this._getSelectedZoneEnd();o.has(s)&&s<=t&&t<=i?this.state.waitingForMove=!0:this.state.waitingForMove=!1}onMouseMove(e){this.state.isResizing||this.state.isMoving||this.state.isSelecting||(this._computeHandleDisplay(e),this._computeGrabDisplay(e))}onMouseLeave(){this.state.resizerIsActive=this.state.isResizing,this.state.waitingForMove=!1}onDblClick(e){this._fitElementSize(this.state.activeElement),this.state.isResizing=!1,this._computeHandleDisplay(e),this._computeGrabDisplay(e)}onMouseDown(e){this.state.isResizing=!0,this.state.delta=0;const t=this._getClientPosition(e),o=this.state.draggerLinePosition,s=this._getElementSize(this.state.activeElement),i=o-s+this.MIN_ELEMENT_SIZE,n=this._getMaxSize();K_((e=>{this.state.delta=this._getClientPosition(e)-t,this.state.draggerLinePosition=o+this.state.delta,this.state.draggerLinePosition<i&&(this.state.draggerLinePosition=i,this.state.delta=this.MIN_ELEMENT_SIZE-s),this.state.draggerLinePosition>n&&(this.state.draggerLinePosition=n,this.state.delta=n-o)}),(e=>{this.state.isResizing=!1,0!==this.state.delta&&this._updateSize()}))}select(e){if(e.button>0)return;const t=this._getElementIndex(this._getEvOffset(e));t<0||(this.state.waitingForMove?this.env.model.getters.isGridSelectionActive()?this.startMovement(e):this._selectElement(t,!1):("editing"===this.composerFocusStore.activeComposer.editionMode&&this.env.model.selection.getBackToDefault(),this.startSelection(e,t)))}startMovement(e){this.state.waitingForMove=!1,this.state.isMoving=!0;const t=this._getDimensionsInViewport(this._getSelectedZoneStart()),o=this._getDimensionsInViewport(this._getSelectedZoneEnd()),s=t.start;this.state.draggerLinePosition=s,this.state.base=this._getSelectedZoneStart(),this.state.draggerShadowPosition=s,this.state.draggerShadowThickness=o.end-t.start;J_(this.env,((e,o)=>{let s="COL"===this._getType()?e:o;if(s>=0){const e=this._getDimensionsInViewport(s);s<=this._getSelectedZoneStart()?(this.state.draggerLinePosition=e.start,this.state.draggerShadowPosition=e.start,this.state.base=s,this.state.position="before"):this._getSelectedZoneEnd()<s?(this.state.draggerLinePosition=e.end,this.state.draggerShadowPosition=e.end-this.state.draggerShadowThickness,this.state.base=s,this.state.position="after"):(this.state.draggerLinePosition=t.start,this.state.draggerShadowPosition=t.start,this.state.base=this._getSelectedZoneStart())}}),(()=>{this.state.isMoving=!1,this.state.base!==this._getSelectedZoneStart()&&this._moveElements(),this._computeGrabDisplay(e)}))}startSelection(e,t){this.state.isSelecting=!0,e.shiftKey?this._increaseSelection(t):this._selectElement(t,oR(e)),this.lastSelectedElementIndex=t;J_(this.env,((e,t)=>{let o="COL"===this._getType()?e:t;o!==this.lastSelectedElementIndex&&-1!==o&&(this._increaseSelection(o),this.lastSelectedElementIndex=o)}),(()=>{this.state.isSelecting=!1,this.lastSelectedElementIndex=null,this._computeGrabDisplay(e)}))}onMouseUp(e){this.lastSelectedElementIndex=null}onContextMenu(e){e.preventDefault();const t=this._getElementIndex(this._getEvOffset(e));if(t<0)return;this._getActiveElements().has(t)||this._selectElement(t,!1);const o=this._getType();this.props.onOpenContextMenu(o,e.clientX,e.clientY)}}Pc`
|
|
1626
1626
|
.o-col-resizer {
|
|
1627
1627
|
position: absolute;
|
|
1628
1628
|
top: 0;
|
|
@@ -1672,7 +1672,7 @@
|
|
|
1672
1672
|
background-color: lightgrey;
|
|
1673
1673
|
}
|
|
1674
1674
|
}
|
|
1675
|
-
`;class
|
|
1675
|
+
`;class TM extends RM{static props={onOpenContextMenu:Function};static template="o-spreadsheet-ColResizer";colResizerRef;setup(){super.setup(),this.colResizerRef=t.useRef("colResizer"),this.PADDING=15,this.MAX_SIZE_MARGIN=90,this.MIN_ELEMENT_SIZE=5}_getEvOffset(e){return e.offsetX}_getViewportOffset(){return this.env.model.getters.getActiveMainViewport().left}_getClientPosition(e){return e.clientX}_getElementIndex(e){return this.env.model.getters.getColIndex(e)}_getSelectedZoneStart(){return this.env.model.getters.getSelectedZone().left}_getSelectedZoneEnd(){return this.env.model.getters.getSelectedZone().right}_getEdgeScroll(e){return this.env.model.getters.getEdgeScrollCol(e,e,e)}_getDimensionsInViewport(e){return this.env.model.getters.getColDimensionsInViewport(this.env.model.getters.getActiveSheetId(),e)}_getElementSize(e){return this.env.model.getters.getColSize(this.env.model.getters.getActiveSheetId(),e)}_getMaxSize(){return this.colResizerRef.el.clientWidth}_updateSize(){const e=this.state.activeElement,t=this.state.delta+this._getElementSize(e),o=this.env.model.getters.getActiveCols();this.env.model.dispatch("RESIZE_COLUMNS_ROWS",{dimension:"COL",sheetId:this.env.model.getters.getActiveSheetId(),elements:o.has(e)?[...o]:[e],size:t})}_moveElements(){const e=[],t=this._getSelectedZoneStart(),o=this._getSelectedZoneEnd();for(let s=t;s<=o;s++)e.push(s);const s=this.env.model.dispatch("MOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"COL",base:this.state.base,elements:e,position:this.state.position});!s.isSuccessful&&s.reasons.includes("WillRemoveExistingMerge")&&this.env.raiseError(vE)}_selectElement(e,t){this.env.model.selection.selectColumn(e,t?"newAnchor":"overrideSelection")}_increaseSelection(e){this.env.model.selection.selectColumn(e,"updateAnchor")}_fitElementSize(e){const t=this.env.model.getters.getActiveCols();this.env.model.dispatch("AUTORESIZE_COLUMNS",{sheetId:this.env.model.getters.getActiveSheetId(),cols:t.has(e)?[...t]:[e]})}_getType(){return"COL"}_getActiveElements(){return this.env.model.getters.getActiveCols()}_getPreviousVisibleElement(e){const t=this.env.model.getters.getActiveSheetId();let o;for(o=e-1;o>=0&&this.env.model.getters.isColHidden(t,o);o--);return o}unhide(e){this.env.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),elements:e,dimension:"COL"})}getUnhideButtonStyle(e){return Lc({left:this._getDimensionsInViewport(e).start+"px"})}}Pc`
|
|
1676
1676
|
.o-row-resizer {
|
|
1677
1677
|
position: absolute;
|
|
1678
1678
|
top: ${ee}px;
|
|
@@ -1723,7 +1723,7 @@
|
|
|
1723
1723
|
background-color: lightgrey;
|
|
1724
1724
|
}
|
|
1725
1725
|
}
|
|
1726
|
-
`;class
|
|
1726
|
+
`;class AM extends RM{static props={onOpenContextMenu:Function};static template="o-spreadsheet-RowResizer";setup(){super.setup(),this.rowResizerRef=t.useRef("rowResizer"),this.PADDING=5,this.MAX_SIZE_MARGIN=60,this.MIN_ELEMENT_SIZE=10}rowResizerRef;_getEvOffset(e){return e.offsetY}_getViewportOffset(){return this.env.model.getters.getActiveMainViewport().top}_getClientPosition(e){return e.clientY}_getElementIndex(e){return this.env.model.getters.getRowIndex(e)}_getSelectedZoneStart(){return this.env.model.getters.getSelectedZone().top}_getSelectedZoneEnd(){return this.env.model.getters.getSelectedZone().bottom}_getEdgeScroll(e){return this.env.model.getters.getEdgeScrollRow(e,e,e)}_getDimensionsInViewport(e){return this.env.model.getters.getRowDimensionsInViewport(this.env.model.getters.getActiveSheetId(),e)}_getElementSize(e){return this.env.model.getters.getRowSize(this.env.model.getters.getActiveSheetId(),e)}_getMaxSize(){return this.rowResizerRef.el.clientHeight}_updateSize(){const e=this.state.activeElement,t=this.state.delta+this._getElementSize(e),o=this.env.model.getters.getActiveRows();this.env.model.dispatch("RESIZE_COLUMNS_ROWS",{dimension:"ROW",sheetId:this.env.model.getters.getActiveSheetId(),elements:o.has(e)?[...o]:[e],size:t})}_moveElements(){const e=[],t=this._getSelectedZoneStart(),o=this._getSelectedZoneEnd();for(let s=t;s<=o;s++)e.push(s);const s=this.env.model.dispatch("MOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"ROW",base:this.state.base,elements:e,position:this.state.position});!s.isSuccessful&&s.reasons.includes("WillRemoveExistingMerge")&&this.env.raiseError(vE)}_selectElement(e,t){this.env.model.selection.selectRow(e,t?"newAnchor":"overrideSelection")}_increaseSelection(e){this.env.model.selection.selectRow(e,"updateAnchor")}_fitElementSize(e){const t=this.env.model.getters.getActiveRows();this.env.model.dispatch("AUTORESIZE_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),rows:t.has(e)?[...t]:[e]})}_getType(){return"ROW"}_getActiveElements(){return this.env.model.getters.getActiveRows()}_getPreviousVisibleElement(e){const t=this.env.model.getters.getActiveSheetId();let o;for(o=e-1;o>=0&&this.env.model.getters.isRowHidden(t,o);o--);return o}unhide(e){this.env.model.dispatch("UNHIDE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"ROW",elements:e})}getUnhideButtonStyle(e){return Lc({top:this._getDimensionsInViewport(e).start+"px"})}}Pc`
|
|
1727
1727
|
.o-overlay {
|
|
1728
1728
|
.all {
|
|
1729
1729
|
position: absolute;
|
|
@@ -1734,7 +1734,7 @@
|
|
|
1734
1734
|
height: ${ee}px;
|
|
1735
1735
|
}
|
|
1736
1736
|
}
|
|
1737
|
-
`;class AM extends t.Component{static props={onOpenContextMenu:Function};static template="o-spreadsheet-HeadersOverlay";static components={ColResizer:RM,RowResizer:TM};selectAll(){this.env.model.selection.selectAll()}}class _M{getters;renderer;fingerprints;constructor(e){this.getters=e(Rc).getters,this.renderer=e(Ac),this.fingerprints=e(p_),this.renderer.register(this)}get renderingLayers(){return["Background","Headers"]}drawLayer(e,t){switch(t){case"Background":this.drawGlobalBackground(e);for(const{zone:t,rect:o}of this.getters.getAllActiveViewportsZonesAndRect()){const{ctx:s}=e;s.save(),s.beginPath(),s.rect(o.x,o.y,o.width,o.height),s.clip();const i=this.getGridBoxes(t);this.drawBackground(e,i),this.drawOverflowingCellBackground(e,i),this.drawCellBackground(e,i),this.drawBorders(e,i),this.drawTexts(e,i),this.drawIcon(e,i),s.restore()}this.drawFrozenPanes(e);break;case"Headers":this.getters.isDashboard()||(this.drawHeaders(e),this.drawFrozenPanesHeaders(e))}}drawGlobalBackground(e){const{ctx:t}=e,{width:o,height:s}=this.getters.getSheetViewDimensionWithHeaders();t.fillStyle="#ffffff",t.fillRect(0,0,o+r,s+r)}drawBackground(e,t){const{ctx:o,thinLineWidth:s}=e,i=!this.getters.isDashboard()&&this.getters.getGridLinesVisibility(this.getters.getActiveSheetId()),n=i?.1*s:0;if(i)for(const e of t)o.strokeStyle="#E2E3E3",o.lineWidth=s,o.strokeRect(e.x+n,e.y+n,e.width-2*n,e.height-2*n)}drawCellBackground(e,t){const{ctx:o}=e;for(const e of t){let t=e.style;if(t.fillColor&&"#ffffff"!==t.fillColor&&(o.fillStyle=t.fillColor||"#ffffff",o.fillRect(e.x,e.y,e.width,e.height)),e.dataBarFill){o.fillStyle=e.dataBarFill.color;const t=e.dataBarFill.percentage,s=e.width*(t/100);o.fillRect(e.x,e.y,s,e.height)}e.isError&&(o.fillStyle="red",o.beginPath(),o.moveTo(e.x+e.width-5,e.y),o.lineTo(e.x+e.width,e.y),o.lineTo(e.x+e.width,e.y+5),o.fill())}}drawOverflowingCellBackground(e,t){const{ctx:o,thinLineWidth:s}=e;for(const e of t)if(e.content&&e.isOverflow){const t=e.content.align||"left";let i,n;const r=e.y+s/2,a=e.height-s,l=Math.min(e.clipRect?.width||1/0,e.content.width);"left"===t?(i=e.x+s/2,n=l-2*s):"right"===t?(i=e.x+e.width-s/2,n=2*s-l):(i=(e.clipRect?.x||e.x+e.width/2-e.content.width/2)+s/2,n=l-2*s),o.fillStyle="#ffffff",o.fillRect(i,r,n,a)}}drawBorders(e,t){const{ctx:o}=e;for(let e of t){const t=e.border;if(t){const{x:o,y:i,width:n,height:r}=e;t.left&&s(t.left,o,i,o,i+r),t.top&&s(t.top,o,i,o+n,i),t.right&&s(t.right,o+n,i,o+n,i+r),t.bottom&&s(t.bottom,o,i+r,o+n,i+r)}}function s({style:e,color:t},s,i,n,r){switch(o.strokeStyle=t,e){case"medium":o.lineWidth=2,i+=(s+=i===r?-.5:.5)===(n+=i===r?1.5:.5)?-.5:.5,r+=s===n?1.5:.5;break;case"thick":o.lineWidth=3,i===r&&(s--,n++),s===n&&(i--,r++);break;case"dashed":o.lineWidth=1,o.setLineDash([1,3]);break;case"dotted":o.lineWidth=1,i===r&&(s+=.5,n+=.5),s===n&&(i+=.5,r+=.5),o.setLineDash([1,1]);break;default:o.lineWidth=1}o.beginPath(),o.moveTo(s,i),o.lineTo(n,r),o.stroke(),o.lineWidth=1,o.setLineDash([])}}drawTexts(e,t){const{ctx:o}=e;let s;o.textBaseline="top";for(let e of t)if(e.content){const t=e.style||{},i=e.content.align||"left",n=ea(t);n!==s&&(s=n,o.font=n),o.fillStyle=t.textColor||"#000";let r=e.x;if(r+="left"===i?ne+(e.image?e.image.size+4:0):"right"===i?e.width-ne-(e.hasIcon?19:0):e.width/2,o.textAlign=i,e.clipRect){o.save(),o.beginPath();const{x:t,y:s,width:i,height:n}=e.clipRect;o.rect(t,s,i,n),o.clip()}const a=ta(t),l=e.content.textLines.length;let c=this.computeTextYCoordinate(e,a,l);for(let s of e.content.textLines)aa(o,s,{x:Math.round(r),y:Math.round(c)},t.underline,t.strikethrough),c+=ne+a;e.clipRect&&o.restore()}}drawIcon(e,t){const{ctx:o}=e;for(const e of t)if(e.image){const t=e.image.image;if(e.image.clipIcon){o.save(),o.beginPath();const{x:t,y:s,width:i,height:n}=e.image.clipIcon;o.rect(t,s,i,n),o.clip()}const s=e.image.size,i=this.computeTextYCoordinate(e,s);o.drawImage(t,e.x+4,i,s,s),e.image.clipIcon&&o.restore()}}computeTextYCoordinate(e,t,o=1){const s=e.y+1,i=qr(t,o),n=e.height>i+2*ne,r=e.verticalAlign||ue;if(n){if("middle"===r)return s+(e.height-i)/2;if("bottom"===r)return s+e.height-i-ne}return s+ne}drawHeaders(e){const{ctx:t,thinLineWidth:o}=e,s=this.getters.getSheetViewVisibleCols(),i=s[0],n=this.getters.getSheetViewVisibleRows(),r=n[0],{width:a,height:l}=this.getters.getSheetViewDimensionWithHeaders(),g=this.getters.getSelectedZones(),p=function(e){const t=new Set;for(let o of wo(e))for(let e of Ze(o.left,o.right+1))t.add(e);return t}(g),m=function(e){const t=new Set;for(let o of wo(e))for(let e of Ze(o.top,o.bottom+1))t.add(e);return t}(g),f=this.getters.getActiveSheetId(),v=this.getters.getNumberCols(f),b=this.getters.getNumberRows(f),S=this.getters.getActiveCols(),y=this.getters.getActiveRows();t.font=`400 11px ${fe}`,t.textAlign="center",t.textBaseline="middle",t.lineWidth=o,t.strokeStyle="#333";for(const e of s){const o={left:e,right:e,top:0,bottom:b-1},{x:s,width:i}=this.getters.getVisibleRect(o),n=S.has(e),r=p.has(e);t.fillStyle=n?d:r?h:c,t.fillRect(s,0,i,ee)}for(const e of n){const o={top:e,bottom:e,left:0,right:v-1},{y:s,height:i}=this.getters.getVisibleRect(o),n=y.has(e),r=m.has(e);t.fillStyle=n?d:r?h:c,t.fillRect(0,s,te,i)}t.beginPath(),t.moveTo(te,0),t.lineTo(te,l),t.moveTo(0,ee),t.lineTo(a,ee),t.strokeStyle="#C0C0C0",t.stroke();for(const e of s){const o=vo(e);t.fillStyle=S.has(e)?"#fff":u;const s={left:e,right:e,top:r,bottom:r},{x:i,width:n}=this.getters.getRect(s),{x:a,width:l}=this.getters.getVisibleRect(s);t.save(),t.beginPath(),t.rect(a,0,l,ee),t.clip(),t.fillText(o,i+n/2,13),t.restore(),t.beginPath(),t.moveTo(i+n,0),t.lineTo(i+n,ee),t.stroke()}for(const e of n){t.fillStyle=y.has(e)?"#fff":u;const o={top:e,bottom:e,left:i,right:i},{y:s,height:n}=this.getters.getRect(o),{y:r,height:a}=this.getters.getVisibleRect(o);t.save(),t.beginPath(),t.rect(0,r,te,a),t.clip(),t.fillText(String(e+1),24,s+n/2),t.restore(),t.beginPath(),t.moveTo(0,s+n),t.lineTo(te,s+n),t.stroke()}}drawFrozenPanesHeaders(e){const{ctx:t,thinLineWidth:o}=e,{x:s,y:i}=this.getters.getMainViewportCoordinates(),n=this.getters.isDashboard()?0:te,r=this.getters.isDashboard()?0:ee;t.lineWidth=6*o,t.strokeStyle=x,t.beginPath(),s&&(t.moveTo(n+s,0),t.lineTo(n+s,r)),i&&(t.moveTo(0,r+i),t.lineTo(n,r+i)),t.stroke()}drawFrozenPanes(e){const{ctx:t,thinLineWidth:o}=e,{x:s,y:i}=this.getters.getMainViewportCoordinates(),n=this.getters.getSheetViewVisibleCols(),r=n[0],a=n[n.length-1],l=this.getters.getSheetViewVisibleRows(),c={left:r,right:a,top:l[0],bottom:l[l.length-1]},h=this.getters.getVisibleRect(c),d=this.getters.isDashboard()?0:te,u=this.getters.isDashboard()?0:ee;t.lineWidth=6*o,t.strokeStyle="#DADFE8",t.beginPath(),s&&(t.moveTo(d+s,u),t.lineTo(d+s,h.height+u)),i&&(t.moveTo(d,u+i),t.lineTo(h.width+d,u+i)),t.stroke()}findNextEmptyCol(e,t,o){const s=this.getters.getActiveSheetId();let i=e;for(;i<t;){const e={sheetId:s,col:i+1,row:o},t=this.getters.getEvaluatedCell(e),n=this.getters.getCellComputedBorder(e),r=this.getters.doesCellHaveGridIcon(e),a=this.getters.isCellValidCheckbox(e);if(t.type!==ri.empty||this.getters.isInMerge(e)||n?.left||r||a)return i;i++}return i}findPreviousEmptyCol(e,t,o){const s=this.getters.getActiveSheetId();let i=e;for(;i>t;){const e={sheetId:s,col:i-1,row:o},t=this.getters.getEvaluatedCell(e),n=this.getters.getCellComputedBorder(e),r=this.getters.doesCellHaveGridIcon(e),a=this.getters.isCellValidCheckbox(e);if(t.type!==ri.empty||this.getters.isInMerge(e)||n?.right||r||a)return i;i--}return i}computeCellAlignment(e,t){const o=this.getters.getCell(e);if(o?.isFormula&&this.getters.shouldShowFormulas())return"left";const{align:s}=this.getters.getCellStyle(e),i=this.getters.getEvaluatedCell(e);return t&&i.type===ri.number?"center"!==s?"left":s:s||i.defaultAlign}createZoneBox(e,t,o){const{left:s,right:i}=o,n=t.left,r=t.top,a={sheetId:e,col:n,row:r},l=this.getters.getEvaluatedCell(a),c=this.getters.shouldShowFormulas(),{x:h,y:d,width:u,height:g}=this.getters.getRect(t),{verticalAlign:p}=this.getters.getCellStyle(a);let m=this.getters.getCellComputedStyle(a);if(this.fingerprints.isEnabled){const e=this.fingerprints.colors.get(a);m={...m,fillColor:e}}const f=this.fingerprints.isEnabled?void 0:this.getters.getConditionalDataBar(a),v={x:h,y:d,width:u,height:g,border:this.getters.getCellComputedBorder(a)||void 0,style:m,dataBarFill:f,verticalAlign:p,isError:l.type===ri.error&&!!l.message||this.getters.isDataValidationInvalid(a)},b=this.getters.getCellIconSrc(a),S=ta(v.style),y=b?4+S:0;if(b){const e=DM(b);v.image={type:"icon",size:S,clipIcon:{x:v.x,y:v.y,width:Math.min(y,u),height:g},image:e}}if(l.type===ri.empty||this.getters.isCellValidCheckbox(a))return v;v.hasIcon=this.getters.doesCellHaveGridIcon(a);const C=v.hasIcon?19:0,w=m.wrapping||"overflow",E="wrap"===w&&!c,x=u-2*ne,I=this.getters.getCellMultiLineText(a,{maxWidth:x,wrapText:E}),R=Math.max(...I.map((e=>this.getters.getTextWidth(e,m)+ne))),T=y+R+C,A=this.computeCellAlignment(a,T>u);v.content={textLines:I,width:"overflow"===w?R:u,align:A};const _=T>u||S>g;if(b||v.hasIcon)v.clipRect={x:v.x+y,y:v.y,width:Math.max(0,u-y-C),height:g};else if(_&&"overflow"===w){let e,o;switch(this.getters.isInMerge(a)?(e=this.getters.getMerge(a).right,o=n):(e=v.border?.right?t.right:this.findNextEmptyCol(n,i,r),o=v.border?.left?t.left:this.findPreviousEmptyCol(n,s,r),v.isOverflow=!0),A){case"left":{const o=vs({col:e,row:r}),{x:s,y:i,width:n,height:a}=this.getters.getVisibleRect(is(t,o));(n<T||S>a||I.length>1)&&(v.clipRect={x:s,y:i,width:n,height:a});break}case"right":{const e=vs({col:o,row:r}),{x:s,y:i,width:n,height:a}=this.getters.getVisibleRect(is(t,e));(n<T||S>a||I.length>1)&&(v.clipRect={x:s,y:i,width:n,height:a});break}case"center":{const s={...t,left:o,right:e},{x:i,y:n,height:r,width:a}=this.getters.getVisibleRect(s),l=T/2,c=v.x+v.width/2;if(i+a<c+l||i>c-l||S>r||I.length>1){const e=i>c-l?i:c-l,t=i+a-e;v.clipRect={x:e,y:n,width:t,height:r}}break}}}else("clip"===w||"wrap"===w||I.length>1)&&(v.clipRect={x:v.x,y:v.y,width:u,height:g});return v}getGridBoxes(e){const t=[],o=this.getters.getSheetViewVisibleCols().filter((t=>t>=e.left&&t<=e.right)),s=o[0],i=o[o.length-1],n=this.getters.getSheetViewVisibleRows().filter((t=>t>=e.top&&t<=e.bottom)),r={left:s,right:i,top:n[0],bottom:n[n.length-1]},a=this.getters.getActiveSheetId();for(const e of n)for(const s of o){const o={sheetId:a,col:s,row:e};this.getters.isInMerge(o)||t.push(this.createZoneBox(a,vs(o),r))}for(const e of this.getters.getMerges(a))if(!this.getters.isMergeHidden(a,e)&&as(e,r)){const o=this.createZoneBox(a,e,r),s=this.getters.getCellComputedBorder({sheetId:a,col:e.right,row:e.bottom});o.border={...o.border,bottom:s?s.bottom:void 0,right:s?s.right:void 0},o.isMerge=!0,t.push(o)}return t}}const DM=xt((function(e){const t=new Image;return t.src=e,t}));function OM(e,o,s){const i=t.useRef(e);t.useEffect((function(){const e=i.el,t=window.devicePixelRatio||1,r=e.getContext("2d",{alpha:!1}),a={ctx:r,dpr:t,thinLineWidth:.4*t},{width:l,height:c}=s();if(e.style.width=`${l}px`,e.style.height=`${c}px`,e.width=l*t,e.height=c*t,e.setAttribute("style",`width:${l}px;height:${c}px;`),0===l||0===c)return;r.translate(-.5,-.5),r.scale(t,t);for(const e of Ii())o.drawLayer(a,e),n.drawLayer(a,e)}));const n=Cc(Ac);Cc(_M)}function FM(e){function t(e,t){return e*(0===t?1:se)}return o=>{const s=t(o.shiftKey&&!tR()?o.deltaY:o.deltaX,o.deltaMode),i=t(o.shiftKey&&!tR()?o.deltaX:o.deltaY,o.deltaMode);e(s,i)}}Pc`
|
|
1737
|
+
`;class _M extends t.Component{static props={onOpenContextMenu:Function};static template="o-spreadsheet-HeadersOverlay";static components={ColResizer:TM,RowResizer:AM};selectAll(){this.env.model.selection.selectAll()}}class DM{getters;renderer;fingerprints;constructor(e){this.getters=e(Rc).getters,this.renderer=e(Ac),this.fingerprints=e(p_),this.renderer.register(this)}get renderingLayers(){return["Background","Headers"]}drawLayer(e,t){switch(t){case"Background":this.drawGlobalBackground(e);for(const{zone:t,rect:o}of this.getters.getAllActiveViewportsZonesAndRect()){const{ctx:s}=e;s.save(),s.beginPath(),s.rect(o.x,o.y,o.width,o.height),s.clip();const i=this.getGridBoxes(t);this.drawBackground(e,i),this.drawOverflowingCellBackground(e,i),this.drawCellBackground(e,i),this.drawBorders(e,i),this.drawTexts(e,i),this.drawIcon(e,i),s.restore()}this.drawFrozenPanes(e);break;case"Headers":this.getters.isDashboard()||(this.drawHeaders(e),this.drawFrozenPanesHeaders(e))}}drawGlobalBackground(e){const{ctx:t}=e,{width:o,height:s}=this.getters.getSheetViewDimensionWithHeaders();t.fillStyle="#ffffff",t.fillRect(0,0,o+r,s+r)}drawBackground(e,t){const{ctx:o,thinLineWidth:s}=e,i=!this.getters.isDashboard()&&this.getters.getGridLinesVisibility(this.getters.getActiveSheetId()),n=i?.1*s:0;if(i)for(const e of t)o.strokeStyle="#E2E3E3",o.lineWidth=s,o.strokeRect(e.x+n,e.y+n,e.width-2*n,e.height-2*n)}drawCellBackground(e,t){const{ctx:o}=e;for(const e of t){let t=e.style;if(t.fillColor&&"#ffffff"!==t.fillColor&&(o.fillStyle=t.fillColor||"#ffffff",o.fillRect(e.x,e.y,e.width,e.height)),e.dataBarFill){o.fillStyle=e.dataBarFill.color;const t=e.dataBarFill.percentage,s=e.width*(t/100);o.fillRect(e.x,e.y,s,e.height)}e.isError&&(o.fillStyle="red",o.beginPath(),o.moveTo(e.x+e.width-5,e.y),o.lineTo(e.x+e.width,e.y),o.lineTo(e.x+e.width,e.y+5),o.fill())}}drawOverflowingCellBackground(e,t){const{ctx:o,thinLineWidth:s}=e;for(const e of t)if(e.content&&e.isOverflow){const t=e.content.align||"left";let i,n;const r=e.y+s/2,a=e.height-s,l=Math.min(e.clipRect?.width||1/0,e.content.width);"left"===t?(i=e.x+s/2,n=l-2*s):"right"===t?(i=e.x+e.width-s/2,n=2*s-l):(i=(e.clipRect?.x||e.x+e.width/2-e.content.width/2)+s/2,n=l-2*s),o.fillStyle="#ffffff",o.fillRect(i,r,n,a)}}drawBorders(e,t){const{ctx:o}=e;for(let e of t){const t=e.border;if(t){const{x:o,y:i,width:n,height:r}=e;t.left&&s(t.left,o,i,o,i+r),t.top&&s(t.top,o,i,o+n,i),t.right&&s(t.right,o+n,i,o+n,i+r),t.bottom&&s(t.bottom,o,i+r,o+n,i+r)}}function s({style:e,color:t},s,i,n,r){switch(o.strokeStyle=t,e){case"medium":o.lineWidth=2,i+=(s+=i===r?-.5:.5)===(n+=i===r?1.5:.5)?-.5:.5,r+=s===n?1.5:.5;break;case"thick":o.lineWidth=3,i===r&&(s--,n++),s===n&&(i--,r++);break;case"dashed":o.lineWidth=1,o.setLineDash([1,3]);break;case"dotted":o.lineWidth=1,i===r&&(s+=.5,n+=.5),s===n&&(i+=.5,r+=.5),o.setLineDash([1,1]);break;default:o.lineWidth=1}o.beginPath(),o.moveTo(s,i),o.lineTo(n,r),o.stroke(),o.lineWidth=1,o.setLineDash([])}}drawTexts(e,t){const{ctx:o}=e;let s;o.textBaseline="top";for(let e of t)if(e.content){const t=e.style||{},i=e.content.align||"left",n=ea(t);n!==s&&(s=n,o.font=n),o.fillStyle=t.textColor||"#000";let r=e.x;if(r+="left"===i?ne+(e.image?e.image.size+4:0):"right"===i?e.width-ne-(e.hasIcon?19:0):e.width/2,o.textAlign=i,e.clipRect){o.save(),o.beginPath();const{x:t,y:s,width:i,height:n}=e.clipRect;o.rect(t,s,i,n),o.clip()}const a=ta(t),l=e.content.textLines.length;let c=this.computeTextYCoordinate(e,a,l);for(let s of e.content.textLines)aa(o,s,{x:Math.round(r),y:Math.round(c)},t.underline,t.strikethrough),c+=ne+a;e.clipRect&&o.restore()}}drawIcon(e,t){const{ctx:o}=e;for(const e of t)if(e.image){const t=e.image.image;if(e.image.clipIcon){o.save(),o.beginPath();const{x:t,y:s,width:i,height:n}=e.image.clipIcon;o.rect(t,s,i,n),o.clip()}const s=e.image.size,i=this.computeTextYCoordinate(e,s);o.drawImage(t,e.x+4,i,s,s),e.image.clipIcon&&o.restore()}}computeTextYCoordinate(e,t,o=1){const s=e.y+1,i=qr(t,o),n=e.height>i+2*ne,r=e.verticalAlign||ue;if(n){if("middle"===r)return s+(e.height-i)/2;if("bottom"===r)return s+e.height-i-ne}return s+ne}drawHeaders(e){const{ctx:t,thinLineWidth:o}=e,s=this.getters.getSheetViewVisibleCols(),i=s[0],n=this.getters.getSheetViewVisibleRows(),r=n[0],{width:a,height:l}=this.getters.getSheetViewDimensionWithHeaders(),g=this.getters.getSelectedZones(),p=function(e){const t=new Set;for(let o of wo(e))for(let e of Ze(o.left,o.right+1))t.add(e);return t}(g),m=function(e){const t=new Set;for(let o of wo(e))for(let e of Ze(o.top,o.bottom+1))t.add(e);return t}(g),f=this.getters.getActiveSheetId(),v=this.getters.getNumberCols(f),b=this.getters.getNumberRows(f),S=this.getters.getActiveCols(),y=this.getters.getActiveRows();t.font=`400 11px ${fe}`,t.textAlign="center",t.textBaseline="middle",t.lineWidth=o,t.strokeStyle="#333";for(const e of s){const o={left:e,right:e,top:0,bottom:b-1},{x:s,width:i}=this.getters.getVisibleRect(o),n=S.has(e),r=p.has(e);t.fillStyle=n?d:r?h:c,t.fillRect(s,0,i,ee)}for(const e of n){const o={top:e,bottom:e,left:0,right:v-1},{y:s,height:i}=this.getters.getVisibleRect(o),n=y.has(e),r=m.has(e);t.fillStyle=n?d:r?h:c,t.fillRect(0,s,te,i)}t.beginPath(),t.moveTo(te,0),t.lineTo(te,l),t.moveTo(0,ee),t.lineTo(a,ee),t.strokeStyle="#C0C0C0",t.stroke();for(const e of s){const o=vo(e);t.fillStyle=S.has(e)?"#fff":u;const s={left:e,right:e,top:r,bottom:r},{x:i,width:n}=this.getters.getRect(s),{x:a,width:l}=this.getters.getVisibleRect(s);t.save(),t.beginPath(),t.rect(a,0,l,ee),t.clip(),t.fillText(o,i+n/2,13),t.restore(),t.beginPath(),t.moveTo(i+n,0),t.lineTo(i+n,ee),t.stroke()}for(const e of n){t.fillStyle=y.has(e)?"#fff":u;const o={top:e,bottom:e,left:i,right:i},{y:s,height:n}=this.getters.getRect(o),{y:r,height:a}=this.getters.getVisibleRect(o);t.save(),t.beginPath(),t.rect(0,r,te,a),t.clip(),t.fillText(String(e+1),24,s+n/2),t.restore(),t.beginPath(),t.moveTo(0,s+n),t.lineTo(te,s+n),t.stroke()}}drawFrozenPanesHeaders(e){const{ctx:t,thinLineWidth:o}=e,{x:s,y:i}=this.getters.getMainViewportCoordinates(),n=this.getters.isDashboard()?0:te,r=this.getters.isDashboard()?0:ee;t.lineWidth=6*o,t.strokeStyle=x,t.beginPath(),s&&(t.moveTo(n+s,0),t.lineTo(n+s,r)),i&&(t.moveTo(0,r+i),t.lineTo(n,r+i)),t.stroke()}drawFrozenPanes(e){const{ctx:t,thinLineWidth:o}=e,{x:s,y:i}=this.getters.getMainViewportCoordinates(),n=this.getters.getSheetViewVisibleCols(),r=n[0],a=n[n.length-1],l=this.getters.getSheetViewVisibleRows(),c={left:r,right:a,top:l[0],bottom:l[l.length-1]},h=this.getters.getVisibleRect(c),d=this.getters.isDashboard()?0:te,u=this.getters.isDashboard()?0:ee;t.lineWidth=6*o,t.strokeStyle="#DADFE8",t.beginPath(),s&&(t.moveTo(d+s,u),t.lineTo(d+s,h.height+u)),i&&(t.moveTo(d,u+i),t.lineTo(h.width+d,u+i)),t.stroke()}findNextEmptyCol(e,t,o){const s=this.getters.getActiveSheetId();let i=e;for(;i<t;){const e={sheetId:s,col:i+1,row:o},t=this.getters.getEvaluatedCell(e),n=this.getters.getCellComputedBorder(e),r=this.getters.doesCellHaveGridIcon(e),a=this.getters.isCellValidCheckbox(e);if(t.type!==ri.empty||this.getters.isInMerge(e)||n?.left||r||a)return i;i++}return i}findPreviousEmptyCol(e,t,o){const s=this.getters.getActiveSheetId();let i=e;for(;i>t;){const e={sheetId:s,col:i-1,row:o},t=this.getters.getEvaluatedCell(e),n=this.getters.getCellComputedBorder(e),r=this.getters.doesCellHaveGridIcon(e),a=this.getters.isCellValidCheckbox(e);if(t.type!==ri.empty||this.getters.isInMerge(e)||n?.right||r||a)return i;i--}return i}computeCellAlignment(e,t){const o=this.getters.getCell(e);if(o?.isFormula&&this.getters.shouldShowFormulas())return"left";const{align:s}=this.getters.getCellStyle(e),i=this.getters.getEvaluatedCell(e);return t&&i.type===ri.number?"center"!==s?"left":s:s||i.defaultAlign}createZoneBox(e,t,o){const{left:s,right:i}=o,n=t.left,r=t.top,a={sheetId:e,col:n,row:r},l=this.getters.getEvaluatedCell(a),c=this.getters.shouldShowFormulas(),{x:h,y:d,width:u,height:g}=this.getters.getRect(t),{verticalAlign:p}=this.getters.getCellStyle(a);let m=this.getters.getCellComputedStyle(a);if(this.fingerprints.isEnabled){const e=this.fingerprints.colors.get(a);m={...m,fillColor:e}}const f=this.fingerprints.isEnabled?void 0:this.getters.getConditionalDataBar(a),v={x:h,y:d,width:u,height:g,border:this.getters.getCellComputedBorder(a)||void 0,style:m,dataBarFill:f,verticalAlign:p,isError:l.type===ri.error&&!!l.message||this.getters.isDataValidationInvalid(a)},b=this.getters.getCellIconSrc(a),S=ta(v.style),y=b?4+S:0;if(b){const e=OM(b);v.image={type:"icon",size:S,clipIcon:{x:v.x,y:v.y,width:Math.min(y,u),height:g},image:e}}if(l.type===ri.empty||this.getters.isCellValidCheckbox(a))return v;v.hasIcon=this.getters.doesCellHaveGridIcon(a);const C=v.hasIcon?19:0,w=m.wrapping||"overflow",E="wrap"===w&&!c,x=u-2*ne,I=this.getters.getCellMultiLineText(a,{maxWidth:x,wrapText:E}),R=Math.max(...I.map((e=>this.getters.getTextWidth(e,m)+ne))),T=y+R+C,A=this.computeCellAlignment(a,T>u);v.content={textLines:I,width:"overflow"===w?R:u,align:A};const _=T>u||S>g;if(b||v.hasIcon)v.clipRect={x:v.x+y,y:v.y,width:Math.max(0,u-y-C),height:g};else if(_&&"overflow"===w){let e,o;switch(this.getters.isInMerge(a)?(e=this.getters.getMerge(a).right,o=n):(e=v.border?.right?t.right:this.findNextEmptyCol(n,i,r),o=v.border?.left?t.left:this.findPreviousEmptyCol(n,s,r),v.isOverflow=!0),A){case"left":{const o=vs({col:e,row:r}),{x:s,y:i,width:n,height:a}=this.getters.getVisibleRect(is(t,o));(n<T||S>a||I.length>1)&&(v.clipRect={x:s,y:i,width:n,height:a});break}case"right":{const e=vs({col:o,row:r}),{x:s,y:i,width:n,height:a}=this.getters.getVisibleRect(is(t,e));(n<T||S>a||I.length>1)&&(v.clipRect={x:s,y:i,width:n,height:a});break}case"center":{const s={...t,left:o,right:e},{x:i,y:n,height:r,width:a}=this.getters.getVisibleRect(s),l=T/2,c=v.x+v.width/2;if(i+a<c+l||i>c-l||S>r||I.length>1){const e=i>c-l?i:c-l,t=i+a-e;v.clipRect={x:e,y:n,width:t,height:r}}break}}}else("clip"===w||"wrap"===w||I.length>1)&&(v.clipRect={x:v.x,y:v.y,width:u,height:g});return v}getGridBoxes(e){const t=[],o=this.getters.getSheetViewVisibleCols().filter((t=>t>=e.left&&t<=e.right)),s=o[0],i=o[o.length-1],n=this.getters.getSheetViewVisibleRows().filter((t=>t>=e.top&&t<=e.bottom)),r={left:s,right:i,top:n[0],bottom:n[n.length-1]},a=this.getters.getActiveSheetId();for(const e of n)for(const s of o){const o={sheetId:a,col:s,row:e};this.getters.isInMerge(o)||t.push(this.createZoneBox(a,vs(o),r))}for(const e of this.getters.getMerges(a))if(!this.getters.isMergeHidden(a,e)&&as(e,r)){const o=this.createZoneBox(a,e,r),s=this.getters.getCellComputedBorder({sheetId:a,col:e.right,row:e.bottom});o.border={...o.border,bottom:s?s.bottom:void 0,right:s?s.right:void 0},o.isMerge=!0,t.push(o)}return t}}const OM=xt((function(e){const t=new Image;return t.src=e,t}));function FM(e,o,s){const i=t.useRef(e);t.useEffect((function(){const e=i.el,t=window.devicePixelRatio||1,r=e.getContext("2d",{alpha:!1}),a={ctx:r,dpr:t,thinLineWidth:.4*t},{width:l,height:c}=s();if(e.style.width=`${l}px`,e.style.height=`${c}px`,e.width=l*t,e.height=c*t,e.setAttribute("style",`width:${l}px;height:${c}px;`),0===l||0===c)return;r.translate(-.5,-.5),r.scale(t,t);for(const e of Ii())o.drawLayer(a,e),n.drawLayer(a,e)}));const n=Cc(Ac);Cc(DM)}function MM(e){function t(e,t){return e*(0===t?1:se)}return o=>{const s=t(o.shiftKey&&!tR()?o.deltaY:o.deltaX,o.deltaMode),i=t(o.shiftKey&&!tR()?o.deltaX:o.deltaY,o.deltaMode);e(s,i)}}Pc`
|
|
1738
1738
|
.o-border {
|
|
1739
1739
|
position: absolute;
|
|
1740
1740
|
&:hover {
|
|
@@ -1744,7 +1744,7 @@
|
|
|
1744
1744
|
.o-moving {
|
|
1745
1745
|
cursor: grabbing;
|
|
1746
1746
|
}
|
|
1747
|
-
`;class
|
|
1747
|
+
`;class PM extends t.Component{static template="o-spreadsheet-Border";static props={zone:Object,orientation:String,isMoving:Boolean,onMoveHighlight:Function};get style(){const e=["n","w","e"].includes(this.props.orientation),t=["n","w","s"].includes(this.props.orientation),o=["n","s"].includes(this.props.orientation),s=["w","e"].includes(this.props.orientation),i=this.props.zone,n=this.env.model.getters.getVisibleRect(i),r=n.x,a=n.x+n.width-4,l=n.y,c=n.y+n.height-4;return Lc({left:`${t?r:a}px`,top:`${e?l:c}px`,width:`${o?a-r:4}px`,height:`${s?c-l:4}px`})}onMouseDown(e){this.props.onMoveHighlight(e.clientX,e.clientY)}}Pc`
|
|
1748
1748
|
.o-corner {
|
|
1749
1749
|
position: absolute;
|
|
1750
1750
|
height: 8px;
|
|
@@ -1766,11 +1766,11 @@
|
|
|
1766
1766
|
.o-resizing {
|
|
1767
1767
|
cursor: grabbing;
|
|
1768
1768
|
}
|
|
1769
|
-
`;class
|
|
1769
|
+
`;class NM extends t.Component{static template="o-spreadsheet-Corner";static props={zone:Object,color:String,orientation:String,isResizing:Boolean,onResizeHighlight:Function};isTop="n"===this.props.orientation[0];isLeft="w"===this.props.orientation[1];get style(){const e=this.props.zone,t=this.isLeft?e.left:e.right,o=this.isTop?e.top:e.bottom,s=this.env.model.getters.getVisibleRect({left:t,right:t,top:o,bottom:o});if(s.width*s.height==0)return"display:none";return Lc({left:(this.isLeft?s.x:s.x+s.width)-4+"px",top:(this.isTop?s.y:s.y+s.height)-4+"px","background-color":this.props.color})}onMouseDown(e){this.props.onResizeHighlight(this.isLeft,this.isTop)}}Pc`
|
|
1770
1770
|
.o-highlight {
|
|
1771
1771
|
z-index: ${Oe.Highlight};
|
|
1772
1772
|
}
|
|
1773
|
-
`;class
|
|
1773
|
+
`;class kM extends t.Component{static template="o-spreadsheet-Highlight";static props={zone:Object,color:String};static components={Corner:NM,Border:PM};highlightState=t.useState({shiftingMode:"none"});onResizeHighlight(e,t){const o=this.env.model.getters.getActiveSheetId();this.highlightState.shiftingMode="isResizing";const s=this.props.zone,i=e?s.right:s.left,n=t?s.bottom:s.top;let r=e?s.left:s.right,a=t?s.top:s.bottom,l=s;this.env.model.dispatch("START_CHANGE_HIGHLIGHT",{zone:l});J_(this.env,((e,t)=>{if(r!==e||a!==t){r=qe(-1===e?r:e,0,this.env.model.getters.getNumberCols(o)-1),a=qe(-1===t?a:t,0,this.env.model.getters.getNumberRows(o)-1);let s={left:Math.min(i,r),top:Math.min(n,a),right:Math.max(i,r),bottom:Math.max(n,a)};rs(s,l)||(this.env.model.selection.selectZone({cell:{col:s.left,row:s.top},zone:s},{unbounded:!0}),l=s)}}),(()=>{this.highlightState.shiftingMode="none"}))}onMoveHighlight(e,t){this.highlightState.shiftingMode="isMoving";const o=this.props.zone,s=jI(),i=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getColIndex(e-s.left),r=this.env.model.getters.getRowIndex(t-s.top),a=-o.left,l=this.env.model.getters.getNumberCols(i)-o.right-1,c=-o.top,h=this.env.model.getters.getNumberRows(i)-o.bottom-1;let d=o;this.env.model.dispatch("START_CHANGE_HIGHLIGHT",{zone:d});let u=n,g=r;J_(this.env,((e,t)=>{if(u!==e||g!==t){u=-1===e?u:e,g=-1===t?g:t;const s=qe(u-n,a,l),i=qe(g-r,c,h);let p={left:o.left+s,top:o.top+i,right:o.right+s,bottom:o.bottom+i};rs(p,d)||(this.env.model.selection.selectZone({cell:{col:p.left,row:p.top},zone:p},{unbounded:!0}),d=p)}}),(()=>{this.highlightState.shiftingMode="none"}))}}Pc`
|
|
1774
1774
|
.o-scrollbar {
|
|
1775
1775
|
position: absolute;
|
|
1776
1776
|
overflow: auto;
|
|
@@ -1787,7 +1787,7 @@
|
|
|
1787
1787
|
border-left: 1px solid #e2e3e3;
|
|
1788
1788
|
}
|
|
1789
1789
|
}
|
|
1790
|
-
`;class
|
|
1790
|
+
`;class LM extends t.Component{static props={width:{type:Number,optional:!0},height:{type:Number,optional:!0},direction:String,position:Object,offset:Number,onScroll:Function};static template=t.xml`
|
|
1791
1791
|
<div
|
|
1792
1792
|
t-attf-class="o-scrollbar {{props.direction}}"
|
|
1793
1793
|
t-on-scroll="onScroll"
|
|
@@ -1795,7 +1795,7 @@
|
|
|
1795
1795
|
t-att-style="positionCss">
|
|
1796
1796
|
<div t-att-style="sizeCss"/>
|
|
1797
1797
|
</div>
|
|
1798
|
-
`;static defaultProps={width:1,height:1};scrollbarRef;scrollbar;setup(){this.scrollbarRef=t.useRef("scrollbar"),this.scrollbar=new class{direction;el;constructor(e,t){this.el=e,this.direction=t}get scroll(){return"horizontal"===this.direction?this.el.scrollLeft:this.el.scrollTop}set scroll(e){"horizontal"===this.direction?this.el.scrollLeft=e:this.el.scrollTop=e}}(this.scrollbarRef.el,this.props.direction),t.onMounted((()=>{this.scrollbar.el=this.scrollbarRef.el})),t.useEffect((()=>{this.scrollbar.scroll!==this.props.offset&&(this.scrollbar.scroll=this.props.offset)}),(()=>[this.scrollbar.scroll,this.props.offset]))}get sizeCss(){return Lc({width:`${this.props.width}px`,height:`${this.props.height}px`})}get positionCss(){return Lc(this.props.position)}onScroll(e){this.props.offset!==this.scrollbar.scroll&&this.props.onScroll(this.scrollbar.scroll)}}class
|
|
1798
|
+
`;static defaultProps={width:1,height:1};scrollbarRef;scrollbar;setup(){this.scrollbarRef=t.useRef("scrollbar"),this.scrollbar=new class{direction;el;constructor(e,t){this.el=e,this.direction=t}get scroll(){return"horizontal"===this.direction?this.el.scrollLeft:this.el.scrollTop}set scroll(e){"horizontal"===this.direction?this.el.scrollLeft=e:this.el.scrollTop=e}}(this.scrollbarRef.el,this.props.direction),t.onMounted((()=>{this.scrollbar.el=this.scrollbarRef.el})),t.useEffect((()=>{this.scrollbar.scroll!==this.props.offset&&(this.scrollbar.scroll=this.props.offset)}),(()=>[this.scrollbar.scroll,this.props.offset]))}get sizeCss(){return Lc({width:`${this.props.width}px`,height:`${this.props.height}px`})}get positionCss(){return Lc(this.props.position)}onScroll(e){this.props.offset!==this.scrollbar.scroll&&this.props.onScroll(this.scrollbar.scroll)}}class VM extends t.Component{static props={leftOffset:{type:Number,optional:!0}};static components={ScrollBar:LM};static template=t.xml`
|
|
1799
1799
|
<ScrollBar
|
|
1800
1800
|
t-if="isDisplayed"
|
|
1801
1801
|
width="width"
|
|
@@ -1803,7 +1803,7 @@
|
|
|
1803
1803
|
offset="offset"
|
|
1804
1804
|
direction="'horizontal'"
|
|
1805
1805
|
onScroll.bind="onScroll"
|
|
1806
|
-
/>`;static defaultProps={leftOffset:0};get offset(){return this.env.model.getters.getActiveSheetScrollInfo().scrollX}get width(){return this.env.model.getters.getMainViewportRect().width}get isDisplayed(){const{xRatio:e}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());return e<1}get position(){const{x:e}=this.env.model.getters.getMainViewportRect();return{left:`${this.props.leftOffset+e}px`,bottom:"0px",height:"15px",right:"0px"}}onScroll(e){const{scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:e,offsetY:t})}}class
|
|
1806
|
+
/>`;static defaultProps={leftOffset:0};get offset(){return this.env.model.getters.getActiveSheetScrollInfo().scrollX}get width(){return this.env.model.getters.getMainViewportRect().width}get isDisplayed(){const{xRatio:e}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());return e<1}get position(){const{x:e}=this.env.model.getters.getMainViewportRect();return{left:`${this.props.leftOffset+e}px`,bottom:"0px",height:"15px",right:"0px"}}onScroll(e){const{scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:e,offsetY:t})}}class UM extends t.Component{static props={topOffset:{type:Number,optional:!0}};static components={ScrollBar:LM};static template=t.xml`
|
|
1807
1807
|
<ScrollBar
|
|
1808
1808
|
t-if="isDisplayed"
|
|
1809
1809
|
height="height"
|
|
@@ -1811,19 +1811,19 @@
|
|
|
1811
1811
|
offset="offset"
|
|
1812
1812
|
direction="'vertical'"
|
|
1813
1813
|
onScroll.bind="onScroll"
|
|
1814
|
-
/>`;static defaultProps={topOffset:0};get offset(){return this.env.model.getters.getActiveSheetScrollInfo().scrollY}get height(){return this.env.model.getters.getMainViewportRect().height}get isDisplayed(){const{yRatio:e}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());return e<1}get position(){const{y:e}=this.env.model.getters.getMainViewportRect();return{top:`${this.props.topOffset+e}px`,right:"0px",width:"15px",bottom:"0px"}}onScroll(e){const{scrollX:t}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:t,offsetY:e})}}const
|
|
1814
|
+
/>`;static defaultProps={topOffset:0};get offset(){return this.env.model.getters.getActiveSheetScrollInfo().scrollY}get height(){return this.env.model.getters.getMainViewportRect().height}get isDisplayed(){const{yRatio:e}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());return e<1}get position(){const{y:e}=this.env.model.getters.getMainViewportRect();return{top:`${this.props.topOffset+e}px`,right:"0px",width:"15px",bottom:"0px"}}onScroll(e){const{scrollX:t}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:t,offsetY:e})}}const HM=350;class BM extends _c{mutators=["open","toggle","close","changePanelSize","resetPanelSize"];initialPanelProps={};componentTag="";panelSize=HM;get isOpen(){return!!this.componentTag&&this.computeState(this.componentTag,this.initialPanelProps).isOpen}get panelProps(){const e=this.computeState(this.componentTag,this.initialPanelProps);return e.isOpen?e.props??{}:{}}get panelKey(){const e=this.computeState(this.componentTag,this.initialPanelProps);if(e.isOpen)return e.key}open(e,t={}){const o=this.computeState(e,t);o.isOpen&&(this.isOpen&&e!==this.componentTag&&this.initialPanelProps?.onCloseSidePanel?.(),this.componentTag=e,this.initialPanelProps=o.props??{})}toggle(e,t){this.isOpen&&e===this.componentTag?this.close():this.open(e,t)}close(){this.initialPanelProps.onCloseSidePanel?.(),this.initialPanelProps={},this.componentTag=""}changePanelSize(e,t){this.panelSize=e<HM?HM:e>t-150?Math.max(t-150,HM):e}resetPanelSize(){this.panelSize=HM}computeState(e,t){const o=WF.get(e).computeState;return o?o(this.getters,t):{isOpen:!0,props:t}}}const zM="#777";Pc`
|
|
1815
1815
|
.o-table-resizer {
|
|
1816
1816
|
width: ${6}px;
|
|
1817
1817
|
height: ${6}px;
|
|
1818
|
-
border-bottom: ${3}px solid ${
|
|
1819
|
-
border-right: ${3}px solid ${
|
|
1818
|
+
border-bottom: ${3}px solid ${zM};
|
|
1819
|
+
border-right: ${3}px solid ${zM};
|
|
1820
1820
|
cursor: nwse-resize;
|
|
1821
1821
|
}
|
|
1822
|
-
`;class zM extends t.Component{static template="o-spreadsheet-TableResizer";static props={table:Object};state=t.useState({highlightZone:void 0});setup(){dO(this)}get containerStyle(){const e=this.props.table.range.zone,t={...e,left:e.right,top:e.bottom},o=this.env.model.getters.getVisibleRect(t);return 0===o.height||0===o.width?Lc({display:"none"}):Lc({top:o.y+o.height-6+"px",left:o.x+o.width-6+"px"})}onMouseDown(e){const t=this.props.table.range.zone,o={col:t.left,row:t.top};document.body.style.cursor="nwse-resize";J_(this.env,((e,t,s)=>{this.state.highlightZone={left:o.col,top:o.row,right:Math.max(e,o.col),bottom:Math.max(t,o.row)}}),(()=>{document.body.style.cursor="";const e=this.state.highlightZone;if(!e)return;const t=this.props.table.range.sheetId;this.env.model.dispatch("RESIZE_TABLE",{sheetId:t,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeDataFromZone(t,e)}),this.state.highlightZone=void 0}))}get highlights(){return this.state.highlightZone?[{zone:this.state.highlightZone,sheetId:this.props.table.range.sheetId,color:BM,noFill:!0}]:[]}}const $M={ROW:q_,COL:z_,CELL:JT,GROUP_HEADERS:YF,UNGROUP_HEADERS:XF};class WM extends t.Component{static template="o-spreadsheet-Grid";static props={exposeFocus:Function};static components={GridComposer:iM,GridOverlay:EM,GridPopover:xM,HeadersOverlay:AM,Menu:mR,Autofill:JF,ClientTag:eM,Highlight:NM,Popover:PI,VerticalScrollBar:VM,HorizontalScrollBar:LM,TableResizer:zM};HEADER_HEIGHT=ee;HEADER_WIDTH=te;menuState;gridRef;highlightStore;cellPopovers;composerFocusStore;DOMFocusableElementStore;paintFormatStore;onMouseWheel;canvasPosition;hoveredCell;sidePanel;setup(){this.highlightStore=Cc(Jb),this.menuState=t.useState({isOpen:!1,position:null,menuItems:[]}),this.gridRef=t.useRef("grid"),this.canvasPosition=MI(this.gridRef),this.hoveredCell=Cc(TI),this.composerFocusStore=Cc(Oc),this.DOMFocusableElementStore=Cc(PD),this.sidePanel=Cc(HM),this.paintFormatStore=Cc(CM),Cc(KF),t.useChildSubEnv({getPopoverContainerRect:()=>this.getGridRect()}),t.useExternalListener(document.body,"cut",this.copy.bind(this,!0)),t.useExternalListener(document.body,"copy",this.copy.bind(this,!1)),t.useExternalListener(document.body,"paste",this.paste),t.onMounted((()=>this.focusDefaultElement())),this.props.exposeFocus((()=>this.focusDefaultElement())),OM("canvas",this.env.model,(()=>this.env.model.getters.getSheetViewDimensionWithHeaders())),this.onMouseWheel=FM(((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()})),this.cellPopovers=Cc(AI),t.useEffect((()=>{this.sidePanel.isOpen||this.DOMFocusableElementStore.focusableElement?.focus()}),(()=>[this.sidePanel.isOpen]))}onCellHovered({col:e,row:t}){this.hoveredCell.hover({col:e,row:t})}get highlights(){return this.highlightStore.highlights}get gridOverlayDimensions(){return Lc({top:"26px",left:"48px",height:"calc(100% - 41px)",width:"calc(100% - 63px)"})}onClosePopover(){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.focusDefaultElement()}keyDownMapping={Enter:()=>{this.env.model.getters.getActiveCell().type===ri.empty?this.onComposerCellFocused():this.onComposerContentFocused()},Tab:()=>this.env.model.selection.moveAnchorCell("right",1),"Shift+Tab":()=>this.env.model.selection.moveAnchorCell("left",1),F2:()=>{this.env.model.getters.getActiveCell().type===ri.empty?this.onComposerCellFocused():this.onComposerContentFocused()},Delete:()=>{this.env.model.dispatch("DELETE_CONTENT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Backspace:()=>{this.env.model.dispatch("DELETE_CONTENT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Escape:()=>{this.cellPopovers.isOpen?this.cellPopovers.close():this.menuState.isOpen?this.closeMenu():this.paintFormatStore.isActive?this.paintFormatStore.cancel():this.env.model.dispatch("CLEAN_CLIPBOARD_HIGHLIGHT")},"Ctrl+A":()=>this.env.model.selection.loopSelection(),"Ctrl+Z":()=>this.env.model.dispatch("REQUEST_UNDO"),"Ctrl+Y":()=>this.env.model.dispatch("REQUEST_REDO"),F4:()=>this.env.model.dispatch("REQUEST_REDO"),"Ctrl+B":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{bold:!this.env.model.getters.getCurrentStyle().bold}}),"Ctrl+I":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{italic:!this.env.model.getters.getCurrentStyle().italic}}),"Ctrl+U":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{underline:!this.env.model.getters.getCurrentStyle().underline}}),"Ctrl+O":()=>MR(this.env),"Alt+=":()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone(),{anchor:o}=this.env.model.getters.getSelection(),s=this.env.model.getters.getAutomaticSums(e,t,o.cell);if(this.env.model.getters.isSingleCellOrMerge(e,t)||this.env.model.getters.isEmpty(e,t)&&s.length<=1){const t=s[0]?.zone,o=t?this.env.model.getters.zoneToXC(e,s[0].zone):"",i=`=SUM(${o})`;this.onComposerCellFocused(i,{start:5,end:5+o.length})}else this.env.model.dispatch("SUM_SELECTION")},"Alt+Enter":()=>{const e=this.env.model.getters.getActiveCell();e.link&&An(e.link,this.env)},"Ctrl+Home":()=>{const e=this.env.model.getters.getActiveSheetId(),{col:t,row:o}=this.env.model.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0});this.env.model.selection.selectCell(t,o)},"Ctrl+End":()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.findVisibleHeader(e,"COL",this.env.model.getters.getNumberCols(e)-1,0),o=this.env.model.getters.findVisibleHeader(e,"ROW",this.env.model.getters.getNumberRows(e)-1,0);this.env.model.selection.selectCell(t,o)},"Shift+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),left:0,right:this.env.model.getters.getNumberCols(e)-1},o=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:o,zone:t})},"Ctrl+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),top:0,bottom:this.env.model.getters.getNumberRows(e)-1},o=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:o,zone:t})},"Ctrl+D":async()=>this.env.model.dispatch("COPY_PASTE_CELLS_ABOVE"),"Ctrl+R":async()=>this.env.model.dispatch("COPY_PASTE_CELLS_ON_LEFT"),"Ctrl+H":()=>this.sidePanel.open("FindAndReplace",{}),"Ctrl+F":()=>this.sidePanel.open("FindAndReplace",{}),"Ctrl+Shift+E":()=>this.setHorizontalAlign("center"),"Ctrl+Shift+L":()=>this.setHorizontalAlign("left"),"Ctrl+Shift+R":()=>this.setHorizontalAlign("right"),"Ctrl+Shift+V":()=>TR(this.env),"Ctrl+Shift+<":()=>this.clearFormatting(),"Ctrl+<":()=>this.clearFormatting(),"Ctrl+Shift+ ":()=>{this.env.model.selection.selectAll()},"Ctrl+Alt+=":()=>{const e=this.env.model.getters.getActiveCols(),t=this.env.model.getters.getActiveRows(),o=1===this.env.model.getters.getSelectedZones().length,s=e.size>0&&o,i=t.size>0&&o;s&&!i?OR(this.env):i&&!s&&DR(this.env)},"Ctrl+Alt+-":()=>{const e=[...this.env.model.getters.getActiveCols()],t=[...this.env.model.getters.getActiveRows()];e.length>0&&0===t.length?this.env.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"COL",elements:e}):t.length>0&&0===e.length&&this.env.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},"Shift+PageDown":()=>{this.env.model.dispatch("ACTIVATE_NEXT_SHEET")},"Shift+PageUp":()=>{this.env.model.dispatch("ACTIVATE_PREVIOUS_SHEET")},PageDown:()=>this.env.model.dispatch("SHIFT_VIEWPORT_DOWN"),PageUp:()=>this.env.model.dispatch("SHIFT_VIEWPORT_UP"),"Ctrl+K":()=>PR(this.env),"Alt+Shift+ArrowRight":()=>this.processHeaderGroupingKey("right"),"Alt+Shift+ArrowLeft":()=>this.processHeaderGroupingKey("left"),"Alt+Shift+ArrowUp":()=>this.processHeaderGroupingKey("up"),"Alt+Shift+ArrowDown":()=>this.processHeaderGroupingKey("down")};focusDefaultElement(){this.env.model.getters.getSelectedFigureId()||"inactive"!==this.composerFocusStore.activeComposer.editionMode||this.DOMFocusableElementStore.focusableElement?.focus()}get gridEl(){if(!this.gridRef.el)throw new Error("Grid el is not defined.");return this.gridRef.el}getAutofillPosition(){const e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect(e);return{left:t.x+t.width-4,top:t.y+t.height-4}}get isAutofillVisible(){const e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect({left:e.right,right:e.right,top:e.bottom,bottom:e.bottom});return!(0===t.width||0===t.height)}onGridResized({height:e,width:t}){this.env.model.dispatch("RESIZE_SHEETVIEW",{width:t,height:e,gridOffsetX:te,gridOffsetY:ee})}moveCanvas(e,t){const{scrollX:o,scrollY:s}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:o+e,offsetY:s+t})}getClientPositionKey(e){return`${e.id}-${e.position?.sheetId}-${e.position?.col}-${e.position?.row}`}isCellHovered(e,t){return this.hoveredCell.col===e&&this.hoveredCell.row===t}getGridRect(){return{...this.canvasPosition,...this.env.model.getters.getSheetViewDimensionWithHeaders()}}onCellClicked(e,t,o){"editing"===this.composerFocusStore.activeComposer.editionMode&&this.composerFocusStore.activeComposer.stopEdition(),o.expandZone?this.env.model.selection.setAnchorCorner(e,t):o.addZone?this.env.model.selection.addCellToSelection(e,t):this.env.model.selection.selectCell(e,t);let s=e,i=t;J_(this.env,((e,t,o)=>{o.preventDefault(),(e!==s&&-1!=e||t!==i&&-1!=t)&&(s=-1===e?s:e,i=-1===t?i:t,this.env.model.selection.setAnchorCorner(s,i))}),(()=>{this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())}))}onCellDoubleClicked(e,t){const o=this.env.model.getters.getActiveSheetId();({col:e,row:t}=this.env.model.getters.getMainCellPosition({sheetId:o,col:e,row:t}));this.env.model.getters.getEvaluatedCell({sheetId:o,col:e,row:t}).type===ri.empty?this.onComposerCellFocused():this.onComposerContentFocused()}processArrows(e){e.preventDefault(),e.stopPropagation(),this.cellPopovers.isOpen&&this.cellPopovers.close(),nD(e,this.env.model.selection),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())}onKeydown(e){const t=eR(e),o=this.keyDownMapping[t];if(o)return e.preventDefault(),e.stopPropagation(),void o();e.key.startsWith("Arrow")&&this.processArrows(e)}onInputContextMenu(e){e.preventDefault();const t=this.env.model.getters.getSelectedZone(),{left:o,top:s}=t;let i="CELL";this.composerFocusStore.activeComposer.stopEdition(),this.env.model.getters.getActiveCols().has(o)?i="COL":this.env.model.getters.getActiveRows().has(s)&&(i="ROW");const{x:n,y:r,width:a}=this.env.model.getters.getVisibleRect(t),l=this.getGridRect();this.toggleContextMenu(i,l.x+n+a,l.y+r)}onCellRightClicked(e,t,{x:o,y:s}){const i=this.env.model.getters.getSelectedZones();let n="CELL";ls(e,t,i[i.length-1])?this.env.model.getters.getActiveCols().has(e)?n="COL":this.env.model.getters.getActiveRows().has(t)&&(n="ROW"):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(n,o,s)}toggleContextMenu(e,t,o){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.menuState.isOpen=!0,this.menuState.position={x:t,y:o},this.menuState.menuItems=$M[e].getMenuItems()}async copy(e,t){if(!this.gridEl.contains(document.activeElement))return;if("inactive"!==this.composerFocusStore.activeComposer.editionMode)return;e?II(this.env):this.env.model.dispatch("COPY");const o=this.env.model.getters.getClipboardContent(),s=t.clipboardData;for(const e in o)s?.setData(e,o[e]);t.preventDefault()}async paste(e){if(!this.gridEl.contains(document.activeElement))return;e.preventDefault();const t=e.clipboardData;if(!t)return;const o={content:{[ai.PlainText]:t?.getData(ai.PlainText),[ai.Html]:t?.getData(ai.Html)}},s=this.env.model.getters.getSelectedZones(),i=this.env.model.getters.isCutOperation(),n=da(o.content),r=n.data?.clipboardId;this.env.model.getters.getClipboardId()===r?dE(this.env,s):uE(this.env,s,n),i&&await this.env.clipboard.write({[ai.PlainText]:""})}clearFormatting(){this.env.model.dispatch("CLEAR_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}setHorizontalAlign(e){this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{align:e}})}closeMenu(){this.menuState.isOpen=!1,this.focusDefaultElement()}processHeaderGroupingKey(e){if(1!==this.env.model.getters.getSelectedZones().length)return;const t=this.env.model.getters.getActiveRows().size>0,o=this.env.model.getters.getActiveCols().size>0;o&&t?this.processHeaderGroupingEventOnWholeSheet(e):o?this.processHeaderGroupingEventOnHeaders(e,"COL"):t?this.processHeaderGroupingEventOnHeaders(e,"ROW"):this.processHeaderGroupingEventOnGrid(e)}processHeaderGroupingEventOnHeaders(e,t){const o=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getSelectedZone(),i="COL"===t?s.left:s.top,n="COL"===t?s.right:s.bottom;switch(e){case"right":this.env.model.dispatch("GROUP_HEADERS",{sheetId:o,dimension:t,start:i,end:n});break;case"left":this.env.model.dispatch("UNGROUP_HEADERS",{sheetId:o,dimension:t,start:i,end:n});break;case"down":this.env.model.dispatch("UNFOLD_HEADER_GROUPS_IN_ZONE",{sheetId:o,dimension:t,zone:s});break;case"up":this.env.model.dispatch("FOLD_HEADER_GROUPS_IN_ZONE",{sheetId:o,dimension:t,zone:s})}}processHeaderGroupingEventOnWholeSheet(e){const t=this.env.model.getters.getActiveSheetId();"up"===e?(this.env.model.dispatch("FOLD_ALL_HEADER_GROUPS",{sheetId:t,dimension:"ROW"}),this.env.model.dispatch("FOLD_ALL_HEADER_GROUPS",{sheetId:t,dimension:"COL"})):"down"===e&&(this.env.model.dispatch("UNFOLD_ALL_HEADER_GROUPS",{sheetId:t,dimension:"ROW"}),this.env.model.dispatch("UNFOLD_ALL_HEADER_GROUPS",{sheetId:t,dimension:"COL"}))}processHeaderGroupingEventOnGrid(e){const t=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getSelectedZone();switch(e){case"down":this.env.model.dispatch("UNFOLD_HEADER_GROUPS_IN_ZONE",{sheetId:t,dimension:"ROW",zone:o}),this.env.model.dispatch("UNFOLD_HEADER_GROUPS_IN_ZONE",{sheetId:t,dimension:"COL",zone:o});break;case"up":this.env.model.dispatch("FOLD_HEADER_GROUPS_IN_ZONE",{sheetId:t,dimension:"ROW",zone:o}),this.env.model.dispatch("FOLD_HEADER_GROUPS_IN_ZONE",{sheetId:t,dimension:"COL",zone:o});break;case"right":{const{x:e,y:t,width:s}=this.env.model.getters.getVisibleRect(o),i=this.getGridRect();this.toggleContextMenu("GROUP_HEADERS",e+s+i.x,t+i.y);break}case"left":{if(!B_(this.env,"COL")&&!B_(this.env,"ROW"))return;const{x:e,y:t,width:s}=this.env.model.getters.getVisibleRect(o),i=this.getGridRect();this.toggleContextMenu("UNGROUP_HEADERS",e+s+i.x,t+i.y);break}}}onComposerCellFocused(e,t){this.composerFocusStore.focusActiveComposer({content:e,selection:t,focusMode:"cellFocus"})}onComposerContentFocused(){this.composerFocusStore.focusActiveComposer({focusMode:"contentFocus"})}get staticTables(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getCoreTables(e).filter(_F)}}class GM{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 qM extends GM{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){}garbageCollectExternalResources(){}}class ZM{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 jM(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 jM{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 YM(e){return""===e?NaN:Number(e)}function XM(e){return Object.entries(e).map((([e,t])=>t?KM(parseInt(e,10),t):void 0)).filter(at).map((e=>Co(e.left,e.top)+":"+Co(e.right,e.bottom)))}function KM(e,t){return{...t.zone,id:e}}class JM{getters;providers=[];constructor(e){this.getters=e}static getters=["adaptFormulaStringDependencies","copyFormulaStringForSheet","extendRange","getRangeString","getRangeFromSheetXC","createAdaptedRanges","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){switch(e.type){case"REMOVE_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",o="COL"===e.dimension?"right":"bottom",s="COL"===e.dimension?"columns":"rows";const i=[...e.elements];i.sort(((e,t)=>t-e));const n=je(i);this.executeOnAllRanges((i=>{if(i.sheetId!==e.sheetId)return{changeType:"NONE"};let r=i,a="NONE";for(let e of n){const n=Ot(e),l=Dt(e);if(i.zone[t]<=n&&n<=i.zone[o]){const e=Math.min(i.zone[o],l)-n+1;a="RESIZE",r=this.createAdaptedRange(r,s,a,-e)}else if(i.zone[t]>=n&&i.zone[o]<=l)a="REMOVE",r=i.clone({...this.getInvalidRange()});else if(i.zone[t]<=l&&i.zone[o]>=l){const e=l-i.zone[t]+1;a="RESIZE",r=this.createAdaptedRange(r,s,a,-e),r=this.createAdaptedRange(r,s,"MOVE",-(i.zone[t]-n))}else n<i.zone[t]&&(a="MOVE",r=this.createAdaptedRange(r,s,a,-(l-n+1)))}return"NONE"!==a?{changeType:a,range:r}:{changeType:"NONE"}}),e.sheetId);break}case"ADD_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",o="COL"===e.dimension?"right":"bottom",s="COL"===e.dimension?"columns":"rows";this.executeOnAllRanges((i=>{if(i.sheetId!==e.sheetId)return{changeType:"NONE"};if("after"===e.position){if(i.zone[t]<=e.base&&e.base<i.zone[o])return{changeType:"RESIZE",range:this.createAdaptedRange(i,s,"RESIZE",e.quantity)};if(e.base<i.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(i,s,"MOVE",e.quantity)}}else{if(i.zone[t]<e.base&&e.base<=i.zone[o])return{changeType:"RESIZE",range:this.createAdaptedRange(i,s,"RESIZE",e.quantity)};if(e.base<=i.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(i,s,"MOVE",e.quantity)}}return{changeType:"NONE"}}),e.sheetId);break}case"DELETE_SHEET":this.executeOnAllRanges((t=>{if(t.sheetId!==e.sheetId)return{changeType:"NONE"};const o=this.getters.getSheetName(e.sheetId);return{changeType:"REMOVE",range:t=t.clone({...this.getInvalidRange(),invalidSheetName:o})}}),e.sheetId);break;case"RENAME_SHEET":this.executeOnAllRanges((t=>{if(t.sheetId===e.sheetId)return{changeType:"CHANGE",range:t};if(e.name&&t.invalidSheetName===e.name){const o=void 0,s=e.sheetId;return{changeType:"CHANGE",range:t.clone({sheetId:s,invalidSheetName:o})}}return{changeType:"NONE"}}));break;case"MOVE_RANGES":{const t=e.target[0];this.executeOnAllRanges((o=>{if(o.sheetId!==e.sheetId||!cs(o.zone,t))return{changeType:"NONE"};const s=e.targetSheetId,i=e.col-t.left,n=e.row-t.top,r=this.createAdaptedRange(o,"both","MOVE",[i,n]),a=e.sheetId!==s||r.prefixSheet;return{changeType:"MOVE",range:r.clone({sheetId:s,prefixSheet:a})}}));break}}}finalize(){}verifyRangeRemoved(e){return t=>{const o=e(t);return"NONE"===o.changeType||Ko(o.range.zone)?o:{range:o.range,changeType:"REMOVE"}}}createAdaptedRange(e,t,o,s){const i=ms(e.unboundedZone,t,o,s);return e.clone({zone:i})}executeOnAllRanges(e,t){const o=this.verifyRangeRemoved(e);for(const e of this.providers)e(o,t)}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,o,s){const i=e.map((e=>Lr.fromRange(e,this.getters)));return i.map((e=>{if(!Ko(e.zone))return e;const i=e.prefixSheet?e.sheetId:s,n={...e.unboundedZone,left:e.isFullRow&&!e.unboundedZone.hasHeader?e.unboundedZone.left:e.unboundedZone.left+(e.parts[0].colFixed?0:t),right:e.isFullRow?e.unboundedZone.right:e.unboundedZone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:e.isFullCol&&!e.unboundedZone.hasHeader?e.unboundedZone.top:e.unboundedZone.top+(e.parts[0].rowFixed?0:o),bottom:e.isFullCol?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:o)};return e.clone({sheetId:i,zone:n}).orderZone()}))}removeRangesSheetPrefix(e,t){return t.map((t=>{const o=Lr.fromRange(t,this.getters);return o.prefixSheet&&o.sheetId===e?o.clone({prefixSheet:!1}):o}))}extendRange(e,t,o){const s=Lr.fromRange(e,this.getters),i="COL"===t?s.zone.right+o:s.zone.right,n="ROW"===t?s.zone.bottom+o:s.zone.bottom,r={left:s.zone.left,top:s.zone.top,right:s.isFullRow?void 0:i,bottom:s.isFullCol?void 0:n};return new Lr({...s,zone:r},this.getters.getSheetSize).orderZone()}getRangeFromSheetXC(e,t){if(!Bo.test(t)||!this.getters.tryGetSheet(e))return new Lr({sheetId:"",zone:{left:-1,top:-1,right:-1,bottom:-1},parts:[],invalidXc:t,prefixSheet:!1},this.getters.getSheetSize);let o,s=t,i=!1;t.includes("!")&&(({xc:s,sheetName:o}=Zo(t)),o&&(i=!0));const n=Yo(s),r=Lr.getRangeParts(s,n),a=o&&!this.getters.getSheetIdByName(o)?o:void 0,l=this.getters.getSheetIdByName(o)||e;return new Lr({prefixSheet:i,zone:n,sheetId:l,invalidSheetName:a,parts:r},this.getters.getSheetSize).orderZone()}getRangeString(e,t,o={useBoundedReference:!1,useFixedReference:!1}){if(!e)return Ri.InvalidReference;if(e.invalidXc)return e.invalidXc;if(!this.getters.tryGetSheet(e.sheetId))return Ri.InvalidReference;if(e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0)return Ri.InvalidReference;if(e.zone.left<0||e.zone.top<0)return Ri.InvalidReference;const s=Lr.fromRange(e,this.getters);let i=s.sheetId!==t||s.invalidSheetName||s.prefixSheet,n="";if(i&&(n=s.invalidSheetName?s.invalidSheetName:We(this.getters.getSheetName(s.sheetId))),i&&!n)return Ri.InvalidReference;let r=this.getRangePartString(s,0,o);return s.parts&&2===s.parts.length&&(s.zone.top!==s.zone.bottom||s.zone.left!==s.zone.right||s.parts[0].rowFixed||s.parts[0].colFixed||s.parts[1].rowFixed||s.parts[1].colFixed)&&(r+=":",r+=this.getRangePartString(s,1,o)),`${i?n+"!":""}${r}`}getRangeDataFromXc(e,t){return this.getters.getRangeFromSheetXC(e,t).rangeData}getRangeDataFromZone(e,t){return{_sheetId:e,_zone:t=this.getters.getUnboundedZone(e,t)}}getRangeFromZone(e,t){return new Lr({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=>Lr.fromRange(e,this.getters).unboundedZone)),s=t.map((e=>Lr.fromRange(e,this.getters).unboundedZone));return wo(o,s).map((t=>this.getRangeFromZone(e[0].sheetId,t)))}getRangeFromRangeData(e){const t={prefixSheet:!1,zone:e._zone,sheetId:e._sheetId,invalidSheetName:void 0,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}]};return new Lr(t,this.getters.getSheetSize)}isRangeValid(e){if(!e)return!1;const{xc:t,sheetName:o}=Zo(e);return null!==t.match(Bo)&&(!o||void 0!==this.getters.getSheetIdByName(o))}getRangesUnion(e){const t=e.map((e=>Lr.fromRange(e,this.getters).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=uS(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=uS(o),n=i.dependencies.map((o=>{const i=this.getters.getRangeFromSheetXC(e,o);return"keepSameReference"===s?i:Vr(e,t,i)}));return this.getters.getFormulaString(t,i.tokens,n)}getRangePartString(e,t,o={useBoundedReference:!1,useFixedReference:!1}){const s=e.parts[t]?.colFixed||o.useFixedReference?"$":"",i=vo(0===t?e.zone.left:e.zone.right),n=e.parts[t]?.rowFixed||o.useFixedReference?"$":"",r=String(0===t?e.zone.top+1:e.zone.bottom+1);let a="";return a=e.isFullCol&&!o.useBoundedReference?0===t&&e.unboundedZone.hasHeader?s+i+n+r:s+i:e.isFullRow&&!o.useBoundedReference?0===t&&e.unboundedZone.hasHeader?s+i+n+r:n+r:s+i+n+r,a}getInvalidRange(){return{parts:[],prefixSheet:!1,zone:{left:-1,top:-1,right:-1,bottom:-1},sheetId:"",invalidXc:Ri.InvalidReference}}}function QM(e,t){if(!e)return;const o=t(e);switch(o.changeType){case"NONE":return e;case"REMOVE":return;default:return o.range}}class eP extends GM{getters;constructor({getters:e,stateObserver:t}){super(t),this.getters=e}}const tP=new n;tP.add("pivots",(e=>{for(const t of e.getPivotIds()){const o=e.getPivot(t);mF.get(o.type).onIterationEndEvaluation(o)}}));const oP=Gb.mapping;function sP(e,t,o){return new iP(e,t,o).getParameters()}class iP{getters;computeCell;evalContext;rangeCache={};constructor(e,t,o){this.getters=t,this.computeCell=o,this.evalContext=Object.assign(Object.create(oP),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:jo(this.getters.getSheetName(e.sheetId),Qo(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=ns(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 Ko(e.zone)?e.invalidSheetName?new Ai(Mo("Invalid sheet name: %s",e.invalidSheetName)):void 0:new Di}}function nP(e,t,o,s,i){rP(e,t,o||0,s||e.length-1,i||lP)}function rP(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);rP(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(aP(e,o,t),i(e[s],h)>0&&aP(e,o,s);d<u;){for(aP(e,d,u),d++,u--;i(e[d],h)<0;)d++;for(;i(e[u],h)>0;)u--}0===i(e[o],h)?aP(e,o,u):aP(e,++u,s),u<=t&&(o=u+1),t<=u&&(s=u-1)}}function aP(e,t,o){var s=e[t];e[t]=e[o],e[o]=s}function lP(e,t){return e<t?-1:e>t?1:0}class cP{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(!yP(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;yP(e,a)&&(t.leaf?o.push(r):SP(e,a)?this._all(r,o):i.push(r))}t=i.pop()}return o}collides(e){let t=this.data;if(!yP(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(yP(e,n)){if(t.leaf||SP(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=CP([]),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=hP(e,o.children,t);if(-1!==s)return o.children.splice(s,1),i.push(o),this._condense(i),this}l||o.leaf||!SP(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=CP(e.slice(t,o+1)),dP(n,this.toBBox),n;s||(s=Math.ceil(Math.log(i)/Math.log(r)),r=Math.ceil(i/Math.pow(r,s-1))),n=CP([]),n.leaf=!1,n.height=s;const a=Math.ceil(i/r),l=a*Math.ceil(Math.sqrt(r));wP(e,t,o,l,this.compareMinX);for(let i=t;i<=o;i+=l){const t=Math.min(i+l-1,o);wP(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 dP(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=fP(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),gP(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=CP(o.children.splice(n,o.children.length-n));r.height=o.height,r.leaf=o.leaf,dP(o,this.toBBox),dP(r,this.toBBox),t?e[t-1].children.push(r):this._splitRoot(o,r)}_splitRoot(e,t){this.data=CP([e,t]),this.data.height=e.height+1,this.data.leaf=!1,dP(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=uP(e,0,r,this.toBBox),a=uP(e,r,o,this.toBBox),l=bP(t,a),c=fP(t)+fP(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:pP,i=e.leaf?this.compareMinY:mP;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=uP(e,0,t,i),r=uP(e,o-t,o,i);let a=vP(n)+vP(r);for(let s=t;s<o-t;s++){const t=e.children[s];gP(n,e.leaf?i(t):t),a+=vP(n)}for(let s=o-t-1;s>=t;s--){const t=e.children[s];gP(r,e.leaf?i(t):t),a+=vP(r)}return a}_adjustParentBBoxes(e,t,o){for(let s=o;s>=0;s--)gP(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():dP(e[o],this.toBBox)}}function hP(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 dP(e,t){uP(e,0,e.children.length,t,e)}function uP(e,t,o,s,i){i||(i=CP(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];gP(i,e.leaf?s(t):t)}return i}function gP(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 pP(e,t){return e.minX-t.minX}function mP(e,t){return e.minY-t.minY}function fP(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function vP(e){return e.maxX-e.minX+(e.maxY-e.minY)}function bP(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 SP(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function yP(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function CP(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function wP(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;nP(e,r,t,o,i),n.push(t,r,r,o)}}class EP{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 xP,this.rTrees[e].load(t[e])}insert(e){const t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new xP),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 xP extends cP{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 IP{createEmptyPositionSet;dependencies=new g_;rTree;constructor(e,t=[]){this.createEmptyPositionSet=e,this.rTree=new EP(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(vs(e)));for(const e in r){const t=wo(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 RP 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 TP{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]=RP.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 AP{resultsToArrayFormulas=new EP;arrayFormulasToResults=new g_;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map((e=>e.data))||_P}getArrayResultZone(e){return this.arrayFormulasToResults.get(e)}removeNode(e){this.resultsToArrayFormulas.remove({boundingBox:{sheetId:e.sheetId,zone:vs(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 _P=[],DP=Ar(new class extends Ai{constructor(e=Mo("Circular reference")){super(e,Ri.CircularDependency)}}),OP=Ar({value:null});class FP{context;getters;compilationParams;evaluatedCells=new g_;formulaDependencies=ut(new IP(this.createEmptyPositionSet.bind(this)));blockedArrayFormulas=new TP({});spreadingRelations=new AP;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=sP(this.context,this.getters,this.computeAndSave.bind(this))}getEvaluatedCell(e){return this.evaluatedCells.get(e)||OP}getSpreadZone(e,t={ignoreSpillError:!1}){const o=this.spreadingRelations.getArrayResultZone(e);if(!o)return;const s=this.evaluatedCells.get(e);return s?.type!==ri.error||t.ignoreSpillError&&s?.value===Ri.SpilledBlocked?is(vs(e),o):vs(e)}getEvaluatedPositions(){return this.evaluatedCells.keys()}getEvaluatedPositionsInSheet(e){return this.evaluatedCells.keysForSheet(e)}getArrayFormulaSpreadingOn(e){if(!(this.getEvaluatedCell(e).type!==ri.empty&&!this.getters.getCell(e)?.isFormula))return this.spreadingRelations.isArrayFormula(e)?e:void 0;const t=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e.sheetId,vs(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=sP(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 TP(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=us(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 AP,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 IP(this.createEmptyPositionSet.bind(this),e)}))}evaluateAllCells(){const e=performance.now();this.evaluatedCells=new g_,this.evaluate(this.getAllCells()),console.debug("evaluate all cells",performance.now()-e,"ms")}evaluateFormulaResult(e,t){const o=uS(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=NP(t,this.compilationParams,e,this.buildSafeGetSymbolValue(o),this.compilationParams.evalContext.__originCellPosition);return wi(s)?ln(s,PP):PP(s)}catch(e){return Zb(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 TP({});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!==OP&&this.evaluatedCells.set(o,s)}tP.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 OP;const s=o.id,i={format:o.format,locale:this.getters.getLocale()};try{return this.cellsBeingComputed.has(s)?DP:(this.cellsBeingComputed.add(s),o.isFormula?this.computeFormulaCell(e,o):Rr(o,i))}catch(e){return e.value=e?.value||Ri.GenericError,e.message=e?.message||Yb,Ar(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=NP(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e);if(!wi(o)){const s=Ar(PP(o),this.getters.getLocale(),t);return s.type===ri.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),MP(s,i,this.checkCollision(e)),MP(s,i,this.spreadValues(e,o)),this.invalidatePositionsDependingOnSpread(e.sheetId,n),Ar(PP(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===ys(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 Mi(Mo("Result couldn't be automatically expanded. Please insert more rows."));if(a)throw new Mi(Mo("Result couldn't be automatically expanded. Please insert more columns."));throw new Mi(Mo("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 Mi(Mo("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!==ri.empty)throw this.blockedArrayFormulas.add(e),new Mi(Mo("Array result was not expanded because it would overwrite data in %s.",Co(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=Ar(PP(s[i][n]),this.getters.getLocale(),a);l.type===ri.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 DP;this.symbolsBeingComputed.add(t);try{const o=e?.(t);return o||new _i(Mo("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=us(e);for(const e in o)t.push(...o[e].map((t=>({sheetId:e,zone:t}))));return this.formulaDependencies().getCellsDependingOn(t)}}function MP(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 PP(e){return null===e.value||void 0===e.value?{...e,value:0}:e}function NP(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 kP=/"(#[0-9a-fA-F]{6})"/g;const LP={isValid:!0};const VP="0.00%";function UP(e){return class extends e{getters;cache={};rankAsc={};rankDesc={};runningTotal={};runningTotalInPercent={};constructor(e,t){super(e,t),this.getters=t.getters}init(e){this.cache={},this.rankAsc={},this.rankDesc={},this.runningTotal={},this.runningTotalInPercent={},super.init(e)}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(o.length+s.length!==t.length){const o=this.getValuesToAggregate(e,t),s=Gl[e.aggregator];if(!s)return{value:0};try{return s([o],this.getters.getLocale())}catch(t){return Zb(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}=fl(this,t),s=o.findIndex((t=>t.field===e));return this.getPivotHeaderValueAndFormat(o.slice(0,s+1))}if(s.find((t=>t.nameWithGranularity===e))){const{rowDomain:o}=fl(this,t),s=o.findIndex((t=>t.field===e));return this.getPivotHeaderValueAndFormat(o.slice(0,s+1))}return this.getPivotCellValueAndFormat(e,t)}));return wi(n)?n[0][0]:n}getValuesToAggregate(e,t){const{rowDomain:o,colDomain:s}=fl(this,t),i=super.getTableStructure(),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}{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=ec(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 e}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:Ri.NotAvailable,message:Mo('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 Zb(e,"COMPUTE_MEASURE_DISPLAY_VALUE")}}asPercentOfGrandTotal(e,t){const o=this.getGrandTotal(t.id);return 0===o?{value:Ri.DivisionByZero}:{value:this.measureValueToNumber(e)/o,format:VP}}asPercentOfRowTotal(e,t,o){const s=this.getRowTotal(t.id,o);return 0===s?{value:Ri.DivisionByZero}:{value:this.measureValueToNumber(e)/s,format:VP}}asPercentOfColumnTotal(e,t,o){const s=this.getColumnTotal(t.id,o);return 0===s?{value:Ri.DivisionByZero}:{value:this.measureValueToNumber(e)/s,format:VP}}asPercentOfParentRowTotal(e,t,o){const s=function(e,t){const{colDomain:o,rowDomain:s}=fl(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:VP}}asPercentOfParentColumnTotal(e,t,o){const s=function(e,t){const{colDomain:o,rowDomain:s}=fl(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:VP}}asPercentOfParentTotal(e,t,o,s){const{fieldNameWithGranularity:i}=s;if(!i)return e;if(!Cl(i,o))return{value:""};const n=function(e,t,o){let{rowDomain:s,colDomain:i}=fl(e,o);if("row"===wl(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:VP}}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:Ri.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}=fl(this,o),h=El(c),d=El(l),u=a[h]?.[d];return{value:u??"",format:"running_total"===i?e.format:VP}}asPercentOf(e,t,o,s){const{fieldNameWithGranularity:i,value:n}=s;if(void 0===n||!i)return e;if(!Cl(i,o))return{value:""};let r=this.getComparisonValue(t,o,i,n),a=this.strictMeasureValueToNumber(e);return 0===r||"sameValue"===r&&0===a?{value:Ri.DivisionByZero}:!r||"sameValue"===r&&!a?{value:""}:"sameValue"===r?{value:1,format:VP}:void 0===a?{value:Ri.NullError}:{value:a/r,format:VP}}asDifferenceFrom(e,t,o,s){const{fieldNameWithGranularity:i,value:n}=s;if(void 0===n||!i)return e;if(!Cl(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(!Cl(i,o))return{value:""};let r=this.getComparisonValue(t,o,i,n);const a=this.strictMeasureValueToNumber(e);return 0===r?{value:Ri.DivisionByZero}:r&&"sameValue"!==r?void 0===a?{value:Ri.NullError}:{value:(a-r)/r,format:VP}:{value:""}}asRank(e,t,o,s,i){const{fieldNameWithGranularity:n}=s;if(!n)return e;if(!Cl(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}=fl(this,o),h=El(c),d=El(l),u=a[h]?.[d];return{value:u??""}}computeRank(e,t,o){const s={},i=wl(this,t),n="row"===i?"column":"row";let r=this.getPivotValueCells(e.id);"column"===i&&(r=cn(r));for(const a of r){const r=El(vl(this,n,a[0].domain)),l=a.map((t=>({...t,value:this.strictMeasureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain)),rowDomain:vl(this,i,t.domain)}))).filter((e=>Cl(t,e.rowDomain))),c=Object.groupBy(l,(e=>Il(e.rowDomain,t)));for(const e in c)c[e]=Mt(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=El(vl(this,i,e.domain)),n=c[Il(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:Pt(s)}computeRunningTotal(e,t,o){const s={},i=wl(this,t),n="row"===i?"column":"row";let r=this.getPivotValueCells(e.id);"column"===i&&(r=cn(r));for(const a of r){const r=El(vl(this,n,a[0].domain));s[r]={};const l={},c=a.map((t=>({...t,rowDomain:vl(this,i,t.domain),value:this.measureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain))}))).filter((e=>Cl(t,e.rowDomain)));for(const e of c){const o=El(e.rowDomain),i=Rl(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=El(o),n=Rl(o,t),a=s[r][i]||0,c=l[n];s[r][i]=c?a/c:void 0}}return"row"===i?s:Pt(s)}getGrandTotal(e){const t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){const o=fl(this,t).rowDomain,s=this._getPivotCellValueAndFormat(e,o);return this.measureValueToNumber(s)}getColumnTotal(e,t){const o=fl(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===pl||s===ml?function(e,t,o,s){const i=wl(e,o),n="row"===i?e.getTableStructure().getRowTree():e.getTableStructure().getColTree(),r=Sl(vl(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 yl(t,o,a[qe(c+(s===pl?-1:1),0,a.length-1)])}(this,t,o,s):yl(t,o,s);if(mt(i,t))return"sameValue";if(!i||!function(e,t){const{rowDomain:o,colDomain:s}=fl(e,t);return bl(o,e.getTableStructure().getRowTree())&&bl(s,e.getTableStructure().getColTree())}(this,i))throw new Oi;const n=this._getPivotCellValueAndFormat(e.id,i);return this.strictMeasureValueToNumber(n)}getPivotValueCells(e){return this.getTableStructure().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`)}getTableStructure(){const e=super.getTableStructure();return this.sortTableStructure(e),e}sortTableStructure(e){if(!this.definition.sortedColumn||e.isSorted)return;const t=this.definition.sortedColumn.measure;lc(this.definition.sortedColumn,this)&&e.sort(t,this.definition.sortedColumn,((e,t)=>this._getPivotCellValueAndFormat(e,t)))}}}const HP=["ADD_PIVOT","UPDATE_PIVOT"];function BP(e){return HP.includes(e.type)}class zP extends GM{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 $P{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}=RS.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}}}}function WP(e,t){if("SPREADSHEET"!==e.pivot.type)return e;if(e.pivot.dataSet?.sheetId!==t.sheetId)return e;const o=pc(e.pivot.dataSet.zone,t),s=o?{...e.pivot.dataSet,zone:o}:void 0;return{...e,pivot:{...e.pivot,dataSet:s}}}function GP(e,t){return{...e,definition:CR(e.definition,t)}}function qP(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(let 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 ZP(e,t){if(e.sheetId!==t.sheetId)return e;const o=pc(e.zone,t);if(!o)return;const s=e.newTableRange?mc(e.newTableRange,t):void 0;return{...e,newTableRange:s,zone:o}}function jP(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let o;if("REMOVE_COLUMNS_ROWS"===t.type)o=Gr(t.elements,[e.base])[0];else if("ADD_COLUMNS_ROWS"===t.type){o=Wr(pt(t.position,t.base),t.quantity,[e.base])[0]}return void 0!==o?{...e,base:o}:void 0}function YP(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;const o=Ze(e.start,e.end+1);let s=[];if("REMOVE_COLUMNS_ROWS"===t.type)s=Gr(t.elements,o);else if("ADD_COLUMNS_ROWS"===t.type){s=Wr(pt(t.position,t.base),t.quantity,o)}return 0!==s.length?{...e,start:Math.min(...s),end:Math.max(...s)}:void 0}Y_.addTransformation("ADD_COLUMNS_ROWS",["ADD_COLUMNS_ROWS"],jP),Y_.addTransformation("REMOVE_COLUMNS_ROWS",["ADD_COLUMNS_ROWS"],jP),Y_.addTransformation("ADD_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],GP),Y_.addTransformation("REMOVE_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],GP),Y_.addTransformation("DELETE_SHEET",["MOVE_RANGES"],(function(e,t){const o=t.sheetId;if(e.targetSheetId===o||e.sheetId===o)return;return e})),Y_.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART"],(function(e,t){if(e.id===t.id)return;return e})),Y_.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})),Y_.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)for(const e of t.target)as(s,e)||o.push({...s});if(o.length)return{...e,target:o};return})),Y_.addTransformation("ADD_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],qP),Y_.addTransformation("REMOVE_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],qP),Y_.addTransformation("ADD_COLUMNS_ROWS",["UPDATE_TABLE"],ZP),Y_.addTransformation("REMOVE_COLUMNS_ROWS",["UPDATE_TABLE"],ZP),Y_.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:tw.styleId}}})),Y_.addTransformation("ADD_COLUMNS_ROWS",["GROUP_HEADERS","UNGROUP_HEADERS","FOLD_HEADER_GROUP","UNFOLD_HEADER_GROUP"],YP),Y_.addTransformation("REMOVE_COLUMNS_ROWS",["GROUP_HEADERS","UNGROUP_HEADERS","FOLD_HEADER_GROUP","UNFOLD_HEADER_GROUP"],YP),Y_.addTransformation("REMOVE_PIVOT",["RENAME_PIVOT","DUPLICATE_PIVOT","INSERT_PIVOT","UPDATE_PIVOT"],(function(e,t){if(e.pivotId===t.pivotId)return;return e})),Y_.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})),Y_.addTransformation("ADD_COLUMNS_ROWS",["ADD_PIVOT","UPDATE_PIVOT"],WP),Y_.addTransformation("REMOVE_COLUMNS_ROWS",["ADD_PIVOT","UPDATE_PIVOT"],WP);const XP=[{match:function(e){return"sheetId"in e},fn:QP},{match:function(e){return"target"in e&&"sheetId"in e},fn:function(e,t){const o=QP(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;const s=[];for(const o of e.target){const e=pc(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=QP(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;const s=pc(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=QP(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(let 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)&&ls(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=QP(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=Gr(t.elements,e.elements);else if("ADD_COLUMNS_ROWS"===t.type){s=Wr(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=>mc(e,t))).filter(at);if(!o.length)return"IGNORE_COMMAND";return{...e,ranges:o}}}];function KP(e,t){const o=Y_.getTransformation(e.type,t.type);return o?o(e,t):function(e,t){for(const{match:o,fn:s}of XP)if(o(e)){const o=s(e,t);if("SKIP_TRANSFORMATION"===o)continue;if("IGNORE_COMMAND"===o)return;e=o}return e}(e,t)}function JP(e,t){let o=[...e];for(const e of t)o=o.map((t=>KP(t,e))).filter(at);return o}function QP(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 eN{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 tN extends Error{}class oN extends fc{revisions;transportService;serverRevisionId;clients={};clientId="local";debouncedMove;pendingMessages=[];waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;uuidGenerator=new la;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 eN(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))}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})}getClient(){const e=this.clients[this.clientId];if(!e)throw new tN("The client left the session");return e}getConnectedClients(){return new Set(Object.values(this.clients).filter(at))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return 0===this.pendingMessages.length}getLastLocalNonEmptyRevision(){return this.lastLocalOperation}_move(e){if(!this.clients[this.clientId])return;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.getClient();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 eN(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:JP(o,t)})}break;case"SNAPSHOT_CREATED":{const t=new eN(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 sN=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 iN(e){return sN.has(e.type)}const nN=[rN,function(e,t){return"target"in t&&Array.isArray(t.target)?{...Be(t),target:e.getSelectedZones()}:t},function(e,t){if(!("row"in t)||!("col"in t))return t;const{col:o,row:s}=e.getActivePosition();return{...Be(t),col:o,row:s}},function(e,t){return"ranges"in t?{...Be(t),ranges:e.getSelectedZones().map((t=>e.getRangeDataFromZone(e.getActiveSheetId(),t)))}:t}];function rN(e,t){return"sheetId"in t?{...Be(t),sheetId:e.getActiveSheetId()}:t}function aN(e,t){return"zone"in t?{...Be(t),zone:e.getSelectedZone()}:t}const lN=new la;function cN(e,t){const o=e.getSelectedZone();return{...rN(e,t),elements:"COL"===t.dimension?Ze(o.left,o.right+1):Ze(o.top,o.bottom+1)}}function hN(e,t){const o=e.getSelectedZone();return{...Be(t),zone:o}}function dN(e,t){const o=Be(t),s=e.getSelectedZone(),{top:i,bottom:n,left:r,right:a}=s;return"cols"in o?o.cols=Ze(r,a+1):"rows"in o&&(o.rows=Ze(i,n+1)),o}function uN(e,t){const o=e.getSelectedZone();return{...rN(e,t),start:"COL"===t.dimension?o.left:o.top,end:"COL"===t.dimension?o.right:o.bottom}}const gN=new n;gN.add("UPDATE_CELL",mN),gN.add("CLEAR_CELL",mN),gN.add("CLEAR_CELLS",mN),gN.add("DELETE_CONTENT",mN),gN.add("ADD_MERGE",mN),gN.add("REMOVE_MERGE",mN),gN.add("SET_FORMATTING",mN),gN.add("CLEAR_FORMATTING",mN),gN.add("SET_BORDER",mN),gN.add("CREATE_TABLE",mN),gN.add("REMOVE_TABLE",mN),gN.add("HIDE_SHEET",mN),gN.add("ADD_COLUMNS_ROWS",(function(e,t){const o=e.getActivePosition();return{...rN(e,t),base:"COL"===t.dimension?o.col:o.row}})),gN.add("REMOVE_COLUMNS_ROWS",cN),gN.add("HIDE_COLUMNS_ROWS",cN),gN.add("RESIZE_COLUMNS_ROWS",cN),gN.add("CREATE_SHEET",(function(e,t){const o=Be(t);o.sheetId=lN.smallUuid();const s=t.name||e.getSheet(e.getActiveSheetId()).name,i=s.match(/(.+?)\d*$/)?.[1]||s;return o.name=e.getNextSheetName(i),o})),gN.add("CREATE_FIGURE",(function(e,t){const o=rN(e,t);return o.figure.id=lN.smallUuid(),o})),gN.add("CREATE_CHART",(function(e,t){return{...rN(e,t),id:lN.smallUuid()}})),gN.add("CREATE_IMAGE",(function(e,t){return{...rN(e,t),figureId:lN.smallUuid()}})),gN.add("GROUP_HEADERS",uN),gN.add("UNGROUP_HEADERS",uN),gN.add("UNGROUP_HEADERS",uN),gN.add("UNFOLD_HEADER_GROUPS_IN_ZONE",aN),gN.add("FOLD_HEADER_GROUPS_IN_ZONE",aN);const pN=new n;function mN(e,t){let o=Be(t);for(const t of nN)o=t(e,o);return o}function fN(e,t){if(e.rootCommand&&"object"==typeof e.rootCommand)return mi(e.rootCommand)?function(e,t){if(!t)return;if(!gN.contains(t.type))return;return gN.get(t.type)(e,t)}(t,e.rootCommand):function(e,t,o){if(!pN.contains(t.type))return;return pN.get(t.type)(e,t,o)}(t,e.rootCommand,e.commands)}pN.add("PASTE",(function(e,t){return{type:"REPEAT_PASTE",pasteOption:Be(t.pasteOption),target:e.getSelectedZones()}})),pN.add("INSERT_CELL",hN),pN.add("DELETE_CELL",hN),pN.add("AUTORESIZE_COLUMNS",dN),pN.add("AUTORESIZE_ROWS",dN),pN.add("SORT_CELLS",(function(e,t){const o=e.getSelectedZone();return{...rN(e,t),col:o.left,row:o.top,zone:o}})),pN.add("SUM_SELECTION",mN),pN.add("SET_DECIMAL",mN);class vN{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,size:s}=this.getters.getColDimensions(this.sheetId,e),{end:i,size:n}=this.getters.getRowDimensions(this.sheetId,t),r=this.searchHeaderIndex("COL",o-this.viewportWidth,0),a=this.getters.getColSize(this.sheetId,r),l=this.searchHeaderIndex("ROW",i-this.viewportHeight,0),c=this.getters.getRowSize(this.sheetId,l);let h=o-this.offsetCorrectionX;this.canScrollHorizontally&&(h+=Math.max(oe,Math.min(a,this.viewportWidth-s)),h=Math.max(h,this.viewportWidth));let d=i-this.offsetCorrectionY;return this.canScrollVertically&&(d+=Math.max(se+5,Math.min(c,this.viewportHeight-n)),d=Math.max(d,this.viewportHeight),i+ce>d&&!this.getters.isReadonly()&&(d+=ce)),{width:h,height:d}}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);ls(s,this.boundaries.top,this.boundaries)&&this.adjustPositionX(s),ls(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=ns(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=ns(e,this),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 bN=(new n).add("settings",class extends qM{static getters=["getLocale"];locale=yi;allowDispatch(e){return"UPDATE_LOCALE"===e.type?Da(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===$a(e)&&(o=$a(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??yi}export(e){e.settings={locale:this.locale}}}).add("sheet",class extends qM{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"];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":"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||$t(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=Ot(e.elements),o=Dt(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.name);break;case"COLOR_SHEET":this.history.update("sheets",e.sheetId,"color",e.color);break;case"HIDE_SHEET":this.hideSheet(e.sheetId);break;case"SHOW_SHEET":this.showSheet(e.sheetId);break;case"DUPLICATE_SHEET":this.duplicateSheet(e.sheetId,e.sheetIdTo);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(let t of e.sheets)this.sheetIdsMapName[t.name]=t.id;for(let 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:$r(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(at).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=ze(e);for(const e in this.sheetIdsMapName)if(e.toUpperCase()===t.toUpperCase())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(at)}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 Nt(e,this.orderedSheetIds.map(this.getSheetName.bind(this)),{compute:(e,t)=>`${e}${t}`,computeFirstOne:!0})}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,Ze(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&&"row"in e&&t.push({top:e.row,left:e.col,bottom:e.row,right:e.col}),t}checkZonesExistInSheet(e,t){if(!t.every(Ko))return"InvalidRange";if(t.length){const o=this.getSheetZone(e);return t.every((e=>cs(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:$r(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);let 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(Mo("There is not enough visible sheets"))}checkSheetName(e){const t=this.getters.tryGetSheetName(e.sheetId);if(void 0!==t&&e.name===t)return"UnchangedSheetName";const{orderedSheetIds:o,sheets:s}=this,i=e.name&&e.name.trim().toLowerCase();return o.find((t=>s[t]?.name.toLowerCase()===i&&t!==e.sheetId))?"DuplicatedSheetName":_e.test(i)?"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(let 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(let o of t)if(o.left<e.quantity&&e.quantity<=o.right)return"MergeOverlap";return"Success"}isRenameAllowed(e){return e.name&&e.name.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){const o=this.getSheet(e),s=this.getDuplicateSheetName(o.name),i=Be(o);i.id=t,i.name=s;for(let e=0;e<=i.numberOfCols;e++)for(let t=0;t<=i.rows.length;t++)i.rows[t]&&(i.rows[t].cells[e]=void 0);const n=this.orderedSheetIds.slice(),r=n.indexOf(e);n.splice(r+1,0,i.id),this.history.update("orderedSheetIds",n),this.history.update("sheets",Object.assign({},this.sheets,{[i.id]:i}));for(const t of Object.values(this.getters.getCells(e))){const{col:e,row:o}=this.getCellPosition(t.id);this.dispatch("UPDATE_CELL",{sheetId:i.id,col:e,row:o,content:t.content,format:t.format,style:t.style})}const a=Object.assign({},this.sheetIdsMapName);a[i.name]=i.id,this.history.update("sheetIdsMapName",a)}getDuplicateSheetName(e){const t=this.orderedSheetIds.map(this.getSheetName.bind(this));return Nt(Mo("Copy of %s",e).toString(),t)}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(let 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(let o of je(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(let 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(let 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(let 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(let 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(let 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(yo);let o=e.rowNumber,s=e.colNumber;for(let{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 qM{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(Ze(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=Be(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;Ze(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&&Et([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]=Wr(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=Gr(o,Ze(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=tC(t,e,i);n.outlineLevel=s+1,o.isFolded&&(n.isHidden=!0)}if(o.isFolded){tC(t,e,o.end+1).collapsed=!0}}}}}}).add("header visibility",class extends qM{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":Ot(e.elements)<0||Dt(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,Be(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(let 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(let t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!0);break;case"UNHIDE_COLUMNS_ROWS":for(let t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!1)}}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=Ze(0,this.getters.getNumberHeaders(e,t)),s=[];return this.getters.getHeaderGroups(e,t).forEach((e=>{e.isFolded&&s.push(...Ze(e.start,e.end+1))})),o.filter((o=>!this.hiddenHeaders[e][t][o]&&!s.includes(o)))}import(e){for(let t of e.sheets){this.hiddenHeaders[t.id]={COL:[],ROW:[]};for(let e=0;e<t.rowNumber;e++)this.hiddenHeaders[t.id].ROW[e]=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(let 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 qM{static getters=["getCoreTable","getCoreTables","getCoreTableMatchingTopLeft"];tables={};nextTableId=1;adaptRanges(e,t){const o=t?[t]:this.getters.getSheetIds();for(const t of o)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 Cs(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(as(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);this.dispatch("REMOVE_MERGE",{sheetId:e.sheetId,target:s});const i=this.consumeNextId(),n=e.config||tw,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=>!ns(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=>cs(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(at):[]}getCoreTable({sheetId:e,col:t,row:o}){return this.getCoreTables(e).find((e=>ls(t,o,e.range.zone)))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter((e=>t.some((t=>as(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(const e of gs(a)){const o={sheetId:t,...e},s=this.getters.getCell(o)?.content;if(s||this.getters.isInMerge(o)||this.getTablesOverlappingZones(t,[vs(e)]).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 Ze(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=bs(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 Ze(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,bs(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 AF(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 AF(o.id,s,t.config,this.getters.getRangeFromZone)}));return{id:t.id,range:o,filters:s,config:Be(t.config),type:t.type}}copyDynamicTableForSheet(e,t){const o=this.getters.getRangeFromZone(e,t.range.zone);return{id:t.id,range:o,config:Be(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=AF(e.id,o,t.config,this.getters.getRangeFromZone);n.push(i)}}const r=i.zone;if(n.length<hs(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||tw,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:Qo(e.range.zone),type:e.type};mt(e.config,tw)||(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=Qo(e.range.zone);t.tables.push({range:o,filters:[],config:e.config})}}}).add("dataValidation",class extends qM{static getters=["cellHasListDataValidationIcon","getDataValidationRule","getDataValidationRules","getValidationRuleForCell"];rules={};adaptRanges(e,t){const o=t?[t]:Object.keys(this.rules);for(const t of o)this.loopThroughRangesOfSheet(t,e)}loopThroughRangesOfSheet(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=Be(this.rules[e.sheetId]).map((t=>({...t,ranges:t.ranges.map((t=>Vr(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=wo(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,Co(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(ls(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)}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),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){o=Be(o);for(const e of o)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 Br(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={...Be(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 vO.contains(e.rule.criterion.type)?"Success":"UnknownDataValidationCriterionType"}checkCriterionHasValidNumberOfValues(e){const t=e.rule.criterion,o=vO.get(t.type).numberOfValues(t);return void 0!==o&&t.values.length!==o?"InvalidNumberOfCriterionValues":"Success"}checkCriterionValuesAreValid(e){const t=e.rule.criterion,o=vO.get(t.type);return t.values.some((e=>"onlyFormulas"===o.allowedValues&&!e.startsWith("=")||(e.startsWith("=")?"onlyLiterals"===o.allowedValues||uS(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 qM{static getters=["zoneToXC","getCells","getTranslatedCellFormula","getCellStyle","getCellById","getFormulaString","getFormulaMovedInSheet"];nextId=1;cells={};adaptRanges(e,t){for(const o of Object.keys(this.cells))for(const s of Object.values(this.cells[o]||{}))if(s.isFormula)for(const i of s.compiledFormula.dependencies)if(!t||i.sheetId===t){const t=e(i);"NONE"!==t.changeType&&this.history.update("cells",o,s.id,"compiledFormula","dependencies",s.compiledFormula.dependencies.indexOf(i),t.range)}}allowDispatch(e){switch(e.type){case"UPDATE_CELL":return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessUpdateCell);case"CLEAR_CELL":return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessClearCell);case"UPDATE_CELL_POSITION":return!e.cellId||this.cells[e.sheetId]?.[e.cellId]?"Success":"InvalidCellId";default:return"Success"}}handle(e){switch(e.type){case"SET_FORMATTING":"style"in e&&this.setStyle(e.sheetId,e.target,e.style),"format"in e&&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(let o of wo(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(let s of wo(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(let o of wo(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=Ze(e.base,e.base+e.quantity),s=e.base+e.quantity):(o=Ze(e.base+1,e.base+e.quantity+1),s=e.base),t(e.sheetId,s,o)}import(e){for(let t of e.sheets){const o=t.id,s=new g_;for(const e in t.cells)if(t.cells[e]){const{col:o,row:i}=yo(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 Is(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(let 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=Co(s.col,s.row),l=this.removeDefaultStyleValues(r.style);if(Object.keys(l).length){const o=Es(l,t);e[o]??=[],e[o].push(s)}if(r.format){const e=Es(r.format,o);i[e]??=[],i[e].push(s)}r.content&&(n[a]=r.content)}s.styles=xs(e),s.formats=xs(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||[])xr(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(gS(s).dependencies.map((t=>this.getters.getRangeFromSheetXC(e,t))),t,o,e);return this.getFormulaString(e,s,i)}getFormulaMovedInSheet(e,t,o){const s=gS(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=Co((t=this.getters.expandZone(e,t)).left,t.top,o[0]),i=Co(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(let s of wo(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(let 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(let 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?wt(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=Tr(t,i);return Ir(o=o||("number"==typeof n?dr(t,i)||ur(t):void 0))||Li(t)||(t=Zi(n)),{id:e,content:t,style:s,format:o,isFormula:!1,parsedValue:n}}createFormulaCell(e,t,o,s,i){const n=uS(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 ZM(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 ls(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 qM{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(at))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){const o=t?[t]:Object.keys(this.merges);for(const t of o)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map((t=>this.getMergeById(e,parseInt(t,10)))).filter(at)}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(at)}getSelectionRangeString(e,t){const o=Lr.fromRange(e,this.getters),s=this.getters.expandZone(o.sheetId,o.zone),i=o.clone({zone:{...s,bottom:o.isFullCol?void 0:s.bottom,right:o.isFullRow?void 0:s.right}}),n=this.getters.getRangeString(i,t);if(this.isSingleCellOrMerge(o.sheetId,o.zone)){const{sheetName:e,xc:t}=Zo(n);return jo(e,t.split(":")[0])}return n}doesIntersectMerge(e,t){for(const o of this.getMerges(e))if(as(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){let{left:o,right:s,top:i,bottom:n}=t,r={left:o,right:s,top:i,bottom:n};for(let t in this.merges[e]){const o=this.getMergeById(e,parseInt(t));o&&as(o,r)&&(r=is(o,r))}return rs(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)&&rs(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(let e of o)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let 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 rs(t,o);const{numberOfCols:s,numberOfRows:i}=hs(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=qe(s,0,this.getters.getNumberCols(e)-1),n=qe(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?KM(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&&as(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);for(const e of t)if(e.left<o&&e.right>=o||e.top<s&&e.bottom>=s)return"FrozenPaneOverlap";return"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||!rs(e,i))return"InvalidTarget"}return"Success"}addMerge(e,t){let{left:o,right:s,top:i,bottom:n}=t;s=qe(s,0,this.getters.getNumberCols(e)-1),n=qe(n,0,this.getters.getNumberRows(e)-1);if(Co(o,i)===Co(s,n))return;const r=this.getters.getCell({sheetId:e,col:o,row:i});let a=this.nextId++;this.history.update("merges",e,a,this.getters.getRangeFromSheetXC(e,Qo({left:o,top:i,right:s,bottom:n})));let 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(let 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&&rs(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}=hs(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 gs(t))this.history.update("mergeCellMap",e,o,s,t.id)}import(e){const t=e.sheets||[];for(let e of t)this.history.update("merges",e.id,{}),this.history.update("mergeCellMap",e.id,{}),e.merges&&this.importMerges(e.id,e.merges)}importMerges(e,t){for(let o of t)this.addMerge(e,Xo(o))}export(e){for(let t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...XM(e))}}exportForExcel(e){this.export(e)}}).add("headerSize",class extends qM{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,Be(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=It(this.sizes[e.sheetId][e.dimension],e.elements);this.history.update("sizes",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{let t=[...this.sizes[e.sheetId][e.dimension]];const 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]||oe)}getUserRowSize(e,t){const o=this.sizes[e]?.ROW[t];return o?Math.round(o):void 0}import(e){for(let t of e.sheets){const e={COL:Array(t.colNumber).fill(void 0),ROW:Array(t.rowNumber).fill(void 0)};for(let[o,s]of Object.entries(t.rows))s.size&&(e.ROW[o]=s.size);for(let[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(let o of e.sheets){void 0===o.rows&&(o.rows={});for(const e of Ze(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)??se});void 0===o.cols&&(o.cols={});for(let e of Ze(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 qM{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=>Be(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_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 je(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?Be(s):null}getBordersColors(e){const t=[],o=this.borders[e];if(o)for(const e of o.filter(at))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=Ze(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(let o of s)this.addBorder(e,o,i,t)}}}ensureRowBorderContinuity(e,t,o){const s=Ze(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(let o of s)this.addBorder(e,i,o,t)}}}getCommonSides(e,t){const o={};for(let 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(at);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]?Ze(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(let n of wo(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(let 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(let i of wo(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 Is(t.id,t.borders)){const{sheetId:t,col:i,row:n}=o,r=e.borders[s];this.setBorder(t,i,n,r,!1)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,Xo(e))}export(e){const t={};for(let 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=Es(n,t),a={sheetId:o.id,col:s,row:i};e[r]??=[],e[r].push(a)}}o.borders=xs(e)}e.borders=t}exportForExcel(e){this.export(e)}}).add("conditional formatting",class extends qM{static getters=["getConditionalFormats","getRulesSelection","getRulesByCell","getAdaptedCfRanges"];cfRules={};loopThroughRangesOfSheet(e,t){for(const o of this.cfRules[e]){if("DataBarRule"===o.rule.type&&o.rule.rangeValues){const s=t(o.rule.rangeValues);switch(s.changeType){case"REMOVE":this.history.update("cfRules",e,this.cfRules[e].indexOf(o),"rule","rangeValues",void 0);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",e,this.cfRules[e].indexOf(o),"rule","rangeValues",s.range)}}for(const s of o.ranges){const i=t(s);switch(i.changeType){case"REMOVE":let 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){if(t)this.loopThroughRangesOfSheet(t,e);else for(const t of Object.keys(this.cfRules))this.loopThroughRangesOfSheet(t,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(let t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map((e=>this.mapToConditionalFormatInternal(t.id,e)))}export(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map((e=>this.mapToConditionalFormat(t.id,e))))}exportForExcel(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map((e=>this.mapToConditionalFormat(t.id,e,{useBoundedReference:!0}))))}getConditionalFormats(e){return this.cfRules[e]?.map((t=>this.mapToConditionalFormat(e,t)))||[]}getRulesSelection(e,t){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(let i of this.cfRules[e])for(let e of i.ranges)ls(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(Yo));const a=wo(r,s);return wo([...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(2,["Between","NotBetween"]),this.checkOperatorArgsNumber(1,["BeginsWith","ContainsText","EndsWith","GreaterThan","GreaterThanOrEqual","LessThan","LessThanOrEqual","NotContains","Equal","NotEqual"]),this.checkOperatorArgsNumber(0,["IsEmpty","IsNotEmpty"]),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,t){if(e>2)throw new Error("Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.");return o=>{if(t.includes(o.operator)){const t=[],s=e=>void 0===e||""===e;return e>=1&&s(o.values[0])&&t.push("FirstArgMissing"),e>=2&&s(o.values[1])&&t.push("SecondArgMissing"),t.length?t:"Success"}return"Success"}}checkNaN(e,t){if(["number","percentage","percentile"].includes(e.type)&&(""===e.value||isNaN(e.value)))switch(t){case"min":return"MinNaN";case"max":return"MaxNaN";case"mid":return"MidNaN";case"upperInflectionPoint":return"ValueUpperInflectionNaN";case"lowerInflectionPoint":return"ValueLowerInflectionNaN"}return"Success"}checkFormulaCompilation(e,t){if("formula"!==e.type)return"Success";if(uS(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&&YM(t)>=YM(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&&YM(t)>=YM(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&&YM(t)>=YM(o)?"MinBiggerThanMid":"Success"}checkCFValues(e){for(const t of e.values){if(!t.startsWith("="))continue;if(uS(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 qM{static getters=["getFigures","getFigure","getFigureSheetId"];figures={};insertionOrders=[];allowDispatch(e){switch(e.type){case"CREATE_FIGURE":return this.checkFigureDuplicate(e.figure.id);case"UPDATE_FIGURE":case"DELETE_FIGURE":return this.checkFigureExists(e.sheetId,e.id);default:return"Success"}}beforeHandle(e){if("DELETE_SHEET"===e.type)this.getters.getFigures(e.sheetId).forEach((t=>{this.dispatch("DELETE_FIGURE",{id: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":this.addFigure(e.figure,e.sheetId);break;case"UPDATE_FIGURE":const{type:t,sheetId:o,...s}=e,i=s;this.updateFigure(o,i);break;case"DELETE_FIGURE":this.removeFigure(e.id,e.sheetId);break;case"REMOVE_COLUMNS_ROWS":this.onRowColDelete(e.sheetId,e.dimension)}}onRowColDelete(e,t){"ROW"===t?this.onRowDeletion(e):this.onColDeletion(e)}onRowDeletion(e){const t=this.getters.getNumberRows(e);let o=0;for(let s=0;s<t;s++)o+=this.getters.getUserRowSize(e,s)||se;const s=this.getters.getFigures(e);for(const t of s){const s=Math.min(t.y,o-t.height);s!==t.y&&this.dispatch("UPDATE_FIGURE",{sheetId:e,id:t.id,y:s})}}onColDeletion(e){const t=this.getters.getNumberCols(e);let o=0;for(let s=0;s<t;s++)o+=this.getters.getColSize(e,s);const s=this.getters.getFigures(e);for(const t of s){const s=Math.min(t.x,o-t.width);s!==t.x&&this.dispatch("UPDATE_FIGURE",{sheetId:e,id:t.id,x:s})}}updateFigure(e,t){if("id"in t)for(const[o,s]of Object.entries(t))switch(o){case"x":case"y":void 0!==s&&this.history.update("figures",e,t.id,o,Math.max(s,0));break;case"width":case"height":void 0!==s&&this.history.update("figures",e,t.id,o,s)}}addFigure(e,t){this.history.update("figures",t,e.id,e),this.history.update("insertionOrders",this.insertionOrders.length,e.id)}deleteSheet(e){this.history.update("insertionOrders",this.insertionOrders.filter((t=>!this.figures[e]?.[t]))),this.history.update("figures",e,void 0)}removeFigure(e,t){this.history.update("insertionOrders",this.insertionOrders.filter((t=>t!==e))),this.history.update("figures",t,e,void 0)}checkFigureExists(e,t){return void 0===this.figures[e]?.[t]?"FigureDoesNotExist":"Success"}checkFigureDuplicate(e){return Object.values(this.figures).find((t=>t?.[e]))?"DuplicatedFigureId":"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(let 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){this.export(e)}}).add("chart",class extends qM{static getters=["isChartDefined","getChartDefinition","getChartType","getChartIds","getChart","getContextCreationChart"];charts={};createChart=bR(this.getters);validateChartDefinition=e=>yR(this,e.definition);adaptRanges(e){for(const[t,o]of Object.entries(this.charts))this.history.update("charts",t,o?.updateRanges(e))}allowDispatch(e){switch(e.type){case"CREATE_CHART":return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartDuplicate));case"UPDATE_CHART":return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartExists));default:return"Success"}}handle(e){switch(e.type){case"CREATE_CHART":this.addFigure(e.id,e.sheetId,e.position,e.size),this.addChart(e.id,e.definition);break;case"UPDATE_CHART":this.addChart(e.id,e.definition);break;case"DUPLICATE_SHEET":{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",{id:s,position:{x:o.x,y:o.y},size:{width:o.width,height:o.height},definition:i.getDefinition(),sheetId:e.sheetIdTo})}break}case"DELETE_FIGURE":this.history.update("charts",e.id,void 0);break;case"DELETE_SHEET":for(let t of this.getChartIds(e.sheetId))this.history.update("charts",t,void 0)}}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(let t of e.sheets)if(t.figures)for(let 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(let t of e.sheets){const e=this.getters.getFigures(t.id),o=[];for(let 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={x:0,y:0},s={width:536,height:335}){if(this.getters.getFigure(t,e))return;const i={id:e,x:o.x,y:o.y,width:s.width,height:s.height,tag:"chart"};this.dispatch("CREATE_FIGURE",{sheetId:t,figure:i})}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.id)?"DuplicatedChartId":"Success"}checkChartExists(e){return this.getters.getFigureSheetId(e.id)?"Success":"ChartDoesNotExist"}}).add("image",class extends qM{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.addImage(e.figureId,e.sheetId,e.position,e.size),this.history.update("images",e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case"DUPLICATE_SHEET":{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,position:{x:o.x,y:o.y},size:t,definition:Be(i)})}}break}case"DELETE_FIGURE":this.history.update("images",e.sheetId,e.id,void 0);break;case"DELETE_SHEET":this.history.update("images",e.sheetId,void 0)}}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}addImage(e,t,o,s){const i={id:e,x:o.x,y:o.y,width:s.width,height:s.height,tag:"image"};this.dispatch("CREATE_FIGURE",{sheetId:t,figure:i})}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:Be(e)})}t.images=[...t.images,...o]}}getAllImages(){const e=[];for(const t in this.images)e.push(...Object.values(this.images[t]||{}).filter(at));return e}}).add("pivot_core",class extends qM{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.checkDuplicatedMeasureIds(e.pivot);case"UPDATE_PIVOT":return e.pivotId in this.pivots?mt(e.pivot,this.pivots[e.pivotId]?.definition)?"NoChanges":""===e.pivot.name?"EmptyName":this.checkDuplicatedMeasureIds(e.pivot):"PivotIdNotFound";case"RENAME_PIVOT":if(!(e.pivotId in this.pivots))return"PivotIdNotFound";if(""===e.name)return"EmptyName";break;case"REMOVE_PIVOT":case"DUPLICATE_PIVOT":case"INSERT_PIVOT":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 sF(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=Be(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",Be(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:Be(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:Ql(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,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,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=uS(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})}}}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||ql(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 qM{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=QM(this.getters.getRangeFromZone(s,i),e),r=n&&{sheetId:n.sheetId,zone:n.zone};this.dispatch("UPDATE_PIVOT",{pivotId:t,pivot:{...o,dataSet:r}})}}}}).add("tableStyle",class extends qM{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(!bw[e.templateName])return"InvalidTableStyle";try{zt(e.primaryColor)}catch(e){return"InvalidTableStyle"}}return"Success"}handle(e){switch(e.type){case"CREATE_TABLE_STYLE":const t=Sw(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:tw.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 Nt(Mo("Custom Table Style"),Object.values(this.styles).map((e=>e.displayName)),{compute:(e,t)=>`${e} ${t}`,start:2})}isTableStyleEditable(e){return!vw[e]}import(e){for(const e in vw)this.styles[e]=vw[e];for(const t in e.customTableStyles){const o=e.customTableStyles[t];this.styles[t]=Sw(o.displayName,o.templateName,o.primaryColor)}}export(e){const t={};for(const e in this.styles)vw[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}}),SN=(new n).add("ui_sheet",class extends zP{static getters=["doesCellHaveGridIcon","getCellWidth","getCellIconSrc","getTextWidth","getCellText","getCellMultiLineText","getContiguousZone"];ctx=document.createElement("canvas").getContext("2d");allowDispatch(e){return this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e)}handle(e){switch(e.type){case"AUTORESIZE_COLUMNS":for(let t of e.cols){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.dispatch("RESIZE_COLUMNS_ROWS",{elements:e.rows,dimension:"ROW",size:null,sheetId:e.sheetId})}}getCellWidth(e){const t=this.getters.getCellComputedStyle(e);let o=0;const s=this.getters.getEvaluatedCell(e).formattedValue;if(s){const e=sa(this.ctx,s,t,void 0);o+=Math.max(...e.map((e=>Yr(this.ctx,e,t))))}if(this.getters.getCellIconSrc(e)&&(o+=function(e){return ta(e)+8}(t)),this.getters.doesCellHaveGridIcon(e)&&(o+=20),0===o)return 0;if(o+=2*re,"wrap"===t.wrapping){const t=this.getters.getColSize(this.getters.getActiveSheetId(),e.col);return Math.min(t,o)}return o}getCellIconSrc(e){const t=yy.getAll();for(const o of t){const t=o(this.getters,e);if(t)return t}}getTextWidth(e,t){return Yr(this.ctx,e,t)}getCellText(e,t){const o=this.getters.getCell(e),s=this.getters.getLocale();if(t?.showFormula&&o?.isFormula)return Na(o.content,s);if(t?.showFormula&&!o?.content)return"";{const i=this.getters.getEvaluatedCell(e),n=t?.availableWidth?{availableWidth:t.availableWidth,measureText:e=>Yr(this.ctx,e,o?.style||{})}:void 0;return Qn(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 sa(this.ctx,s,o,t.wrapText?t.maxWidth:void 0)}doesCellHaveGridIcon(e){const t=this.getters.isFilterHeader(e),o=!this.getters.isReadonly()&&this.getters.cellHasListDataValidationIcon(e);return t||o}getContiguousZone(e,t){const o=t=>{for(const o of Ze(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 Ze(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);rs(i,e)||(s=!0,i=e)}while(s);return i}isCellEmpty(e){const t=this.getters.getMainCellPosition(e);return this.getters.getEvaluatedCell(t).type===ri.empty}getColMaxWidth(e,t){const o=gs(this.getters.getColsZone(e,t,t)).map((t=>this.getCellWidth({sheetId:e,...t})));return Math.max(0,Dt(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"}}).add("ui_options",class extends zP{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 zP{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:qe(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=-1===e.row?this.lastCellSelected.row:qe(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();break;case"AUTOFILL_CELL":this.autoFillMerge(e.originCol,e.originRow,e.col,e.row);const t=this.getters.getActiveSheetId();this.dispatch("UPDATE_CELL",{sheetId:t,col:e.col,row:e.row,style:e.style||null,content:e.content||"",format:e.format||""}),this.dispatch("SET_BORDER",{sheetId:t,col:e.col,row:e.row,border:e.border}),this.autofillCF(e.originCol,e.originRow,e.col,e.row),this.autofillDV(e.originCol,e.originRow,e.col,e.row)}}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;switch(this.direction){case"down":for(let s=t.left;s<=t.right;s++){const i=[];for(let e=t.top;e<=t.bottom;e++)i.push(Co(s,e));const n=this.createGenerator(i);for(let t=o.top;t<=o.bottom;t++)this.computeNewCell(n,s,t,e)}break;case"up":for(let s=t.left;s<=t.right;s++){const i=[];for(let e=t.bottom;e>=t.top;e--)i.push(Co(s,e));const n=this.createGenerator(i);for(let t=o.bottom;t>=o.top;t--)this.computeNewCell(n,s,t,e)}break;case"left":for(let s=t.top;s<=t.bottom;s++){const i=[];for(let e=t.right;e>=t.left;e--)i.push(Co(e,s));const n=this.createGenerator(i);for(let t=o.right;t>=o.left;t--)this.computeNewCell(n,t,s,e)}break;case"right":for(let s=t.top;s<=t.bottom;s++){const i=[];for(let e=t.left;e<=t.right;e++)i.push(Co(e,s));const n=this.createGenerator(i);for(let t=o.left;t<=o.right;t++)this.computeNewCell(n,t,s,e)}}e&&(this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0)}select(e,t){const o=this.getters.getSelectedZone();if(ls(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!==ri.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!==ri.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!==ri.empty;)s+=1,e={sheetId:t,col:o+1,row:s}}return s-1}computeNewCell(e,t,o,s){const{cellData:i,tooltip:n,origin:r}=e.next(),{content:a,style:l,border:c,format:h}=i;this.tooltip=n,s&&this.dispatch("AUTOFILL_CELL",{originCol:r.col,originRow:r.row,col:t,row:o,content:a,style:l,border:c,format:h})}getRule(e,t){const o=TS.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((o=>o.condition(e,t)));return o&&o.generateRule(e,t)}createGenerator(e){const t=[],o=[],s=this.getters.getActiveSheetId();for(let t of e){const{col:e,row:i}=yo(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(let 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 $P(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,o,s){const i=this.getters.getActiveSheetId(),n={sheetId:i,col:o,row:s},r={sheetId:i,col:e,row:t};if(this.getters.isInMerge(n)&&!this.getters.isInMerge(r)){const e=this.getters.getMerge(n);e&&this.dispatch("REMOVE_MERGE",{sheetId:i,target:[e]})}const a=this.getters.getMerge(r);a?.left===e&&a?.top===t&&this.dispatch("ADD_MERGE",{sheetId:i,target:[{top:s,bottom:s+a.bottom-a.top,left:o,right:o+a.right-a.left}]})}autofillCF(e,t,o,s){const i=this.getters.getActiveSheetId(),n=this.getters.getRulesByCell(i,e,t);for(const e of n){const t=this.getters.getAdaptedCfRanges(i,e,[vs({col:o,row:s})],[]);t&&this.dispatch("ADD_CONDITIONAL_FORMAT",{cf:Be(e),ranges:t,sheetId:i})}}autofillDV(e,t,o,s){const i=this.getters.getActiveSheetId(),n={sheetId:i,col:e,row:t},r=this.getters.getValidationRuleForCell(n);if(!r)return;const a=r.ranges.map((e=>e.zone)),l=wo(a.concat(vs({col:o,row:s})),[]);this.dispatch("ADD_DATA_VALIDATION_RULE",{rule:r,ranges:l.map((e=>this.getters.getRangeDataFromZone(i,e))),sheetId:i})}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 zP{allowDispatch(e){return"SORT_CELLS"===e.type?ls(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 gs(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=>as(e,t))),s=hs(o[0]);let[i,n]=[s.numberOfCols,s.numberOfRows];return o.every((e=>{let[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 gs(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]===ri.empty&&(o=o.slice(1)),!o.some((e=>e[0]===ri.empty))&&!!o.some((e=>e[1]!==ri.empty&&e[0]!==e[1]))}sortZone(e,t,o,s,i){const[n,r]=this.mainCellsSteps(e,o);let a=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,l=Object.assign({},o),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===ri.empty?{...e,type:ri.number,value:0}:e)):s).sort(_p(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++){let{col:o,row:s,sheetId:i}=c[e][d[t]];const a=this.getters.getCell({sheetId:i,col:o,row:s});let 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=Ze(t.left,t.right+1,o),r=Ze(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 zP{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}=ls(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)||ds(is(n,t))?[{position:{col:s,row:i},zone:n}]:this.sumDimensions(e,is(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=Ze(o,-1,-1),n=Dt(i.filter((e=>s[e]&&!s[e].isAutoSummable))),r=je(i.filter((e=>this.isNumber(s[e]))))[0]||[];return Dt(r)<n?1/0:Ot(r)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===ri.number&&!(e.format&&ar(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 ds(t)?(o.add(1===hs(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)},gs(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)},gs(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 zP{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 wo(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=wo(s.map(vs));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:wo(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 wo(t))for(const t of gs(i)){const i=this.getCellNumberFormat({sheetId:e,...t});if(void 0!==i){const e=wr(i,o);s[e]=s[e]||[],s[e].push(t)}}for(const t in s){const o=wo(s[t].map((e=>vs(e))));this.setContextualFormat(e,o,t)}}getCellNumberFormat(e){for(const t of[e]){const e=this.getters.getEvaluatedCell(t);if(!(e.type!==ri.number||e.format&&ar(e.format)))return e.format||hr(e.value)}}}).add("insert_pivot",class extends zP{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===ys(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:Mo("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:Mo("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.getTableStructure().export(),"dynamic")}duplicatePivotInNewSheet(e,t,o){this.dispatch("DUPLICATE_PIVOT",{pivotId:e,newPivotId:t,duplicatedPivotName:Mo("%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(Mo("%(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.getTableStructure().export(),"dynamic")}}getPivotDuplicateSheetName(e){const t=this.getters.getSheetIds().map((e=>this.getters.getSheetName(e)));return Nt(Ge(e),t)}insertPivotWithTable(e,t,o,s,i,n){const{cols:r,rows:a,measures:l,fieldsType:c}=i,h=new sF(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:{...ke,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,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,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:Ql(n,t)});const a=this.getters.getCoreTable({sheetId:e,col:t,row:o});if("dynamic"===a?.type){const s=vs({col:t,row:o}),n=this.getters.getRangeDataFromZone(e,i);this.dispatch("UPDATE_TABLE",{sheetId:e,zone:s,newTableRange:n,tableType:"static"})}}}).add("split_to_columns",class extends zP{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===ri.text){const e=this.getAutoSeparatorForString(t.value);if(e)return e}return" "}getAutoSeparatorForString(e){const t=[Pe,";",","," ","."];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:Oa(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 Ze(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 Ze(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 Ze(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,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,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 zP{static getters=["getClientsToDisplay","getClient","getConnectedClients","isFullySynchronized"];static layers=["Selection"];availableColors=new go(12);colors={};session;constructor(e){super(e),this.session=e.session}isPositionValid(e){return e.row<this.getters.getNumberRows(e.sheetId)&&e.col<this.getters.getNumberCols(e.sheetId)}getClient(){return this.session.getClient()}getConnectedClients(){return this.session.getConnectedClients()}isFullySynchronized(){return this.session.isFullySynchronized()}getClientsToDisplay(){try{this.getters.getClient()}catch(e){if(e instanceof tN)return[];throw e}const e=this.getters.getActiveSheetId(),t=[];for(const o of this.getters.getConnectedClients())if(o.id!==this.getters.getClient().id&&o.position&&o.position.sheetId===e&&this.isPositionValid(o.position)){const e=o.position;this.colors[o.id]||(this.colors[o.id]=this.availableColors.next());const s=this.colors[o.id];t.push({...o,position:e,color:s})}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 zP{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=fN(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)&&(mi(t.rootCommand)?gN.contains(t.rootCommand.type):pN.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 zP{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===hs(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 cc(this.getters,this.dispatch),l=a.copy(ca(o,r));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 Ze(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:Mo("%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=wo(this.getters.getSelectedZones()),t=this.getters.getActiveSheetId();let o=0;for(const{col:s,row:i}of e.map(gs).flat()){const e=this.getters.getCell({col:s,row:i,sheetId:t});if(!e)continue;const n=Tt(e.content);n!==e.content&&(o+=1,this.dispatch("UPDATE_CELL",{sheetId:t,col:s,row:i,content:n}))}const s=o?Mo("Trimmed whitespace from %s cells.",o):Mo("No selected cells had whitespace trimmed.");this.ui.notifyUI({type:"info",text:s,sticky:!1})}}).add("table_autofill",class extends zP{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&&ls(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!==ri.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 zP{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 zP{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 Br(t)){const t=this.getters.getCell(e),o=this.getters.getEvaluatedCell(e);if(t?.content)if(t?.content&&o.type===ri.empty){let o;if(t.content.startsWith("=")){const s=this.getters.evaluateFormula(e.sheetId,t.content);o=(wi(s)?s[0][0]:s)?.toString()}else o=t.content;o&&Xe(o)||this.dispatch("UPDATE_CELL",{...e,content:"FALSE"})}else o.type!==ri.boolean&&this.dispatch("UPDATE_CELL",{...e,content:"FALSE"});else this.dispatch("UPDATE_CELL",{...e,content:"FALSE"})}}}}).add("geo_features",class extends zP{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")}}),yN=(new n).add("selection",class extends zP{static layers=["Selection"];static getters=["getActiveSheet","getActiveSheetId","getActiveCell","getActiveCols","getActiveRows","getCurrentStyle","getSelectedZones","getSelectedZone","getSelectedCells","getSelectedFigureId","getSelection","getActivePosition","getSheetPosition","isSingleColSelected","getElementsFromSelection","tryGetActiveSheetId","isGridSelectionActive"];gridSelection={anchor:{cell:{col:0,row:0},zone:{top:0,left:0,bottom:0,right:0}},zones:[{top:0,left:0,bottom:0,right:0}]};selectedFigureId=null;sheetsData={};moveClient;activeSheet=null;constructor(e){super(e),this.moveClient=e.moveClient}allowDispatch(e){switch(e.type){case"ACTIVATE_SHEET":try{if(!this.getters.getSheet(e.sheetIdTo).isVisible)return"SheetIsHidden";break}catch(e){return"InvalidSheetId"}case"MOVE_COLUMNS_ROWS":return this.isMoveElementAllowed(e)}return"Success"}handleEvent(e){const t=e.anchor;let o=[];switch(e.mode){case"overrideSelection":o=[t.zone];break;case"updateAnchor":o=[...this.gridSelection.zones];const s=o.findIndex((t=>rs(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,Be(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.id&&(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.id;break;case"ACTIVATE_NEXT_SHEET":this.activateNextSheet("right");break;case"ACTIVATE_PREVIOUS_SHEET":this.activateNextSheet("left");break;case"HIDE_SHEET":e.sheetId===this.getActiveSheetId()&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e.sheetId,sheetIdTo:this.getters.getVisibleSheetIds()[0]});break;case"UNDO":case"REDO":case"DELETE_SHEET":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:Be(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,Be(this.gridSelection.anchor))}isGridSelectionActive(){return this.selection.isListening(this)}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}tryGetActiveSheetId(){return this.activeSheet?.id}getActiveCell(){return this.getters.getEvaluatedCell(this.getActivePosition())}getActiveCols(){const e=new Set;for(let 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(let 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 Be(this.gridSelection.zones)}getSelectedZone(){return Be(this.gridSelection.anchor.zone)}getSelection(){return Be(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:Be(this.gridSelection)},t in this.sheetsData)Object.assign(this,this.sheetsData[t]),this.selection.resetDefaultAnchor(this,Be(this.gridSelection.anchor));else{const{col:e,row:o}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(e,o)}}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=os(o,"left",[...e.elements]);let i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=os(i,"left",[...e.elements]);const n={cell:{col:i.left,row:i.top},zone:s},r=this.gridSelection.zones.map((t=>os(t,"left",[...e.elements])));this.setSelectionMixin(n,r)}onRowsRemoved(e){const{cell:t,zone:o}=this.gridSelection.anchor,s=os(o,"top",[...e.elements]);let i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=os(i,"top",[...e.elements]);const n={cell:{col:i.left,row:i.top},zone:s},r=this.gridSelection.zones.map((t=>os(t,"top",[...e.elements])));this.setSelectionMixin(n,r)}onAddElements(e){const t="COL"===e.dimension?"left":"top",o=ts(this.gridSelection.anchor.zone,t,e.base,e.position,e.quantity),s=this.gridSelection.zones.map((o=>ts(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;this.dispatch("ADD_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,base:e.base,quantity:t,position:e.position});const o="COL"===e.dimension,s=e.elements[0],i=e.elements[t-1],n=e.base<s,r=n&&o?t:0,a=n&&!o?t:0,l=[{left:o?s+r:0,right:o?i+r:this.getters.getNumberCols(e.sheetId)-1,top:o?0:s+a,bottom:o?this.getters.getNumberRows(e.sheetId)-1:i+a}],c=this.getActiveSheetId(),h=new cc(this.getters,this.dispatch),d=h.copy(ca(c,l));if(!d)return;const u=n?e.base:e.base+1,g=[{left:o?u:0,right:o?u+t-1:this.getters.getNumberCols(e.sheetId)-1,top:o?0:u,bottom:o?this.getters.getNumberRows(e.sheetId)-1:u+t-1}];h.paste({zones:g,sheetId:c},d,{isCutOperation:!0});const p=g[0],m=p.left,f=p.top;this.setSelectionMixin({zone:p,cell:{col:m,row:f}},[p]);const v=n?e.elements.map((e=>e+t)):e.elements;let b=n?e.base:e.base+1;const S={};for(const t of v){const o=this.getters.getHeaderSize(e.sheetId,e.dimension,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,elements:v})}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":"Success"}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:qe(e.left,0,o),right:qe(e.right,0,o),top:qe(e.top,0,s),bottom:qe(e.bottom,0,s)}))),anchor:{cell:{col:qe(t.anchor.cell.col,0,o),row:qe(t.anchor.cell.row,0,s)},zone:{left:qe(t.anchor.zone.left,0,o),right:qe(t.anchor.zone.right,0,o),top:qe(t.anchor.zone.top,0,s),bottom:qe(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):vs(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 zP{static getters=["getFilterHiddenValues","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]=Be(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)}getFilterHiddenValues(e){const t=this.getters.getFilterId(e),o=e.sheetId;return t&&this.filterValues[o]&&this.filterValues[o][t]||[]}isFilterActive(e){const t=this.getters.getFilterId(e),o=e.sheetId;return Boolean(t&&this.filterValues[o]?.[t]?.length)}getFirstTableInSelection(){const e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZones();return this.getters.getTablesOverlappingZones(e,t)[0]}updateFilter({col:e,row:t,hiddenValues: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(let s of t){if(o.has(s.rangeWithHeaders.zone.top)||this.getters.isRowHiddenByUser(e,s.rangeWithHeaders.zone.top))continue;const t=this.filterValues[e]?.[s.id]?.map(ia),i=s.filteredRange?.zone;if(t&&i)for(let n=i.top;n<=i.bottom;n++){const i=this.getCellValueAsString(e,s.col,n);t.includes(i)&&o.add(n)}}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=Xo(o.range),i=[],n=[];for(const o of Ze(0,hs(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?gs(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=Co(r.col,r.row);t.cells[u]=d,t.cellValues[u]=d}o.filters=i}}}getUniqueColNameForExcel(e,t,o){return t||(t=`Column${e}`),Nt(t,o,{compute:(e,o)=>t+String(o),start:2})}}).add("header_visibility_ui",class extends zP{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 Ze(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 zP{static getters=["getCellComputedBorder","getCellComputedStyle"];styles={};borders={};handle(e){if(li.has(e.type)||"UPDATE_CELL"===e.type||"SET_FORMATTING"===e.type||"EVALUATE_CELLS"===e.type)return this.styles={},void(this.borders={});iN(e)?"sheetId"in e?(delete this.styles[e.sheetId],delete this.borders[e.sheetId]):(this.styles={},this.borders={}):di.has(e.type)?this.styles={}:ui.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={...bt(this.getters.getCellTableStyle(e)),...bt(t?.style),...bt(o)};return this.getters.getEvaluatedCell(e).link&&!s.textColor&&(s.textColor=b),s}}).add("table_computed_style",class extends zP{static getters=["getCellTableStyle","getCellTableBorder"];tableStyles={};handle(e){li.has(e.type)||"UPDATE_CELL"===e.type&&"content"in e||"EVALUATE_CELLS"===e.type?this.tableStyles={}:iN(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=DF(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 zP{static getters=["getColDimensions","getRowDimensions","getColRowOffset"];headerPositions={};isDirty=!0;handle(e){switch(li.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]=Be(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 zP{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"];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}=fs(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(li.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":this.sheetsWithDirtyViewports.add(e.sheetId);break;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":{const t="sheetId"in e?e.sheetId:this.getters.getActiveSheetId();this.sheetsWithDirtyViewports.add(t);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"UNFREEZE_ROWS":case"UNFREEZE_COLUMNS":case"FREEZE_COLUMNS":case"FREEZE_ROWS":case"UNFREEZE_COLUMNS_ROWS":this.resetViewports(this.getters.getActiveSheetId());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}}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=>Ze(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=>Ze(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);let{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+1),maxOffsetY:Math.max(0,o-s.viewportHeight+1)}}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)),r=i.findIndex((e=>o<=e)),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=kr(e-a),i=1):e<l&&o>=l&&c>0?(s=!0,n=kr(l-e),i=-1):r&&t<l&&e>l&&(s=!0,n=kr(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=kr(e-a),i=1):e<l&&o>=l&&c>0?(s=!0,n=kr(l-e),i=-1):r&&t<l&&e>l&&(s=!0,n=kr(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}}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 o={left:t,right:t,top:0,bottom:this.getters.getNumberRows(e)-1},{x:s,width:i}=this.getVisibleRect(o),n=s-this.gridOffsetX;return{start:n,size:i,end:n+i}}getRowDimensionsInViewport(e,t){const o={left:0,right:this.getters.getNumberCols(e)-1,top:t,bottom:t},{y:s,height:i}=this.getVisibleRect(o),n=s-this.gridOffsetY;return{start:n,size:i,end:n+i}}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(at)}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(qe(e,0,s),qe(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(qe(e,0,s),qe(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 vN(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 vN(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 vN(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 vN(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)}}getVisibleFigures(){const e=this.getters.getActiveSheetId(),t=[],o=this.getters.getFigures(e),{scrollX:s,scrollY:i}=this.getActiveSheetScrollInfo(),{x:n,y:r}=this.getters.getMainViewportCoordinates(),{width:a,height:l}=this.getters.getSheetViewDimensionWithHeaders();for(const e of o)e.x>=n&&(e.x+e.width<=n+s||e.x>=a+s+n)||e.y>=r&&(e.y+e.height<=r+i||e.y>=l+i+r)||t.push(e);return t}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 zP{static layers=["Clipboard"];static getters=["getClipboardContent","getClipboardId","getClipboardTextContent","isCutOperation"];status="invisible";originSheetId;copiedData;_isCutOperation=!1;clipboardId=(new la).uuidv4();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);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);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.copiedData=this.copy(t),this._isCutOperation="CUT"===e.type;break;case"PASTE_FROM_OS_CLIPBOARD":{this._isCutOperation=!1,this.copiedData=e.clipboardContent.data||this.convertTextToClipboardData(e.clipboardContent.text??"");const t=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:t,selectTarget:!0,isCutOperation:!1}),this.status="invisible";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(!Ko(t[0])){this.dispatch("CLEAR_CELLS",{target:[e.zone],sheetId:this.getters.getActiveSheetId()});break}const s=this.copy(t);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);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(let t of e.elements){if(this.isColRowDirtyingClipboard(t,e.dimension)){this.copiedData=void 0;break}}this.status="invisible";break;case"REPEAT_PASTE":this.paste(e.target,this.copiedData,{isCutOperation:!1,pasteOption:e.pasteOption,selectTarget:!0});break;case"DELETE_SHEET":if(!this._isCutOperation)return;this.originSheetId===e.sheetId&&(this.copiedData=void 0,this.status="invisible");break;default:mi(e)&&(this.status="invisible")}}convertTextToClipboardData(e){const t=this.selectClipboardHandlers({figureId:!0}).concat(this.selectClipboardHandlers({}));let 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?gc.figureHandlers:gc.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(let s of o){if("COL"===t&&e<=s.right)return!0;if("ROW"===t&&e<=s.bottom)return!0}return!1}copy(e){let t={};const o=this.getClipboardData(e);for(const{handlerName:e,handler:s}of this.selectClipboardHandlers(o)){const i=s.copy(o);t[e]=i;const n=["sheetId","cells","zones","figureId"];for(const e of n)i&&e in i&&(t[e]=i[e])}return t}paste(e,t,o){if(!t)return;let s,i=[];const n=this.getters.getActiveSheetId();let r={sheetId:n,zones:e};const a=this.selectClipboardHandlers(t);for(const{handlerName:l,handler:c}of a){const a=t[l];if(!a)continue;const h=c.getPasteTarget(n,e,a,o);h.figureId&&(r.figureId=h.figureId);for(const e of h.zones)i.push(e),s=void 0!==s?is(s,e):e}if(void 0!==s&&this.addMissingDimensions(this.getters.getActiveSheetId(),s.right-s.left+1,s.bottom-s.top+1,s.left,s.top),a.forEach((({handlerName:e,handler:s})=>{const i=t[e];i&&s.paste(r,i,o)})),!o?.selectTarget)return;const l=e[0],c=l.left,h=l.top;this.selection.getBackToDefault(),this.selection.selectZone({cell:{col:c,row:h},zone:is(...i)},{scrollIntoView:!1})}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,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,quantity:r,position:"after"})}getClipboardTextContent(){return this.getPlainTextContent()}getClipboardId(){return this.clipboardId}getClipboardContent(){return{[ai.PlainText]:this.getPlainTextContent(),[ai.Html]:this.getHTMLContent()}}getSheetData(){const e={version:tE,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"}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="${Lc(kc(this.getters.getCellComputedStyle(t.position)))}">`+Iw(this.getters.getCellText(t.position))+"</td>"}o+="</tr>"}o+="</table>",e=o}}else e="\t";return`<div data-osheet-clipboard='${Iw(JSON.stringify(this.getSheetData()))}'>${e}</div>`}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();return o?{figureId:o,sheetId:t}:ca(t,e)}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)}}}),CN=(new n).add("evaluation",class extends eP{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 FP(e.custom,this.getters)}beforeHandle(e){(li.has(e.type)||hi.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 wi(o)?ln(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 gs(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 gs(t).map((({col:t,row:o})=>this.getEvaluatedCell({sheetId:e,col:t,row:o}))).every((e=>e.type===ri.empty))}mapVisiblePositions(e,t){const{sheetId:o,zone:s}=e;return gs(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={};for(const t of this.evaluator.getEvaluatedPositions()){const o=this.evaluator.getEvaluatedCell(t),s=Co(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&&(a=fS(c.compiledFormula.tokens),r=a,!a&&""!==i)){n=(i??"").toString();const t=o.format;if(t){const o=Es(t,e.formats);l.formats[s]=o}}const h=l.cells[s];let d;d=a&&r&&c instanceof ZM?c.contentWithFixedReferences:a?h:n,l.cells[s]=d,l.cellValues[s]=i}}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 eP{static getters=["getChartRuntime","getStyleOfSingleCellChart"];charts={};createRuntimeChart=SR(this.getters);handle(e){if(li.has(e.type)||di.has(e.type)||ci.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.id]=void 0;break;case"DELETE_SHEET":for(let 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:jc(e)};if(!t)return{background:m,fontColor:jc(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||jc(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=JS(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 eP{static getters=["getConditionalIcon","getCellConditionalFormatStyle","getConditionalDataBar"];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(li.has(e.type)||di.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(let o of this.getters.getConditionalFormats(e).reverse())switch(o.rule.type){case"ColorScaleRule":for(let s of o.ranges)this.applyColorScale(e,s,o.rule,t);break;case"CellIsRule":const s=o.rule.values.map((e=>e.startsWith("=")?uS(e):void 0));for(let 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=this.rulePredicate[o.rule.type],l={sheetId:e,col:r,row:i},c=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}));a&&a(l,{...o.rule,values:c})&&(t[r]||(t[r]=[]),t[r][i]=Object.assign(t[r]?.[i]||{},o.rule.style))}}}return t}getComputedIcons(e){const t={};for(let o of this.getters.getConditionalFormats(e).reverse())if("IconSetRule"===o.rule.type)for(let s of o.ranges)this.applyIcon(e,s,o.rule,t);return t}getComputedDataBars(e){const t={};for(let o of this.getters.getConditionalFormats(e).reverse())if("DataBarRule"===o.rule.type)for(let 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===ri.number)).map((e=>e.value));switch(o.type){case"value":return"max"===s?Dt(i):Ot(i);case"number":return Number(o.value);case"percentage":const t=Ot(i);return t+(Dt(i)-t)*Number(o.value)/100;case"percentile":return ni(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!==ri.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=Dt(this.getters.getEvaluatedCellsInZone(e,i.zone).filter((e=>e.type===ri.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});!ls(i,c,l)||h.type!==ri.number||h.value<=0||(s[o]||(s[o]=[]),s[o][t]={color:Ht(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=po(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===ri.number){const e=qe(n.value,i,r);s[o]||(s[o]=[]),s[o][t]=s[o]?.[t]||{},s[o][t].fillColor=c(e)}}}rulePredicate={CellIsRule:(e,t)=>{const o=this.getters.getEvaluatedCell(e);if(o.type===ri.error)return!1;let[s,i]=t.values.map((t=>t.startsWith("=")?this.getters.evaluateFormula(e.sheetId,t)??"":Tr(t,yi)));if(wi(s)||wi(i))return!1;const n=o.value??"";switch(s=s??"",i=i??"",t.operator){case"IsEmpty":return""===n.toString().trim();case"IsNotEmpty":return""!==n.toString().trim();case"BeginsWith":return""!==s&&n.toString().startsWith(s.toString());case"EndsWith":return""!==s&&n.toString().endsWith(s.toString());case"Between":return n>=s&&n<=i;case"NotBetween":return!(n>=s&&n<=i);case"ContainsText":return n.toString().indexOf(s.toString())>-1;case"NotContains":return!n||-1===n.toString().indexOf(s.toString());case"GreaterThan":return n>s;case"GreaterThanOrEqual":return n>=s;case"LessThan":return n<s;case"LessThanOrEqual":return n<=s;case"NotEqual":return""!==s&&n!==s;case"Equal":return""===s||n===s;default:console.warn(Mo("Not implemented operator %s for kind of conditional formatting: %s",t.operator,t.type))}return!1}}}).add("row_size",class extends eP{static getters=["getRowSize","getHeaderSize"];tallestCellInRow={};ctx=document.createElement("canvas").getContext("2d");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=Be(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=It(this.tallestCellInRow[e.sheetId],e.elements);this.history.update("tallestCellInRow",e.sheetId,t);break}case"ADD_COLUMNS_ROWS":{if("COL"===e.dimension)return;const t=pt(e.position,e.base),o=Array(e.quantity).fill(void 0),s=Rt(this.tallestCellInRow[e.sheetId],o,t);this.history.update("tallestCellInRow",e.sheetId,s);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 Ze(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 gs(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??se)}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<=se)&&(!s&&i>se||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 se;const t=this.getters.getCell(e),o=this.getters.getColSize(e.sheetId,e.col);return function(e,t,o){if(!t||!t.isFormula&&!t.content)return se;const s="wrap"===t.style?.wrapping?o-2*ne:void 0,i=t.isFormula?1:sa(e,t.content,t.style,s).length;return qr(ta(t.style),i)+6}(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>se&&(i=r,s={cell:n,size:r})}return s&&s.size>se?s:void 0}}).add("data_validation_ui",class extends eP{static getters=["getDataValidationInvalidCriterionValueMessage","getInvalidDataValidationMessage","getValidationResultForCellValue","isCellValidCheckbox","isDataValidationInvalid"];validationResults={};handle(e){if(li.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}getInvalidDataValidationMessage(e){const t=this.getValidationResultForCell(e);return t.isValid?void 0:t.error}getDataValidationInvalidCriterionValueMessage(e,t){const o=vO.get(e);return t.startsWith("=")?"onlyLiterals"===o.allowedValues?Mo("The value must not be a formula"):this.isValidFormula(t)?void 0:yE.CriterionError.validFormula:"onlyFormulas"===o.allowedValues?Mo("The value must be a formula"):o.isCriterionValueValid(t)?void 0:o.criterionValueErrorString}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 LP;const s=this.getRuleErrorForCellValue(e,t,o);return s?{error:s,rule:o,isValid:!1}:LP}isValidFormula(e){return!uS(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]?.()||LP}computeSheetValidationResults(e){const t={},o=this.getters.getDataValidationRules(e).map((e=>e.ranges));for(const e of Br(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===ri.empty?LP:this.getValidationResultForCellValue(t.value,e)}))}return t}getRuleErrorForCellValue(e,t,o){const{sheetId:s}=t,i=o.criterion,n=vO.get(i.type),r=this.getCellOffsetInRule(t,o),a=this.getEvaluatedCriterionValues(s,r,i),l={...i,values:a};if(!n.isValueValid(e,l,this.getters,s))return n.getErrorString(l,this.getters,s)}getCellOffsetInRule(e,t){const o=t.ranges.find((t=>ls(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 o;const s=uS(o),i=this.getters.getTranslatedCellFormula(e,t.col,t.row,s.tokens),n=this.getters.evaluateFormula(e,i);return n&&!wi(n)?n.toString():""}))}}).add("dynamic_tables",class extends eP{static getters=["canCreateDynamicTableOnZones","doesZonesContainFilter","getFilter","getFilters","getTable","getTables","getTablesOverlappingZones","getFilterId","getFilterHeaders","isFilterHeader"];tables={};handle(e){if(li.has(e.type)||"UPDATE_CELL"===e.type&&"content"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)as(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=>ls(t,o,e.range.zone)))}getTablesOverlappingZones(e,t){return this.getTables(e).filter((e=>t.some((t=>as(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(!Cs(t))return!1;const o=is(...t),s={col:o.left,row:o.top,sheetId:e},i=this.getters.getArrayFormulaSpreadingOn(s);if(!i)return!1;if(mt(i,s)&&1===ys(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=AF(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=Xo(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=Qo(n.range.zone))}}}).add("custom_colors",class extends eP{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.id));break;case"UPDATE_CELL":case"ADD_CONDITIONAL_FORMAT":case"SET_BORDER":case"SET_ZONE_BORDERS":case"SET_FORMATTING":case"CREATE_TABLE":case"UPDATE_TABLE":this.history.update("shouldUpdateColors",!0)}}finalize(){this.shouldUpdateColors&&(this.history.update("shouldUpdateColors",!1),this.tryToAddColors(this.computeCustomColors()))}getCustomColors(){return function(e){const t=[{leadColor:Gt(255,0,0),colors:[]},{leadColor:Gt(255,128,0),colors:[]},{leadColor:Gt(128,128,0),colors:[]},{leadColor:Gt(128,255,0),colors:[]},{leadColor:Gt(0,255,0),colors:[]},{leadColor:Gt(0,255,128),colors:[]},{leadColor:Gt(0,255,255),colors:[]},{leadColor:Gt(0,127,255),colors:[]},{leadColor:Gt(0,0,255),colors:[]},{leadColor:Gt(127,0,255),colors:[]},{leadColor:Gt(128,0,128),colors:[]},{leadColor:Gt(255,0,128),colors:[]}];for(const o of e.map(jt)){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)=>Xt(e).s-Xt(t).s)))).flat().map(Zt)}(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(Ht(t.minimum.color)),o.push(t.midpoint?Ht(t.midpoint.color):void 0),o.push(Ht(t.maximum.color)))}return o.filter(at)}getChartColors(e){const t=this.getters.getChart(e);if(void 0===t)return[];return[...JSON.stringify(t.getDefinition()).matchAll(kP)].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(at):[]}tryToAddColors(e){for(const t of e){if(!$t(t))continue;const e=zt(t);t&&!Q.includes(e)&&this.history.update("customColors",e,!0)}}}).add("pivot_ui",class extends eP{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(li.has(e.type))for(const e of this.getters.getPivotIds())mF.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(BP);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 gF)gF[e].set.clear(),gF[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=ES(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=Nf(t);return this.getters.evaluateFormula(e,o)}))}}getPivotCellFromPosition(e){const t=this.getters.getCorrespondingFormulaCell(e);if(!t||!t.isFormula||0===xS(t.compiledFormula.tokens))return iF;const o=this.getters.getCellPosition(t.id),s=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(!s)return iF;const{functionName:i,args:n}=s,r=n[0];if(!r)return iF;const a=this.getters.getPivotId(r.toString());if(!a)return iF;const l=this.getPivot(a);if(!l.isValid())return iF;if("PIVOT"===i&&!t.content.replaceAll(" ","").toUpperCase().startsWith("=PIVOT"))return iF;if("PIVOT"===i){const t=Qa(n[2]),s=void 0===t||Xi(t),i=Qa(n[3]),r=void 0===i||Xi(i),a=l.getTableStructure().getPivotCells(s,r),c=e.col-o.col,h=e.row-o.row;return a[c][h]}try{if("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){return{type:"HEADER",domain:l.parseArgsToPivotDomain(n.slice(1).map((e=>({value:e}))))}}const[e,...t]=n.slice(1);return{type:"VALUE",domain:l.parseArgsToPivotDomain(t.map((e=>({value:e})))),measure:e?.toString()||""}}catch(e){return iF}}generateNewCalculatedMeasureName(e){const t=e.map((e=>e.fieldName));return Nt(Mo("Calculated measure 1"),t,{compute:(e,t)=>Mo("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=UP(mF.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}}),wN=new n;wN.add("link",{condition:(e,t)=>!!t.getEvaluatedCell(e).link,execute:(e,t,o)=>An(t.model.getters.getEvaluatedCell(e).link,t,o),sequence:5});class EN{fileStore;constructor(e){this.fileStore=e}async requestImage(){const e=await this.getImageFromUser(),t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}getImageFromUser(){return new Promise(((e,t)=>{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.src=e,s.addEventListener("load",(()=>{const e={width:s.width,height:s.height};t(e)})),s.addEventListener("error",o)}))}}const xN=[{transform:"scale(0)"},{transform:"scale(0.8)",offset:.33},{opacity:"0",transform:"scale(1)",offset:1}];Pc`
|
|
1822
|
+
`;class $M extends t.Component{static template="o-spreadsheet-TableResizer";static props={table:Object};state=t.useState({highlightZone:void 0});setup(){dO(this)}get containerStyle(){const e=this.props.table.range.zone,t={...e,left:e.right,top:e.bottom},o=this.env.model.getters.getVisibleRect(t);return 0===o.height||0===o.width?Lc({display:"none"}):Lc({top:o.y+o.height-6+"px",left:o.x+o.width-6+"px"})}onMouseDown(e){const t=this.props.table.range.zone,o={col:t.left,row:t.top};document.body.style.cursor="nwse-resize";J_(this.env,((e,t,s)=>{this.state.highlightZone={left:o.col,top:o.row,right:Math.max(e,o.col),bottom:Math.max(t,o.row)}}),(()=>{document.body.style.cursor="";const e=this.state.highlightZone;if(!e)return;const t=this.props.table.range.sheetId;this.env.model.dispatch("RESIZE_TABLE",{sheetId:t,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeDataFromZone(t,e)}),this.state.highlightZone=void 0}))}get highlights(){return this.state.highlightZone?[{zone:this.state.highlightZone,sheetId:this.props.table.range.sheetId,color:zM,noFill:!0}]:[]}}const WM={ROW:q_,COL:z_,CELL:JT,GROUP_HEADERS:XF,UNGROUP_HEADERS:KF};class GM extends t.Component{static template="o-spreadsheet-Grid";static props={exposeFocus:Function};static components={GridComposer:nM,GridOverlay:xM,GridPopover:IM,HeadersOverlay:_M,Menu:mR,Autofill:QF,ClientTag:tM,Highlight:kM,Popover:PI,VerticalScrollBar:UM,HorizontalScrollBar:VM,TableResizer:$M};HEADER_HEIGHT=ee;HEADER_WIDTH=te;menuState;gridRef;highlightStore;cellPopovers;composerFocusStore;DOMFocusableElementStore;paintFormatStore;onMouseWheel;canvasPosition;hoveredCell;sidePanel;setup(){this.highlightStore=Cc(Jb),this.menuState=t.useState({isOpen:!1,position:null,menuItems:[]}),this.gridRef=t.useRef("grid"),this.canvasPosition=MI(this.gridRef),this.hoveredCell=Cc(TI),this.composerFocusStore=Cc(Oc),this.DOMFocusableElementStore=Cc(PD),this.sidePanel=Cc(BM),this.paintFormatStore=Cc(wM),Cc(JF),t.useChildSubEnv({getPopoverContainerRect:()=>this.getGridRect()}),t.useExternalListener(document.body,"cut",this.copy.bind(this,!0)),t.useExternalListener(document.body,"copy",this.copy.bind(this,!1)),t.useExternalListener(document.body,"paste",this.paste),t.onMounted((()=>this.focusDefaultElement())),this.props.exposeFocus((()=>this.focusDefaultElement())),FM("canvas",this.env.model,(()=>this.env.model.getters.getSheetViewDimensionWithHeaders())),this.onMouseWheel=MM(((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()})),this.cellPopovers=Cc(AI),t.useEffect((()=>{this.sidePanel.isOpen||this.DOMFocusableElementStore.focusableElement?.focus()}),(()=>[this.sidePanel.isOpen]))}onCellHovered({col:e,row:t}){this.hoveredCell.hover({col:e,row:t})}get highlights(){return this.highlightStore.highlights}get gridOverlayDimensions(){return Lc({top:"26px",left:"48px",height:"calc(100% - 41px)",width:"calc(100% - 63px)"})}onClosePopover(){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.focusDefaultElement()}keyDownMapping={Enter:()=>{this.env.model.getters.getActiveCell().type===ri.empty?this.onComposerCellFocused():this.onComposerContentFocused()},Tab:()=>this.env.model.selection.moveAnchorCell("right",1),"Shift+Tab":()=>this.env.model.selection.moveAnchorCell("left",1),F2:()=>{this.env.model.getters.getActiveCell().type===ri.empty?this.onComposerCellFocused():this.onComposerContentFocused()},Delete:()=>{this.env.model.dispatch("DELETE_CONTENT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Backspace:()=>{this.env.model.dispatch("DELETE_CONTENT",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Escape:()=>{this.cellPopovers.isOpen?this.cellPopovers.close():this.menuState.isOpen?this.closeMenu():this.paintFormatStore.isActive?this.paintFormatStore.cancel():this.env.model.dispatch("CLEAN_CLIPBOARD_HIGHLIGHT")},"Ctrl+A":()=>this.env.model.selection.loopSelection(),"Ctrl+Z":()=>this.env.model.dispatch("REQUEST_UNDO"),"Ctrl+Y":()=>this.env.model.dispatch("REQUEST_REDO"),F4:()=>this.env.model.dispatch("REQUEST_REDO"),"Ctrl+B":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{bold:!this.env.model.getters.getCurrentStyle().bold}}),"Ctrl+I":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{italic:!this.env.model.getters.getCurrentStyle().italic}}),"Ctrl+U":()=>this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{underline:!this.env.model.getters.getCurrentStyle().underline}}),"Ctrl+O":()=>MR(this.env),"Alt+=":()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone(),{anchor:o}=this.env.model.getters.getSelection(),s=this.env.model.getters.getAutomaticSums(e,t,o.cell);if(this.env.model.getters.isSingleCellOrMerge(e,t)||this.env.model.getters.isEmpty(e,t)&&s.length<=1){const t=s[0]?.zone,o=t?this.env.model.getters.zoneToXC(e,s[0].zone):"",i=`=SUM(${o})`;this.onComposerCellFocused(i,{start:5,end:5+o.length})}else this.env.model.dispatch("SUM_SELECTION")},"Alt+Enter":()=>{const e=this.env.model.getters.getActiveCell();e.link&&An(e.link,this.env)},"Ctrl+Home":()=>{const e=this.env.model.getters.getActiveSheetId(),{col:t,row:o}=this.env.model.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0});this.env.model.selection.selectCell(t,o)},"Ctrl+End":()=>{const e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.findVisibleHeader(e,"COL",this.env.model.getters.getNumberCols(e)-1,0),o=this.env.model.getters.findVisibleHeader(e,"ROW",this.env.model.getters.getNumberRows(e)-1,0);this.env.model.selection.selectCell(t,o)},"Shift+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),left:0,right:this.env.model.getters.getNumberCols(e)-1},o=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:o,zone:t})},"Ctrl+ ":()=>{const e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),top:0,bottom:this.env.model.getters.getNumberRows(e)-1},o=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:o,zone:t})},"Ctrl+D":async()=>this.env.model.dispatch("COPY_PASTE_CELLS_ABOVE"),"Ctrl+R":async()=>this.env.model.dispatch("COPY_PASTE_CELLS_ON_LEFT"),"Ctrl+H":()=>this.sidePanel.open("FindAndReplace",{}),"Ctrl+F":()=>this.sidePanel.open("FindAndReplace",{}),"Ctrl+Shift+E":()=>this.setHorizontalAlign("center"),"Ctrl+Shift+L":()=>this.setHorizontalAlign("left"),"Ctrl+Shift+R":()=>this.setHorizontalAlign("right"),"Ctrl+Shift+V":()=>TR(this.env),"Ctrl+Shift+<":()=>this.clearFormatting(),"Ctrl+<":()=>this.clearFormatting(),"Ctrl+Shift+ ":()=>{this.env.model.selection.selectAll()},"Ctrl+Alt+=":()=>{const e=this.env.model.getters.getActiveCols(),t=this.env.model.getters.getActiveRows(),o=1===this.env.model.getters.getSelectedZones().length,s=e.size>0&&o,i=t.size>0&&o;s&&!i?OR(this.env):i&&!s&&DR(this.env)},"Ctrl+Alt+-":()=>{const e=[...this.env.model.getters.getActiveCols()],t=[...this.env.model.getters.getActiveRows()];e.length>0&&0===t.length?this.env.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"COL",elements:e}):t.length>0&&0===e.length&&this.env.model.dispatch("REMOVE_COLUMNS_ROWS",{sheetId:this.env.model.getters.getActiveSheetId(),dimension:"ROW",elements:t})},"Shift+PageDown":()=>{this.env.model.dispatch("ACTIVATE_NEXT_SHEET")},"Shift+PageUp":()=>{this.env.model.dispatch("ACTIVATE_PREVIOUS_SHEET")},PageDown:()=>this.env.model.dispatch("SHIFT_VIEWPORT_DOWN"),PageUp:()=>this.env.model.dispatch("SHIFT_VIEWPORT_UP"),"Ctrl+K":()=>PR(this.env),"Alt+Shift+ArrowRight":()=>this.processHeaderGroupingKey("right"),"Alt+Shift+ArrowLeft":()=>this.processHeaderGroupingKey("left"),"Alt+Shift+ArrowUp":()=>this.processHeaderGroupingKey("up"),"Alt+Shift+ArrowDown":()=>this.processHeaderGroupingKey("down")};focusDefaultElement(){this.env.model.getters.getSelectedFigureId()||"inactive"!==this.composerFocusStore.activeComposer.editionMode||this.DOMFocusableElementStore.focusableElement?.focus()}get gridEl(){if(!this.gridRef.el)throw new Error("Grid el is not defined.");return this.gridRef.el}getAutofillPosition(){const e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect(e);return{left:t.x+t.width-4,top:t.y+t.height-4}}get isAutofillVisible(){const e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect({left:e.right,right:e.right,top:e.bottom,bottom:e.bottom});return!(0===t.width||0===t.height)}onGridResized({height:e,width:t}){this.env.model.dispatch("RESIZE_SHEETVIEW",{width:t,height:e,gridOffsetX:te,gridOffsetY:ee})}moveCanvas(e,t){const{scrollX:o,scrollY:s}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:o+e,offsetY:s+t})}getClientPositionKey(e){return`${e.id}-${e.position?.sheetId}-${e.position?.col}-${e.position?.row}`}isCellHovered(e,t){return this.hoveredCell.col===e&&this.hoveredCell.row===t}getGridRect(){return{...this.canvasPosition,...this.env.model.getters.getSheetViewDimensionWithHeaders()}}onCellClicked(e,t,o){"editing"===this.composerFocusStore.activeComposer.editionMode&&this.composerFocusStore.activeComposer.stopEdition(),o.expandZone?this.env.model.selection.setAnchorCorner(e,t):o.addZone?this.env.model.selection.addCellToSelection(e,t):this.env.model.selection.selectCell(e,t);let s=e,i=t;J_(this.env,((e,t,o)=>{o.preventDefault(),(e!==s&&-1!=e||t!==i&&-1!=t)&&(s=-1===e?s:e,i=-1===t?i:t,this.env.model.selection.setAnchorCorner(s,i))}),(()=>{this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())}))}onCellDoubleClicked(e,t){const o=this.env.model.getters.getActiveSheetId();({col:e,row:t}=this.env.model.getters.getMainCellPosition({sheetId:o,col:e,row:t}));this.env.model.getters.getEvaluatedCell({sheetId:o,col:e,row:t}).type===ri.empty?this.onComposerCellFocused():this.onComposerContentFocused()}processArrows(e){e.preventDefault(),e.stopPropagation(),this.cellPopovers.isOpen&&this.cellPopovers.close(),nD(e,this.env.model.selection),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())}onKeydown(e){const t=eR(e),o=this.keyDownMapping[t];if(o)return e.preventDefault(),e.stopPropagation(),void o();e.key.startsWith("Arrow")&&this.processArrows(e)}onInputContextMenu(e){e.preventDefault();const t=this.env.model.getters.getSelectedZone(),{left:o,top:s}=t;let i="CELL";this.composerFocusStore.activeComposer.stopEdition(),this.env.model.getters.getActiveCols().has(o)?i="COL":this.env.model.getters.getActiveRows().has(s)&&(i="ROW");const{x:n,y:r,width:a}=this.env.model.getters.getVisibleRect(t),l=this.getGridRect();this.toggleContextMenu(i,l.x+n+a,l.y+r)}onCellRightClicked(e,t,{x:o,y:s}){const i=this.env.model.getters.getSelectedZones();let n="CELL";ls(e,t,i[i.length-1])?this.env.model.getters.getActiveCols().has(e)?n="COL":this.env.model.getters.getActiveRows().has(t)&&(n="ROW"):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(n,o,s)}toggleContextMenu(e,t,o){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.menuState.isOpen=!0,this.menuState.position={x:t,y:o},this.menuState.menuItems=WM[e].getMenuItems()}async copy(e,t){if(!this.gridEl.contains(document.activeElement))return;if("inactive"!==this.composerFocusStore.activeComposer.editionMode)return;e?II(this.env):this.env.model.dispatch("COPY");const o=this.env.model.getters.getClipboardContent(),s=t.clipboardData;for(const e in o)s?.setData(e,o[e]);t.preventDefault()}async paste(e){if(!this.gridEl.contains(document.activeElement))return;e.preventDefault();const t=e.clipboardData;if(!t)return;const o={content:{[ai.PlainText]:t?.getData(ai.PlainText),[ai.Html]:t?.getData(ai.Html)}},s=this.env.model.getters.getSelectedZones(),i=this.env.model.getters.isCutOperation(),n=da(o.content),r=n.data?.clipboardId;this.env.model.getters.getClipboardId()===r?dE(this.env,s):uE(this.env,s,n),i&&await this.env.clipboard.write({[ai.PlainText]:""})}clearFormatting(){this.env.model.dispatch("CLEAR_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}setHorizontalAlign(e){this.env.model.dispatch("SET_FORMATTING",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{align:e}})}closeMenu(){this.menuState.isOpen=!1,this.focusDefaultElement()}processHeaderGroupingKey(e){if(1!==this.env.model.getters.getSelectedZones().length)return;const t=this.env.model.getters.getActiveRows().size>0,o=this.env.model.getters.getActiveCols().size>0;o&&t?this.processHeaderGroupingEventOnWholeSheet(e):o?this.processHeaderGroupingEventOnHeaders(e,"COL"):t?this.processHeaderGroupingEventOnHeaders(e,"ROW"):this.processHeaderGroupingEventOnGrid(e)}processHeaderGroupingEventOnHeaders(e,t){const o=this.env.model.getters.getActiveSheetId(),s=this.env.model.getters.getSelectedZone(),i="COL"===t?s.left:s.top,n="COL"===t?s.right:s.bottom;switch(e){case"right":this.env.model.dispatch("GROUP_HEADERS",{sheetId:o,dimension:t,start:i,end:n});break;case"left":this.env.model.dispatch("UNGROUP_HEADERS",{sheetId:o,dimension:t,start:i,end:n});break;case"down":this.env.model.dispatch("UNFOLD_HEADER_GROUPS_IN_ZONE",{sheetId:o,dimension:t,zone:s});break;case"up":this.env.model.dispatch("FOLD_HEADER_GROUPS_IN_ZONE",{sheetId:o,dimension:t,zone:s})}}processHeaderGroupingEventOnWholeSheet(e){const t=this.env.model.getters.getActiveSheetId();"up"===e?(this.env.model.dispatch("FOLD_ALL_HEADER_GROUPS",{sheetId:t,dimension:"ROW"}),this.env.model.dispatch("FOLD_ALL_HEADER_GROUPS",{sheetId:t,dimension:"COL"})):"down"===e&&(this.env.model.dispatch("UNFOLD_ALL_HEADER_GROUPS",{sheetId:t,dimension:"ROW"}),this.env.model.dispatch("UNFOLD_ALL_HEADER_GROUPS",{sheetId:t,dimension:"COL"}))}processHeaderGroupingEventOnGrid(e){const t=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getSelectedZone();switch(e){case"down":this.env.model.dispatch("UNFOLD_HEADER_GROUPS_IN_ZONE",{sheetId:t,dimension:"ROW",zone:o}),this.env.model.dispatch("UNFOLD_HEADER_GROUPS_IN_ZONE",{sheetId:t,dimension:"COL",zone:o});break;case"up":this.env.model.dispatch("FOLD_HEADER_GROUPS_IN_ZONE",{sheetId:t,dimension:"ROW",zone:o}),this.env.model.dispatch("FOLD_HEADER_GROUPS_IN_ZONE",{sheetId:t,dimension:"COL",zone:o});break;case"right":{const{x:e,y:t,width:s}=this.env.model.getters.getVisibleRect(o),i=this.getGridRect();this.toggleContextMenu("GROUP_HEADERS",e+s+i.x,t+i.y);break}case"left":{if(!B_(this.env,"COL")&&!B_(this.env,"ROW"))return;const{x:e,y:t,width:s}=this.env.model.getters.getVisibleRect(o),i=this.getGridRect();this.toggleContextMenu("UNGROUP_HEADERS",e+s+i.x,t+i.y);break}}}onComposerCellFocused(e,t){this.composerFocusStore.focusActiveComposer({content:e,selection:t,focusMode:"cellFocus"})}onComposerContentFocused(){this.composerFocusStore.focusActiveComposer({focusMode:"contentFocus"})}get staticTables(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getCoreTables(e).filter(DF)}}class qM{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 ZM extends qM{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){}garbageCollectExternalResources(){}}class jM{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 YM(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 YM{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 XM(e){return""===e?NaN:Number(e)}function KM(e){return Object.entries(e).map((([e,t])=>t?JM(parseInt(e,10),t):void 0)).filter(at).map((e=>Co(e.left,e.top)+":"+Co(e.right,e.bottom)))}function JM(e,t){return{...t.zone,id:e}}class QM{getters;providers=[];constructor(e){this.getters=e}static getters=["adaptFormulaStringDependencies","copyFormulaStringForSheet","extendRange","getRangeString","getRangeFromSheetXC","createAdaptedRanges","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){switch(e.type){case"REMOVE_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",o="COL"===e.dimension?"right":"bottom",s="COL"===e.dimension?"columns":"rows";const i=[...e.elements];i.sort(((e,t)=>t-e));const n=je(i);this.executeOnAllRanges((i=>{if(i.sheetId!==e.sheetId)return{changeType:"NONE"};let r=i,a="NONE";for(let e of n){const n=Ot(e),l=Dt(e);if(i.zone[t]<=n&&n<=i.zone[o]){const e=Math.min(i.zone[o],l)-n+1;a="RESIZE",r=this.createAdaptedRange(r,s,a,-e)}else if(i.zone[t]>=n&&i.zone[o]<=l)a="REMOVE",r=i.clone({...this.getInvalidRange()});else if(i.zone[t]<=l&&i.zone[o]>=l){const e=l-i.zone[t]+1;a="RESIZE",r=this.createAdaptedRange(r,s,a,-e),r=this.createAdaptedRange(r,s,"MOVE",-(i.zone[t]-n))}else n<i.zone[t]&&(a="MOVE",r=this.createAdaptedRange(r,s,a,-(l-n+1)))}return"NONE"!==a?{changeType:a,range:r}:{changeType:"NONE"}}),e.sheetId);break}case"ADD_COLUMNS_ROWS":{let t="COL"===e.dimension?"left":"top",o="COL"===e.dimension?"right":"bottom",s="COL"===e.dimension?"columns":"rows";this.executeOnAllRanges((i=>{if(i.sheetId!==e.sheetId)return{changeType:"NONE"};if("after"===e.position){if(i.zone[t]<=e.base&&e.base<i.zone[o])return{changeType:"RESIZE",range:this.createAdaptedRange(i,s,"RESIZE",e.quantity)};if(e.base<i.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(i,s,"MOVE",e.quantity)}}else{if(i.zone[t]<e.base&&e.base<=i.zone[o])return{changeType:"RESIZE",range:this.createAdaptedRange(i,s,"RESIZE",e.quantity)};if(e.base<=i.zone[t])return{changeType:"MOVE",range:this.createAdaptedRange(i,s,"MOVE",e.quantity)}}return{changeType:"NONE"}}),e.sheetId);break}case"DELETE_SHEET":this.executeOnAllRanges((t=>{if(t.sheetId!==e.sheetId)return{changeType:"NONE"};const o=this.getters.getSheetName(e.sheetId);return{changeType:"REMOVE",range:t=t.clone({...this.getInvalidRange(),invalidSheetName:o})}}),e.sheetId);break;case"RENAME_SHEET":this.executeOnAllRanges((t=>{if(t.sheetId===e.sheetId)return{changeType:"CHANGE",range:t};if(e.name&&t.invalidSheetName===e.name){const o=void 0,s=e.sheetId;return{changeType:"CHANGE",range:t.clone({sheetId:s,invalidSheetName:o})}}return{changeType:"NONE"}}));break;case"MOVE_RANGES":{const t=e.target[0];this.executeOnAllRanges((o=>{if(o.sheetId!==e.sheetId||!cs(o.zone,t))return{changeType:"NONE"};const s=e.targetSheetId,i=e.col-t.left,n=e.row-t.top,r=this.createAdaptedRange(o,"both","MOVE",[i,n]),a=e.sheetId!==s||r.prefixSheet;return{changeType:"MOVE",range:r.clone({sheetId:s,prefixSheet:a})}}));break}}}finalize(){}verifyRangeRemoved(e){return t=>{const o=e(t);return"NONE"===o.changeType||Ko(o.range.zone)?o:{range:o.range,changeType:"REMOVE"}}}createAdaptedRange(e,t,o,s){const i=ms(e.unboundedZone,t,o,s);return e.clone({zone:i})}executeOnAllRanges(e,t){const o=this.verifyRangeRemoved(e);for(const e of this.providers)e(o,t)}addRangeProvider(e){this.providers.push(e)}createAdaptedRanges(e,t,o,s){const i=e.map((e=>Lr.fromRange(e,this.getters)));return i.map((e=>{if(!Ko(e.zone))return e;const i=e.prefixSheet?e.sheetId:s,n={...e.unboundedZone,left:e.isFullRow&&!e.unboundedZone.hasHeader?e.unboundedZone.left:e.unboundedZone.left+(e.parts[0].colFixed?0:t),right:e.isFullRow?e.unboundedZone.right:e.unboundedZone.right+((e.parts[1]||e.parts[0]).colFixed?0:t),top:e.isFullCol&&!e.unboundedZone.hasHeader?e.unboundedZone.top:e.unboundedZone.top+(e.parts[0].rowFixed?0:o),bottom:e.isFullCol?e.unboundedZone.bottom:e.unboundedZone.bottom+((e.parts[1]||e.parts[0]).rowFixed?0:o)};return e.clone({sheetId:i,zone:n}).orderZone()}))}removeRangesSheetPrefix(e,t){return t.map((t=>{const o=Lr.fromRange(t,this.getters);return o.prefixSheet&&o.sheetId===e?o.clone({prefixSheet:!1}):o}))}extendRange(e,t,o){const s=Lr.fromRange(e,this.getters),i="COL"===t?s.zone.right+o:s.zone.right,n="ROW"===t?s.zone.bottom+o:s.zone.bottom,r={left:s.zone.left,top:s.zone.top,right:s.isFullRow?void 0:i,bottom:s.isFullCol?void 0:n};return new Lr({...s,zone:r},this.getters.getSheetSize).orderZone()}getRangeFromSheetXC(e,t){if(!Bo.test(t)||!this.getters.tryGetSheet(e))return new Lr({sheetId:"",zone:{left:-1,top:-1,right:-1,bottom:-1},parts:[],invalidXc:t,prefixSheet:!1},this.getters.getSheetSize);let o,s=t,i=!1;t.includes("!")&&(({xc:s,sheetName:o}=Zo(t)),o&&(i=!0));const n=Yo(s),r=Lr.getRangeParts(s,n),a=o&&!this.getters.getSheetIdByName(o)?o:void 0,l=this.getters.getSheetIdByName(o)||e;return new Lr({prefixSheet:i,zone:n,sheetId:l,invalidSheetName:a,parts:r},this.getters.getSheetSize).orderZone()}getRangeString(e,t,o={useBoundedReference:!1,useFixedReference:!1}){if(!e)return Ri.InvalidReference;if(e.invalidXc)return e.invalidXc;if(!this.getters.tryGetSheet(e.sheetId))return Ri.InvalidReference;if(e.zone.bottom-e.zone.top<0||e.zone.right-e.zone.left<0)return Ri.InvalidReference;if(e.zone.left<0||e.zone.top<0)return Ri.InvalidReference;const s=Lr.fromRange(e,this.getters);let i=s.sheetId!==t||s.invalidSheetName||s.prefixSheet,n="";if(i&&(n=s.invalidSheetName?s.invalidSheetName:We(this.getters.getSheetName(s.sheetId))),i&&!n)return Ri.InvalidReference;let r=this.getRangePartString(s,0,o);return s.parts&&2===s.parts.length&&(s.zone.top!==s.zone.bottom||s.zone.left!==s.zone.right||s.parts[0].rowFixed||s.parts[0].colFixed||s.parts[1].rowFixed||s.parts[1].colFixed)&&(r+=":",r+=this.getRangePartString(s,1,o)),`${i?n+"!":""}${r}`}getRangeDataFromXc(e,t){return this.getters.getRangeFromSheetXC(e,t).rangeData}getRangeDataFromZone(e,t){return{_sheetId:e,_zone:t=this.getters.getUnboundedZone(e,t)}}getRangeFromZone(e,t){return new Lr({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=>Lr.fromRange(e,this.getters).unboundedZone)),s=t.map((e=>Lr.fromRange(e,this.getters).unboundedZone));return wo(o,s).map((t=>this.getRangeFromZone(e[0].sheetId,t)))}getRangeFromRangeData(e){const t={prefixSheet:!1,zone:e._zone,sheetId:e._sheetId,invalidSheetName:void 0,parts:[{colFixed:!1,rowFixed:!1},{colFixed:!1,rowFixed:!1}]};return new Lr(t,this.getters.getSheetSize)}isRangeValid(e){if(!e)return!1;const{xc:t,sheetName:o}=Zo(e);return null!==t.match(Bo)&&(!o||void 0!==this.getters.getSheetIdByName(o))}getRangesUnion(e){const t=e.map((e=>Lr.fromRange(e,this.getters).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=uS(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=uS(o),n=i.dependencies.map((o=>{const i=this.getters.getRangeFromSheetXC(e,o);return"keepSameReference"===s?i:Vr(e,t,i)}));return this.getters.getFormulaString(t,i.tokens,n)}getRangePartString(e,t,o={useBoundedReference:!1,useFixedReference:!1}){const s=e.parts[t]?.colFixed||o.useFixedReference?"$":"",i=vo(0===t?e.zone.left:e.zone.right),n=e.parts[t]?.rowFixed||o.useFixedReference?"$":"",r=String(0===t?e.zone.top+1:e.zone.bottom+1);let a="";return a=e.isFullCol&&!o.useBoundedReference?0===t&&e.unboundedZone.hasHeader?s+i+n+r:s+i:e.isFullRow&&!o.useBoundedReference?0===t&&e.unboundedZone.hasHeader?s+i+n+r:n+r:s+i+n+r,a}getInvalidRange(){return{parts:[],prefixSheet:!1,zone:{left:-1,top:-1,right:-1,bottom:-1},sheetId:"",invalidXc:Ri.InvalidReference}}}function eP(e,t){if(!e)return;const o=t(e);switch(o.changeType){case"NONE":return e;case"REMOVE":return;default:return o.range}}class tP extends qM{getters;constructor({getters:e,stateObserver:t}){super(t),this.getters=e}}const oP=new n;oP.add("pivots",(e=>{for(const t of e.getPivotIds()){const o=e.getPivot(t);fF.get(o.type).onIterationEndEvaluation(o)}}));const sP=Gb.mapping;function iP(e,t,o){return new nP(e,t,o).getParameters()}class nP{getters;computeCell;evalContext;rangeCache={};constructor(e,t,o){this.getters=t,this.computeCell=o,this.evalContext=Object.assign(Object.create(sP),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:jo(this.getters.getSheetName(e.sheetId),Qo(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=ns(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 Ko(e.zone)?e.invalidSheetName?new Ai(Mo("Invalid sheet name: %s",e.invalidSheetName)):void 0:new Di}}function rP(e,t,o,s,i){aP(e,t,o||0,s||e.length-1,i||cP)}function aP(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);aP(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(lP(e,o,t),i(e[s],h)>0&&lP(e,o,s);d<u;){for(lP(e,d,u),d++,u--;i(e[d],h)<0;)d++;for(;i(e[u],h)>0;)u--}0===i(e[o],h)?lP(e,o,u):lP(e,++u,s),u<=t&&(o=u+1),t<=u&&(s=u-1)}}function lP(e,t,o){var s=e[t];e[t]=e[o],e[o]=s}function cP(e,t){return e<t?-1:e>t?1:0}class hP{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(!CP(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;CP(e,a)&&(t.leaf?o.push(r):yP(e,a)?this._all(r,o):i.push(r))}t=i.pop()}return o}collides(e){let t=this.data;if(!CP(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(CP(e,n)){if(t.leaf||yP(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=wP([]),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=dP(e,o.children,t);if(-1!==s)return o.children.splice(s,1),i.push(o),this._condense(i),this}l||o.leaf||!yP(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=wP(e.slice(t,o+1)),uP(n,this.toBBox),n;s||(s=Math.ceil(Math.log(i)/Math.log(r)),r=Math.ceil(i/Math.pow(r,s-1))),n=wP([]),n.leaf=!1,n.height=s;const a=Math.ceil(i/r),l=a*Math.ceil(Math.sqrt(r));EP(e,t,o,l,this.compareMinX);for(let i=t;i<=o;i+=l){const t=Math.min(i+l-1,o);EP(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 uP(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=vP(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),pP(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=wP(o.children.splice(n,o.children.length-n));r.height=o.height,r.leaf=o.leaf,uP(o,this.toBBox),uP(r,this.toBBox),t?e[t-1].children.push(r):this._splitRoot(o,r)}_splitRoot(e,t){this.data=wP([e,t]),this.data.height=e.height+1,this.data.leaf=!1,uP(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=gP(e,0,r,this.toBBox),a=gP(e,r,o,this.toBBox),l=SP(t,a),c=vP(t)+vP(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:mP,i=e.leaf?this.compareMinY:fP;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=gP(e,0,t,i),r=gP(e,o-t,o,i);let a=bP(n)+bP(r);for(let s=t;s<o-t;s++){const t=e.children[s];pP(n,e.leaf?i(t):t),a+=bP(n)}for(let s=o-t-1;s>=t;s--){const t=e.children[s];pP(r,e.leaf?i(t):t),a+=bP(r)}return a}_adjustParentBBoxes(e,t,o){for(let s=o;s>=0;s--)pP(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():uP(e[o],this.toBBox)}}function dP(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 uP(e,t){gP(e,0,e.children.length,t,e)}function gP(e,t,o,s,i){i||(i=wP(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];pP(i,e.leaf?s(t):t)}return i}function pP(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 mP(e,t){return e.minX-t.minX}function fP(e,t){return e.minY-t.minY}function vP(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function bP(e){return e.maxX-e.minX+(e.maxY-e.minY)}function SP(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 yP(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function CP(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function wP(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function EP(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;rP(e,r,t,o,i),n.push(t,r,r,o)}}class xP{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 IP,this.rTrees[e].load(t[e])}insert(e){const t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new IP),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 IP extends hP{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 RP{createEmptyPositionSet;dependencies=new g_;rTree;constructor(e,t=[]){this.createEmptyPositionSet=e,this.rTree=new xP(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(vs(e)));for(const e in r){const t=wo(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 TP 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 AP{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]=TP.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 _P{resultsToArrayFormulas=new xP;arrayFormulasToResults=new g_;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map((e=>e.data))||DP}getArrayResultZone(e){return this.arrayFormulasToResults.get(e)}removeNode(e){this.resultsToArrayFormulas.remove({boundingBox:{sheetId:e.sheetId,zone:vs(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 DP=[],OP=Ar(new class extends Ai{constructor(e=Mo("Circular reference")){super(e,Ri.CircularDependency)}}),FP=Ar({value:null});class MP{context;getters;compilationParams;evaluatedCells=new g_;formulaDependencies=ut(new RP(this.createEmptyPositionSet.bind(this)));blockedArrayFormulas=new AP({});spreadingRelations=new _P;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=iP(this.context,this.getters,this.computeAndSave.bind(this))}getEvaluatedCell(e){return this.evaluatedCells.get(e)||FP}getSpreadZone(e,t={ignoreSpillError:!1}){const o=this.spreadingRelations.getArrayResultZone(e);if(!o)return;const s=this.evaluatedCells.get(e);return s?.type!==ri.error||t.ignoreSpillError&&s?.value===Ri.SpilledBlocked?is(vs(e),o):vs(e)}getEvaluatedPositions(){return this.evaluatedCells.keys()}getEvaluatedPositionsInSheet(e){return this.evaluatedCells.keysForSheet(e)}getArrayFormulaSpreadingOn(e){if(!(this.getEvaluatedCell(e).type!==ri.empty&&!this.getters.getCell(e)?.isFormula))return this.spreadingRelations.isArrayFormula(e)?e:void 0;const t=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e.sheetId,vs(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=iP(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 AP(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=us(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 _P,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 RP(this.createEmptyPositionSet.bind(this),e)}))}evaluateAllCells(){const e=performance.now();this.evaluatedCells=new g_,this.evaluate(this.getAllCells()),console.debug("evaluate all cells",performance.now()-e,"ms")}evaluateFormulaResult(e,t){const o=uS(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=kP(t,this.compilationParams,e,this.buildSafeGetSymbolValue(o),this.compilationParams.evalContext.__originCellPosition);return wi(s)?ln(s,NP):NP(s)}catch(e){return Zb(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 AP({});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!==FP&&this.evaluatedCells.set(o,s)}oP.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 FP;const s=o.id,i={format:o.format,locale:this.getters.getLocale()};try{return this.cellsBeingComputed.has(s)?OP:(this.cellsBeingComputed.add(s),o.isFormula?this.computeFormulaCell(e,o):Rr(o,i))}catch(e){return e.value=e?.value||Ri.GenericError,e.message=e?.message||Yb,Ar(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=kP(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e);if(!wi(o)){const s=Ar(NP(o),this.getters.getLocale(),t);return s.type===ri.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),PP(s,i,this.checkCollision(e)),PP(s,i,this.spreadValues(e,o)),this.invalidatePositionsDependingOnSpread(e.sheetId,n),Ar(NP(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===ys(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 Mi(Mo("Result couldn't be automatically expanded. Please insert more rows."));if(a)throw new Mi(Mo("Result couldn't be automatically expanded. Please insert more columns."));throw new Mi(Mo("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 Mi(Mo("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!==ri.empty)throw this.blockedArrayFormulas.add(e),new Mi(Mo("Array result was not expanded because it would overwrite data in %s.",Co(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=Ar(NP(s[i][n]),this.getters.getLocale(),a);l.type===ri.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 OP;this.symbolsBeingComputed.add(t);try{const o=e?.(t);return o||new _i(Mo("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=us(e);for(const e in o)t.push(...o[e].map((t=>({sheetId:e,zone:t}))));return this.formulaDependencies().getCellsDependingOn(t)}}function PP(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 NP(e){return null===e.value||void 0===e.value?{...e,value:0}:e}function kP(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 LP=/"(#[0-9a-fA-F]{6})"/g;const VP={isValid:!0};const UP="0.00%";function HP(e){return class extends e{getters;cache={};rankAsc={};rankDesc={};runningTotal={};runningTotalInPercent={};constructor(e,t){super(e,t),this.getters=t.getters}init(e){this.cache={},this.rankAsc={},this.rankDesc={},this.runningTotal={},this.runningTotalInPercent={},super.init(e)}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(o.length+s.length!==t.length){const o=this.getValuesToAggregate(e,t),s=Gl[e.aggregator];if(!s)return{value:0};try{return s([o],this.getters.getLocale())}catch(t){return Zb(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}=fl(this,t),s=o.findIndex((t=>t.field===e));return this.getPivotHeaderValueAndFormat(o.slice(0,s+1))}if(s.find((t=>t.nameWithGranularity===e))){const{rowDomain:o}=fl(this,t),s=o.findIndex((t=>t.field===e));return this.getPivotHeaderValueAndFormat(o.slice(0,s+1))}return this.getPivotCellValueAndFormat(e,t)}));return wi(n)?n[0][0]:n}getValuesToAggregate(e,t){const{rowDomain:o,colDomain:s}=fl(this,t),i=super.getTableStructure(),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}{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=ec(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 e}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:Ri.NotAvailable,message:Mo('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 Zb(e,"COMPUTE_MEASURE_DISPLAY_VALUE")}}asPercentOfGrandTotal(e,t){const o=this.getGrandTotal(t.id);return 0===o?{value:Ri.DivisionByZero}:{value:this.measureValueToNumber(e)/o,format:UP}}asPercentOfRowTotal(e,t,o){const s=this.getRowTotal(t.id,o);return 0===s?{value:Ri.DivisionByZero}:{value:this.measureValueToNumber(e)/s,format:UP}}asPercentOfColumnTotal(e,t,o){const s=this.getColumnTotal(t.id,o);return 0===s?{value:Ri.DivisionByZero}:{value:this.measureValueToNumber(e)/s,format:UP}}asPercentOfParentRowTotal(e,t,o){const s=function(e,t){const{colDomain:o,rowDomain:s}=fl(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:UP}}asPercentOfParentColumnTotal(e,t,o){const s=function(e,t){const{colDomain:o,rowDomain:s}=fl(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:UP}}asPercentOfParentTotal(e,t,o,s){const{fieldNameWithGranularity:i}=s;if(!i)return e;if(!Cl(i,o))return{value:""};const n=function(e,t,o){let{rowDomain:s,colDomain:i}=fl(e,o);if("row"===wl(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:UP}}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:Ri.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}=fl(this,o),h=El(c),d=El(l),u=a[h]?.[d];return{value:u??"",format:"running_total"===i?e.format:UP}}asPercentOf(e,t,o,s){const{fieldNameWithGranularity:i,value:n}=s;if(void 0===n||!i)return e;if(!Cl(i,o))return{value:""};let r=this.getComparisonValue(t,o,i,n),a=this.strictMeasureValueToNumber(e);return 0===r||"sameValue"===r&&0===a?{value:Ri.DivisionByZero}:!r||"sameValue"===r&&!a?{value:""}:"sameValue"===r?{value:1,format:UP}:void 0===a?{value:Ri.NullError}:{value:a/r,format:UP}}asDifferenceFrom(e,t,o,s){const{fieldNameWithGranularity:i,value:n}=s;if(void 0===n||!i)return e;if(!Cl(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(!Cl(i,o))return{value:""};let r=this.getComparisonValue(t,o,i,n);const a=this.strictMeasureValueToNumber(e);return 0===r?{value:Ri.DivisionByZero}:r&&"sameValue"!==r?void 0===a?{value:Ri.NullError}:{value:(a-r)/r,format:UP}:{value:""}}asRank(e,t,o,s,i){const{fieldNameWithGranularity:n}=s;if(!n)return e;if(!Cl(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}=fl(this,o),h=El(c),d=El(l),u=a[h]?.[d];return{value:u??""}}computeRank(e,t,o){const s={},i=wl(this,t),n="row"===i?"column":"row";let r=this.getPivotValueCells(e.id);"column"===i&&(r=cn(r));for(const a of r){const r=El(vl(this,n,a[0].domain)),l=a.map((t=>({...t,value:this.strictMeasureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain)),rowDomain:vl(this,i,t.domain)}))).filter((e=>Cl(t,e.rowDomain))),c=Object.groupBy(l,(e=>Il(e.rowDomain,t)));for(const e in c)c[e]=Mt(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=El(vl(this,i,e.domain)),n=c[Il(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:Pt(s)}computeRunningTotal(e,t,o){const s={},i=wl(this,t),n="row"===i?"column":"row";let r=this.getPivotValueCells(e.id);"column"===i&&(r=cn(r));for(const a of r){const r=El(vl(this,n,a[0].domain));s[r]={};const l={},c=a.map((t=>({...t,rowDomain:vl(this,i,t.domain),value:this.measureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain))}))).filter((e=>Cl(t,e.rowDomain)));for(const e of c){const o=El(e.rowDomain),i=Rl(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=El(o),n=Rl(o,t),a=s[r][i]||0,c=l[n];s[r][i]=c?a/c:void 0}}return"row"===i?s:Pt(s)}getGrandTotal(e){const t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){const o=fl(this,t).rowDomain,s=this._getPivotCellValueAndFormat(e,o);return this.measureValueToNumber(s)}getColumnTotal(e,t){const o=fl(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===pl||s===ml?function(e,t,o,s){const i=wl(e,o),n="row"===i?e.getTableStructure().getRowTree():e.getTableStructure().getColTree(),r=Sl(vl(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 yl(t,o,a[qe(c+(s===pl?-1:1),0,a.length-1)])}(this,t,o,s):yl(t,o,s);if(mt(i,t))return"sameValue";if(!i||!function(e,t){const{rowDomain:o,colDomain:s}=fl(e,t);return bl(o,e.getTableStructure().getRowTree())&&bl(s,e.getTableStructure().getColTree())}(this,i))throw new Oi;const n=this._getPivotCellValueAndFormat(e.id,i);return this.strictMeasureValueToNumber(n)}getPivotValueCells(e){return this.getTableStructure().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`)}getTableStructure(){const e=super.getTableStructure();return this.sortTableStructure(e),e}sortTableStructure(e){if(!this.definition.sortedColumn||e.isSorted)return;const t=this.definition.sortedColumn.measure;lc(this.definition.sortedColumn,this)&&e.sort(t,this.definition.sortedColumn,((e,t)=>this._getPivotCellValueAndFormat(e,t)))}}}const BP=["ADD_PIVOT","UPDATE_PIVOT"];function zP(e){return BP.includes(e.type)}class $P extends qM{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 WP{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}=RS.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}}}}function GP(e,t){if("SPREADSHEET"!==e.pivot.type)return e;if(e.pivot.dataSet?.sheetId!==t.sheetId)return e;const o=pc(e.pivot.dataSet.zone,t),s=o?{...e.pivot.dataSet,zone:o}:void 0;return{...e,pivot:{...e.pivot,dataSet:s}}}function qP(e,t){return{...e,definition:CR(e.definition,t)}}function ZP(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(let 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 jP(e,t){if(e.sheetId!==t.sheetId)return e;const o=pc(e.zone,t);if(!o)return;const s=e.newTableRange?mc(e.newTableRange,t):void 0;return{...e,newTableRange:s,zone:o}}function YP(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let o;if("REMOVE_COLUMNS_ROWS"===t.type)o=Gr(t.elements,[e.base])[0];else if("ADD_COLUMNS_ROWS"===t.type){o=Wr(pt(t.position,t.base),t.quantity,[e.base])[0]}return void 0!==o?{...e,base:o}:void 0}function XP(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;const o=Ze(e.start,e.end+1);let s=[];if("REMOVE_COLUMNS_ROWS"===t.type)s=Gr(t.elements,o);else if("ADD_COLUMNS_ROWS"===t.type){s=Wr(pt(t.position,t.base),t.quantity,o)}return 0!==s.length?{...e,start:Math.min(...s),end:Math.max(...s)}:void 0}Y_.addTransformation("ADD_COLUMNS_ROWS",["ADD_COLUMNS_ROWS"],YP),Y_.addTransformation("REMOVE_COLUMNS_ROWS",["ADD_COLUMNS_ROWS"],YP),Y_.addTransformation("ADD_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],qP),Y_.addTransformation("REMOVE_COLUMNS_ROWS",["CREATE_CHART","UPDATE_CHART"],qP),Y_.addTransformation("DELETE_SHEET",["MOVE_RANGES"],(function(e,t){const o=t.sheetId;if(e.targetSheetId===o||e.sheetId===o)return;return e})),Y_.addTransformation("DELETE_FIGURE",["UPDATE_FIGURE","UPDATE_CHART"],(function(e,t){if(e.id===t.id)return;return e})),Y_.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})),Y_.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)for(const e of t.target)as(s,e)||o.push({...s});if(o.length)return{...e,target:o};return})),Y_.addTransformation("ADD_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],ZP),Y_.addTransformation("REMOVE_COLUMNS_ROWS",["FREEZE_COLUMNS","FREEZE_ROWS"],ZP),Y_.addTransformation("ADD_COLUMNS_ROWS",["UPDATE_TABLE"],jP),Y_.addTransformation("REMOVE_COLUMNS_ROWS",["UPDATE_TABLE"],jP),Y_.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:tw.styleId}}})),Y_.addTransformation("ADD_COLUMNS_ROWS",["GROUP_HEADERS","UNGROUP_HEADERS","FOLD_HEADER_GROUP","UNFOLD_HEADER_GROUP"],XP),Y_.addTransformation("REMOVE_COLUMNS_ROWS",["GROUP_HEADERS","UNGROUP_HEADERS","FOLD_HEADER_GROUP","UNFOLD_HEADER_GROUP"],XP),Y_.addTransformation("REMOVE_PIVOT",["RENAME_PIVOT","DUPLICATE_PIVOT","INSERT_PIVOT","UPDATE_PIVOT"],(function(e,t){if(e.pivotId===t.pivotId)return;return e})),Y_.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})),Y_.addTransformation("ADD_COLUMNS_ROWS",["ADD_PIVOT","UPDATE_PIVOT"],GP),Y_.addTransformation("REMOVE_COLUMNS_ROWS",["ADD_PIVOT","UPDATE_PIVOT"],GP);const KP=[{match:function(e){return"sheetId"in e},fn:eN},{match:function(e){return"target"in e&&"sheetId"in e},fn:function(e,t){const o=eN(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;const s=[];for(const o of e.target){const e=pc(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=eN(e,t);if("SKIP_TRANSFORMATION"!==o)return"IGNORE_COMMAND"===o?"IGNORE_COMMAND":e;const s=pc(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=eN(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(let 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)&&ls(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=eN(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=Gr(t.elements,e.elements);else if("ADD_COLUMNS_ROWS"===t.type){s=Wr(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=>mc(e,t))).filter(at);if(!o.length)return"IGNORE_COMMAND";return{...e,ranges:o}}}];function JP(e,t){const o=Y_.getTransformation(e.type,t.type);return o?o(e,t):function(e,t){for(const{match:o,fn:s}of KP)if(o(e)){const o=s(e,t);if("SKIP_TRANSFORMATION"===o)continue;if("IGNORE_COMMAND"===o)return;e=o}return e}(e,t)}function QP(e,t){let o=[...e];for(const e of t)o=o.map((t=>JP(t,e))).filter(at);return o}function eN(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 tN{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 oN extends Error{}class sN extends fc{revisions;transportService;serverRevisionId;clients={};clientId="local";debouncedMove;pendingMessages=[];waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;uuidGenerator=new la;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 tN(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))}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})}getClient(){const e=this.clients[this.clientId];if(!e)throw new oN("The client left the session");return e}getConnectedClients(){return new Set(Object.values(this.clients).filter(at))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return 0===this.pendingMessages.length}getLastLocalNonEmptyRevision(){return this.lastLocalOperation}_move(e){if(!this.clients[this.clientId])return;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.getClient();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 tN(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:QP(o,t)})}break;case"SNAPSHOT_CREATED":{const t=new tN(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 iN=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 nN(e){return iN.has(e.type)}const rN=[aN,function(e,t){return"target"in t&&Array.isArray(t.target)?{...Be(t),target:e.getSelectedZones()}:t},function(e,t){if(!("row"in t)||!("col"in t))return t;const{col:o,row:s}=e.getActivePosition();return{...Be(t),col:o,row:s}},function(e,t){return"ranges"in t?{...Be(t),ranges:e.getSelectedZones().map((t=>e.getRangeDataFromZone(e.getActiveSheetId(),t)))}:t}];function aN(e,t){return"sheetId"in t?{...Be(t),sheetId:e.getActiveSheetId()}:t}function lN(e,t){return"zone"in t?{...Be(t),zone:e.getSelectedZone()}:t}const cN=new la;function hN(e,t){const o=e.getSelectedZone();return{...aN(e,t),elements:"COL"===t.dimension?Ze(o.left,o.right+1):Ze(o.top,o.bottom+1)}}function dN(e,t){const o=e.getSelectedZone();return{...Be(t),zone:o}}function uN(e,t){const o=Be(t),s=e.getSelectedZone(),{top:i,bottom:n,left:r,right:a}=s;return"cols"in o?o.cols=Ze(r,a+1):"rows"in o&&(o.rows=Ze(i,n+1)),o}function gN(e,t){const o=e.getSelectedZone();return{...aN(e,t),start:"COL"===t.dimension?o.left:o.top,end:"COL"===t.dimension?o.right:o.bottom}}const pN=new n;pN.add("UPDATE_CELL",fN),pN.add("CLEAR_CELL",fN),pN.add("CLEAR_CELLS",fN),pN.add("DELETE_CONTENT",fN),pN.add("ADD_MERGE",fN),pN.add("REMOVE_MERGE",fN),pN.add("SET_FORMATTING",fN),pN.add("CLEAR_FORMATTING",fN),pN.add("SET_BORDER",fN),pN.add("CREATE_TABLE",fN),pN.add("REMOVE_TABLE",fN),pN.add("HIDE_SHEET",fN),pN.add("ADD_COLUMNS_ROWS",(function(e,t){const o=e.getActivePosition();return{...aN(e,t),base:"COL"===t.dimension?o.col:o.row}})),pN.add("REMOVE_COLUMNS_ROWS",hN),pN.add("HIDE_COLUMNS_ROWS",hN),pN.add("RESIZE_COLUMNS_ROWS",hN),pN.add("CREATE_SHEET",(function(e,t){const o=Be(t);o.sheetId=cN.smallUuid();const s=t.name||e.getSheet(e.getActiveSheetId()).name,i=s.match(/(.+?)\d*$/)?.[1]||s;return o.name=e.getNextSheetName(i),o})),pN.add("CREATE_FIGURE",(function(e,t){const o=aN(e,t);return o.figure.id=cN.smallUuid(),o})),pN.add("CREATE_CHART",(function(e,t){return{...aN(e,t),id:cN.smallUuid()}})),pN.add("CREATE_IMAGE",(function(e,t){return{...aN(e,t),figureId:cN.smallUuid()}})),pN.add("GROUP_HEADERS",gN),pN.add("UNGROUP_HEADERS",gN),pN.add("UNGROUP_HEADERS",gN),pN.add("UNFOLD_HEADER_GROUPS_IN_ZONE",lN),pN.add("FOLD_HEADER_GROUPS_IN_ZONE",lN);const mN=new n;function fN(e,t){let o=Be(t);for(const t of rN)o=t(e,o);return o}function vN(e,t){if(e.rootCommand&&"object"==typeof e.rootCommand)return mi(e.rootCommand)?function(e,t){if(!t)return;if(!pN.contains(t.type))return;return pN.get(t.type)(e,t)}(t,e.rootCommand):function(e,t,o){if(!mN.contains(t.type))return;return mN.get(t.type)(e,t,o)}(t,e.rootCommand,e.commands)}mN.add("PASTE",(function(e,t){return{type:"REPEAT_PASTE",pasteOption:Be(t.pasteOption),target:e.getSelectedZones()}})),mN.add("INSERT_CELL",dN),mN.add("DELETE_CELL",dN),mN.add("AUTORESIZE_COLUMNS",uN),mN.add("AUTORESIZE_ROWS",uN),mN.add("SORT_CELLS",(function(e,t){const o=e.getSelectedZone();return{...aN(e,t),col:o.left,row:o.top,zone:o}})),mN.add("SUM_SELECTION",fN),mN.add("SET_DECIMAL",fN);class bN{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,size:s}=this.getters.getColDimensions(this.sheetId,e),{end:i,size:n}=this.getters.getRowDimensions(this.sheetId,t),r=this.searchHeaderIndex("COL",o-this.viewportWidth,0),a=this.getters.getColSize(this.sheetId,r),l=this.searchHeaderIndex("ROW",i-this.viewportHeight,0),c=this.getters.getRowSize(this.sheetId,l);let h=o-this.offsetCorrectionX;this.canScrollHorizontally&&(h+=Math.max(oe,Math.min(a,this.viewportWidth-s)),h=Math.max(h,this.viewportWidth));let d=i-this.offsetCorrectionY;return this.canScrollVertically&&(d+=Math.max(se+5,Math.min(c,this.viewportHeight-n)),d=Math.max(d,this.viewportHeight),i+ce>d&&!this.getters.isReadonly()&&(d+=ce)),{width:h,height:d}}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);ls(s,this.boundaries.top,this.boundaries)&&this.adjustPositionX(s),ls(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=ns(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=ns(e,this),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 SN=(new n).add("settings",class extends ZM{static getters=["getLocale"];locale=yi;allowDispatch(e){return"UPDATE_LOCALE"===e.type?Da(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===$a(e)&&(o=$a(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??yi}export(e){e.settings={locale:this.locale}}}).add("sheet",class extends ZM{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"];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":"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||$t(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=Ot(e.elements),o=Dt(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.name);break;case"COLOR_SHEET":this.history.update("sheets",e.sheetId,"color",e.color);break;case"HIDE_SHEET":this.hideSheet(e.sheetId);break;case"SHOW_SHEET":this.showSheet(e.sheetId);break;case"DUPLICATE_SHEET":this.duplicateSheet(e.sheetId,e.sheetIdTo);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(let t of e.sheets)this.sheetIdsMapName[t.name]=t.id;for(let 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:$r(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(at).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=ze(e);for(const e in this.sheetIdsMapName)if(e.toUpperCase()===t.toUpperCase())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(at)}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 Nt(e,this.orderedSheetIds.map(this.getSheetName.bind(this)),{compute:(e,t)=>`${e}${t}`,computeFirstOne:!0})}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,Ze(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&&"row"in e&&t.push({top:e.row,left:e.col,bottom:e.row,right:e.col}),t}checkZonesExistInSheet(e,t){if(!t.every(Ko))return"InvalidRange";if(t.length){const o=this.getSheetZone(e);return t.every((e=>cs(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:$r(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);let 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(Mo("There is not enough visible sheets"))}checkSheetName(e){const t=this.getters.tryGetSheetName(e.sheetId);if(void 0!==t&&e.name===t)return"UnchangedSheetName";const{orderedSheetIds:o,sheets:s}=this,i=e.name&&e.name.trim().toLowerCase();return o.find((t=>s[t]?.name.toLowerCase()===i&&t!==e.sheetId))?"DuplicatedSheetName":_e.test(i)?"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(let 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(let o of t)if(o.left<e.quantity&&e.quantity<=o.right)return"MergeOverlap";return"Success"}isRenameAllowed(e){return e.name&&e.name.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){const o=this.getSheet(e),s=this.getDuplicateSheetName(o.name),i=Be(o);i.id=t,i.name=s;for(let e=0;e<=i.numberOfCols;e++)for(let t=0;t<=i.rows.length;t++)i.rows[t]&&(i.rows[t].cells[e]=void 0);const n=this.orderedSheetIds.slice(),r=n.indexOf(e);n.splice(r+1,0,i.id),this.history.update("orderedSheetIds",n),this.history.update("sheets",Object.assign({},this.sheets,{[i.id]:i}));for(const t of Object.values(this.getters.getCells(e))){const{col:e,row:o}=this.getCellPosition(t.id);this.dispatch("UPDATE_CELL",{sheetId:i.id,col:e,row:o,content:t.content,format:t.format,style:t.style})}const a=Object.assign({},this.sheetIdsMapName);a[i.name]=i.id,this.history.update("sheetIdsMapName",a)}getDuplicateSheetName(e){const t=this.orderedSheetIds.map(this.getSheetName.bind(this));return Nt(Mo("Copy of %s",e).toString(),t)}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(let 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(let o of je(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(let 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(let 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(let 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(let 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(let 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(yo);let o=e.rowNumber,s=e.colNumber;for(let{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 ZM{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(Ze(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=Be(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;Ze(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&&Et([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]=Wr(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=Gr(o,Ze(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=tC(t,e,i);n.outlineLevel=s+1,o.isFolded&&(n.isHidden=!0)}if(o.isFolded){tC(t,e,o.end+1).collapsed=!0}}}}}}).add("header visibility",class extends ZM{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":Ot(e.elements)<0||Dt(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,Be(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(let 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(let t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!0);break;case"UNHIDE_COLUMNS_ROWS":for(let t of e.elements)this.history.update("hiddenHeaders",e.sheetId,e.dimension,t,!1)}}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=Ze(0,this.getters.getNumberHeaders(e,t)),s=[];return this.getters.getHeaderGroups(e,t).forEach((e=>{e.isFolded&&s.push(...Ze(e.start,e.end+1))})),o.filter((o=>!this.hiddenHeaders[e][t][o]&&!s.includes(o)))}import(e){for(let t of e.sheets){this.hiddenHeaders[t.id]={COL:[],ROW:[]};for(let e=0;e<t.rowNumber;e++)this.hiddenHeaders[t.id].ROW[e]=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(let 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 ZM{static getters=["getCoreTable","getCoreTables","getCoreTableMatchingTopLeft"];tables={};nextTableId=1;adaptRanges(e,t){const o=t?[t]:this.getters.getSheetIds();for(const t of o)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 Cs(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(as(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);this.dispatch("REMOVE_MERGE",{sheetId:e.sheetId,target:s});const i=this.consumeNextId(),n=e.config||tw,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=>!ns(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=>cs(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(at):[]}getCoreTable({sheetId:e,col:t,row:o}){return this.getCoreTables(e).find((e=>ls(t,o,e.range.zone)))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter((e=>t.some((t=>as(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(const e of gs(a)){const o={sheetId:t,...e},s=this.getters.getCell(o)?.content;if(s||this.getters.isInMerge(o)||this.getTablesOverlappingZones(t,[vs(e)]).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 Ze(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=bs(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 Ze(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,bs(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 _F(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 _F(o.id,s,t.config,this.getters.getRangeFromZone)}));return{id:t.id,range:o,filters:s,config:Be(t.config),type:t.type}}copyDynamicTableForSheet(e,t){const o=this.getters.getRangeFromZone(e,t.range.zone);return{id:t.id,range:o,config:Be(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=_F(e.id,o,t.config,this.getters.getRangeFromZone);n.push(i)}}const r=i.zone;if(n.length<hs(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||tw,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:Qo(e.range.zone),type:e.type};mt(e.config,tw)||(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=Qo(e.range.zone);t.tables.push({range:o,filters:[],config:e.config})}}}).add("dataValidation",class extends ZM{static getters=["cellHasListDataValidationIcon","getDataValidationRule","getDataValidationRules","getValidationRuleForCell"];rules={};adaptRanges(e,t){const o=t?[t]:Object.keys(this.rules);for(const t of o)this.loopThroughRangesOfSheet(t,e)}loopThroughRangesOfSheet(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=Be(this.rules[e.sheetId]).map((t=>({...t,ranges:t.ranges.map((t=>Vr(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=wo(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,Co(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(ls(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)}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),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){o=Be(o);for(const e of o)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 Br(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={...Be(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 vO.contains(e.rule.criterion.type)?"Success":"UnknownDataValidationCriterionType"}checkCriterionHasValidNumberOfValues(e){const t=e.rule.criterion,o=vO.get(t.type).numberOfValues(t);return void 0!==o&&t.values.length!==o?"InvalidNumberOfCriterionValues":"Success"}checkCriterionValuesAreValid(e){const t=e.rule.criterion,o=vO.get(t.type);return t.values.some((e=>"onlyFormulas"===o.allowedValues&&!e.startsWith("=")||(e.startsWith("=")?"onlyLiterals"===o.allowedValues||uS(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 ZM{static getters=["zoneToXC","getCells","getTranslatedCellFormula","getCellStyle","getCellById","getFormulaString","getFormulaMovedInSheet"];nextId=1;cells={};adaptRanges(e,t){for(const o of Object.keys(this.cells))for(const s of Object.values(this.cells[o]||{}))if(s.isFormula)for(const i of s.compiledFormula.dependencies)if(!t||i.sheetId===t){const t=e(i);"NONE"!==t.changeType&&this.history.update("cells",o,s.id,"compiledFormula","dependencies",s.compiledFormula.dependencies.indexOf(i),t.range)}}allowDispatch(e){switch(e.type){case"UPDATE_CELL":return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessUpdateCell);case"CLEAR_CELL":return this.checkValidations(e,this.checkCellOutOfSheet,this.checkUselessClearCell);case"UPDATE_CELL_POSITION":return!e.cellId||this.cells[e.sheetId]?.[e.cellId]?"Success":"InvalidCellId";default:return"Success"}}handle(e){switch(e.type){case"SET_FORMATTING":"style"in e&&this.setStyle(e.sheetId,e.target,e.style),"format"in e&&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(let o of wo(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(let s of wo(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(let o of wo(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=Ze(e.base,e.base+e.quantity),s=e.base+e.quantity):(o=Ze(e.base+1,e.base+e.quantity+1),s=e.base),t(e.sheetId,s,o)}import(e){for(let t of e.sheets){const o=t.id,s=new g_;for(const e in t.cells)if(t.cells[e]){const{col:o,row:i}=yo(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 Is(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(let 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=Co(s.col,s.row),l=this.removeDefaultStyleValues(r.style);if(Object.keys(l).length){const o=Es(l,t);e[o]??=[],e[o].push(s)}if(r.format){const e=Es(r.format,o);i[e]??=[],i[e].push(s)}r.content&&(n[a]=r.content)}s.styles=xs(e),s.formats=xs(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||[])xr(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(gS(s).dependencies.map((t=>this.getters.getRangeFromSheetXC(e,t))),t,o,e);return this.getFormulaString(e,s,i)}getFormulaMovedInSheet(e,t,o){const s=gS(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=Co((t=this.getters.expandZone(e,t)).left,t.top,o[0]),i=Co(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(let s of wo(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(let 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(let 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?wt(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=Tr(t,i);return Ir(o=o||("number"==typeof n?dr(t,i)||ur(t):void 0))||Li(t)||(t=Zi(n)),{id:e,content:t,style:s,format:o,isFormula:!1,parsedValue:n}}createFormulaCell(e,t,o,s,i){const n=uS(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 jM(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 ls(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 ZM{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(at))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){const o=t?[t]:Object.keys(this.merges);for(const t of o)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map((t=>this.getMergeById(e,parseInt(t,10)))).filter(at)}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(at)}getSelectionRangeString(e,t){const o=Lr.fromRange(e,this.getters),s=this.getters.expandZone(o.sheetId,o.zone),i=o.clone({zone:{...s,bottom:o.isFullCol?void 0:s.bottom,right:o.isFullRow?void 0:s.right}}),n=this.getters.getRangeString(i,t);if(this.isSingleCellOrMerge(o.sheetId,o.zone)){const{sheetName:e,xc:t}=Zo(n);return jo(e,t.split(":")[0])}return n}doesIntersectMerge(e,t){for(const o of this.getMerges(e))if(as(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){let{left:o,right:s,top:i,bottom:n}=t,r={left:o,right:s,top:i,bottom:n};for(let t in this.merges[e]){const o=this.getMergeById(e,parseInt(t));o&&as(o,r)&&(r=is(o,r))}return rs(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)&&rs(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(let e of o)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let 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 rs(t,o);const{numberOfCols:s,numberOfRows:i}=hs(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=qe(s,0,this.getters.getNumberCols(e)-1),n=qe(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?JM(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&&as(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);for(const e of t)if(e.left<o&&e.right>=o||e.top<s&&e.bottom>=s)return"FrozenPaneOverlap";return"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||!rs(e,i))return"InvalidTarget"}return"Success"}addMerge(e,t){let{left:o,right:s,top:i,bottom:n}=t;s=qe(s,0,this.getters.getNumberCols(e)-1),n=qe(n,0,this.getters.getNumberRows(e)-1);if(Co(o,i)===Co(s,n))return;const r=this.getters.getCell({sheetId:e,col:o,row:i});let a=this.nextId++;this.history.update("merges",e,a,this.getters.getRangeFromSheetXC(e,Qo({left:o,top:i,right:s,bottom:n})));let 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(let 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&&rs(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}=hs(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 gs(t))this.history.update("mergeCellMap",e,o,s,t.id)}import(e){const t=e.sheets||[];for(let e of t)this.history.update("merges",e.id,{}),this.history.update("mergeCellMap",e.id,{}),e.merges&&this.importMerges(e.id,e.merges)}importMerges(e,t){for(let o of t)this.addMerge(e,Xo(o))}export(e){for(let t of e.sheets){const e=this.merges[t.id];e&&t.merges.push(...KM(e))}}exportForExcel(e){this.export(e)}}).add("headerSize",class extends ZM{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,Be(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=It(this.sizes[e.sheetId][e.dimension],e.elements);this.history.update("sizes",e.sheetId,e.dimension,t);break}case"ADD_COLUMNS_ROWS":{let t=[...this.sizes[e.sheetId][e.dimension]];const 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]||oe)}getUserRowSize(e,t){const o=this.sizes[e]?.ROW[t];return o?Math.round(o):void 0}import(e){for(let t of e.sheets){const e={COL:Array(t.colNumber).fill(void 0),ROW:Array(t.rowNumber).fill(void 0)};for(let[o,s]of Object.entries(t.rows))s.size&&(e.ROW[o]=s.size);for(let[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(let o of e.sheets){void 0===o.rows&&(o.rows={});for(const e of Ze(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)??se});void 0===o.cols&&(o.cols={});for(let e of Ze(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 ZM{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=>Be(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_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 je(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?Be(s):null}getBordersColors(e){const t=[],o=this.borders[e];if(o)for(const e of o.filter(at))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=Ze(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(let o of s)this.addBorder(e,o,i,t)}}}ensureRowBorderContinuity(e,t,o){const s=Ze(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(let o of s)this.addBorder(e,i,o,t)}}}getCommonSides(e,t){const o={};for(let 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(at);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]?Ze(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(let n of wo(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(let 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(let i of wo(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 Is(t.id,t.borders)){const{sheetId:t,col:i,row:n}=o,r=e.borders[s];this.setBorder(t,i,n,r,!1)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,Xo(e))}export(e){const t={};for(let 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=Es(n,t),a={sheetId:o.id,col:s,row:i};e[r]??=[],e[r].push(a)}}o.borders=xs(e)}e.borders=t}exportForExcel(e){this.export(e)}}).add("conditional formatting",class extends ZM{static getters=["getConditionalFormats","getRulesSelection","getRulesByCell","getAdaptedCfRanges"];cfRules={};loopThroughRangesOfSheet(e,t){for(const o of this.cfRules[e]){if("DataBarRule"===o.rule.type&&o.rule.rangeValues){const s=t(o.rule.rangeValues);switch(s.changeType){case"REMOVE":this.history.update("cfRules",e,this.cfRules[e].indexOf(o),"rule","rangeValues",void 0);break;case"RESIZE":case"MOVE":case"CHANGE":this.history.update("cfRules",e,this.cfRules[e].indexOf(o),"rule","rangeValues",s.range)}}for(const s of o.ranges){const i=t(s);switch(i.changeType){case"REMOVE":let 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){if(t)this.loopThroughRangesOfSheet(t,e);else for(const t of Object.keys(this.cfRules))this.loopThroughRangesOfSheet(t,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(let t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map((e=>this.mapToConditionalFormatInternal(t.id,e)))}export(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map((e=>this.mapToConditionalFormat(t.id,e))))}exportForExcel(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map((e=>this.mapToConditionalFormat(t.id,e,{useBoundedReference:!0}))))}getConditionalFormats(e){return this.cfRules[e]?.map((t=>this.mapToConditionalFormat(e,t)))||[]}getRulesSelection(e,t){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(let i of this.cfRules[e])for(let e of i.ranges)ls(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(Yo));const a=wo(r,s);return wo([...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(2,["Between","NotBetween"]),this.checkOperatorArgsNumber(1,["BeginsWith","ContainsText","EndsWith","GreaterThan","GreaterThanOrEqual","LessThan","LessThanOrEqual","NotContains","Equal","NotEqual"]),this.checkOperatorArgsNumber(0,["IsEmpty","IsNotEmpty"]),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,t){if(e>2)throw new Error("Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.");return o=>{if(t.includes(o.operator)){const t=[],s=e=>void 0===e||""===e;return e>=1&&s(o.values[0])&&t.push("FirstArgMissing"),e>=2&&s(o.values[1])&&t.push("SecondArgMissing"),t.length?t:"Success"}return"Success"}}checkNaN(e,t){if(["number","percentage","percentile"].includes(e.type)&&(""===e.value||isNaN(e.value)))switch(t){case"min":return"MinNaN";case"max":return"MaxNaN";case"mid":return"MidNaN";case"upperInflectionPoint":return"ValueUpperInflectionNaN";case"lowerInflectionPoint":return"ValueLowerInflectionNaN"}return"Success"}checkFormulaCompilation(e,t){if("formula"!==e.type)return"Success";if(uS(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&&XM(t)>=XM(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&&XM(t)>=XM(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&&XM(t)>=XM(o)?"MinBiggerThanMid":"Success"}checkCFValues(e){for(const t of e.values){if(!t.startsWith("="))continue;if(uS(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 ZM{static getters=["getFigures","getFigure","getFigureSheetId"];figures={};insertionOrders=[];allowDispatch(e){switch(e.type){case"CREATE_FIGURE":return this.checkFigureDuplicate(e.figure.id);case"UPDATE_FIGURE":case"DELETE_FIGURE":return this.checkFigureExists(e.sheetId,e.id);default:return"Success"}}beforeHandle(e){if("DELETE_SHEET"===e.type)this.getters.getFigures(e.sheetId).forEach((t=>{this.dispatch("DELETE_FIGURE",{id: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":this.addFigure(e.figure,e.sheetId);break;case"UPDATE_FIGURE":const{type:t,sheetId:o,...s}=e,i=s;this.updateFigure(o,i);break;case"DELETE_FIGURE":this.removeFigure(e.id,e.sheetId);break;case"REMOVE_COLUMNS_ROWS":this.onRowColDelete(e.sheetId,e.dimension)}}onRowColDelete(e,t){"ROW"===t?this.onRowDeletion(e):this.onColDeletion(e)}onRowDeletion(e){const t=this.getters.getNumberRows(e);let o=0;for(let s=0;s<t;s++)o+=this.getters.getUserRowSize(e,s)||se;const s=this.getters.getFigures(e);for(const t of s){const s=Math.min(t.y,o-t.height);s!==t.y&&this.dispatch("UPDATE_FIGURE",{sheetId:e,id:t.id,y:s})}}onColDeletion(e){const t=this.getters.getNumberCols(e);let o=0;for(let s=0;s<t;s++)o+=this.getters.getColSize(e,s);const s=this.getters.getFigures(e);for(const t of s){const s=Math.min(t.x,o-t.width);s!==t.x&&this.dispatch("UPDATE_FIGURE",{sheetId:e,id:t.id,x:s})}}updateFigure(e,t){if("id"in t)for(const[o,s]of Object.entries(t))switch(o){case"x":case"y":void 0!==s&&this.history.update("figures",e,t.id,o,Math.max(s,0));break;case"width":case"height":void 0!==s&&this.history.update("figures",e,t.id,o,s)}}addFigure(e,t){this.history.update("figures",t,e.id,e),this.history.update("insertionOrders",this.insertionOrders.length,e.id)}deleteSheet(e){this.history.update("insertionOrders",this.insertionOrders.filter((t=>!this.figures[e]?.[t]))),this.history.update("figures",e,void 0)}removeFigure(e,t){this.history.update("insertionOrders",this.insertionOrders.filter((t=>t!==e))),this.history.update("figures",t,e,void 0)}checkFigureExists(e,t){return void 0===this.figures[e]?.[t]?"FigureDoesNotExist":"Success"}checkFigureDuplicate(e){return Object.values(this.figures).find((t=>t?.[e]))?"DuplicatedFigureId":"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(let 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){this.export(e)}}).add("chart",class extends ZM{static getters=["isChartDefined","getChartDefinition","getChartType","getChartIds","getChart","getContextCreationChart"];charts={};createChart=bR(this.getters);validateChartDefinition=e=>yR(this,e.definition);adaptRanges(e){for(const[t,o]of Object.entries(this.charts))this.history.update("charts",t,o?.updateRanges(e))}allowDispatch(e){switch(e.type){case"CREATE_CHART":return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartDuplicate));case"UPDATE_CHART":return this.checkValidations(e,this.chainValidations(this.validateChartDefinition,this.checkChartExists));default:return"Success"}}handle(e){switch(e.type){case"CREATE_CHART":this.addFigure(e.id,e.sheetId,e.position,e.size),this.addChart(e.id,e.definition);break;case"UPDATE_CHART":this.addChart(e.id,e.definition);break;case"DUPLICATE_SHEET":{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",{id:s,position:{x:o.x,y:o.y},size:{width:o.width,height:o.height},definition:i.getDefinition(),sheetId:e.sheetIdTo})}break}case"DELETE_FIGURE":this.history.update("charts",e.id,void 0);break;case"DELETE_SHEET":for(let t of this.getChartIds(e.sheetId))this.history.update("charts",t,void 0)}}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(let t of e.sheets)if(t.figures)for(let 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(let t of e.sheets){const e=this.getters.getFigures(t.id),o=[];for(let 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={x:0,y:0},s={width:536,height:335}){if(this.getters.getFigure(t,e))return;const i={id:e,x:o.x,y:o.y,width:s.width,height:s.height,tag:"chart"};this.dispatch("CREATE_FIGURE",{sheetId:t,figure:i})}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.id)?"DuplicatedChartId":"Success"}checkChartExists(e){return this.getters.getFigureSheetId(e.id)?"Success":"ChartDoesNotExist"}}).add("image",class extends ZM{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.addImage(e.figureId,e.sheetId,e.position,e.size),this.history.update("images",e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case"DUPLICATE_SHEET":{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,position:{x:o.x,y:o.y},size:t,definition:Be(i)})}}break}case"DELETE_FIGURE":this.history.update("images",e.sheetId,e.id,void 0);break;case"DELETE_SHEET":this.history.update("images",e.sheetId,void 0)}}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}addImage(e,t,o,s){const i={id:e,x:o.x,y:o.y,width:s.width,height:s.height,tag:"image"};this.dispatch("CREATE_FIGURE",{sheetId:t,figure:i})}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:Be(e)})}t.images=[...t.images,...o]}}getAllImages(){const e=[];for(const t in this.images)e.push(...Object.values(this.images[t]||{}).filter(at));return e}}).add("pivot_core",class extends ZM{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.checkDuplicatedMeasureIds(e.pivot);case"UPDATE_PIVOT":return e.pivotId in this.pivots?mt(e.pivot,this.pivots[e.pivotId]?.definition)?"NoChanges":""===e.pivot.name?"EmptyName":this.checkDuplicatedMeasureIds(e.pivot):"PivotIdNotFound";case"RENAME_PIVOT":if(!(e.pivotId in this.pivots))return"PivotIdNotFound";if(""===e.name)return"EmptyName";break;case"REMOVE_PIVOT":case"DUPLICATE_PIVOT":case"INSERT_PIVOT":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 iF(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=Be(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",Be(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:Be(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:Ql(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,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,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=uS(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})}}}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||ql(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 ZM{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=eP(this.getters.getRangeFromZone(s,i),e),r=n&&{sheetId:n.sheetId,zone:n.zone};this.dispatch("UPDATE_PIVOT",{pivotId:t,pivot:{...o,dataSet:r}})}}}}).add("tableStyle",class extends ZM{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(!bw[e.templateName])return"InvalidTableStyle";try{zt(e.primaryColor)}catch(e){return"InvalidTableStyle"}}return"Success"}handle(e){switch(e.type){case"CREATE_TABLE_STYLE":const t=Sw(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:tw.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 Nt(Mo("Custom Table Style"),Object.values(this.styles).map((e=>e.displayName)),{compute:(e,t)=>`${e} ${t}`,start:2})}isTableStyleEditable(e){return!vw[e]}import(e){for(const e in vw)this.styles[e]=vw[e];for(const t in e.customTableStyles){const o=e.customTableStyles[t];this.styles[t]=Sw(o.displayName,o.templateName,o.primaryColor)}}export(e){const t={};for(const e in this.styles)vw[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}}),yN=(new n).add("ui_sheet",class extends $P{static getters=["doesCellHaveGridIcon","getCellWidth","getCellIconSrc","getTextWidth","getCellText","getCellMultiLineText","getContiguousZone"];ctx=document.createElement("canvas").getContext("2d");allowDispatch(e){return this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e)}handle(e){switch(e.type){case"AUTORESIZE_COLUMNS":for(let t of e.cols){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.dispatch("RESIZE_COLUMNS_ROWS",{elements:e.rows,dimension:"ROW",size:null,sheetId:e.sheetId})}}getCellWidth(e){const t=this.getters.getCellComputedStyle(e);let o=0;const s=this.getters.getEvaluatedCell(e).formattedValue;if(s){const e=sa(this.ctx,s,t,void 0);o+=Math.max(...e.map((e=>Yr(this.ctx,e,t))))}if(this.getters.getCellIconSrc(e)&&(o+=function(e){return ta(e)+8}(t)),this.getters.doesCellHaveGridIcon(e)&&(o+=20),0===o)return 0;if(o+=2*re,"wrap"===t.wrapping){const t=this.getters.getColSize(this.getters.getActiveSheetId(),e.col);return Math.min(t,o)}return o}getCellIconSrc(e){const t=yy.getAll();for(const o of t){const t=o(this.getters,e);if(t)return t}}getTextWidth(e,t){return Yr(this.ctx,e,t)}getCellText(e,t){const o=this.getters.getCell(e),s=this.getters.getLocale();if(t?.showFormula&&o?.isFormula)return Na(o.content,s);if(t?.showFormula&&!o?.content)return"";{const i=this.getters.getEvaluatedCell(e),n=t?.availableWidth?{availableWidth:t.availableWidth,measureText:e=>Yr(this.ctx,e,o?.style||{})}:void 0;return Qn(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 sa(this.ctx,s,o,t.wrapText?t.maxWidth:void 0)}doesCellHaveGridIcon(e){const t=this.getters.isFilterHeader(e),o=!this.getters.isReadonly()&&this.getters.cellHasListDataValidationIcon(e);return t||o}getContiguousZone(e,t){const o=t=>{for(const o of Ze(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 Ze(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);rs(i,e)||(s=!0,i=e)}while(s);return i}isCellEmpty(e){const t=this.getters.getMainCellPosition(e);return this.getters.getEvaluatedCell(t).type===ri.empty}getColMaxWidth(e,t){const o=gs(this.getters.getColsZone(e,t,t)).map((t=>this.getCellWidth({sheetId:e,...t})));return Math.max(0,Dt(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"}}).add("ui_options",class extends $P{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 $P{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:qe(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=-1===e.row?this.lastCellSelected.row:qe(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();break;case"AUTOFILL_CELL":this.autoFillMerge(e.originCol,e.originRow,e.col,e.row);const t=this.getters.getActiveSheetId();this.dispatch("UPDATE_CELL",{sheetId:t,col:e.col,row:e.row,style:e.style||null,content:e.content||"",format:e.format||""}),this.dispatch("SET_BORDER",{sheetId:t,col:e.col,row:e.row,border:e.border}),this.autofillCF(e.originCol,e.originRow,e.col,e.row),this.autofillDV(e.originCol,e.originRow,e.col,e.row)}}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;switch(this.direction){case"down":for(let s=t.left;s<=t.right;s++){const i=[];for(let e=t.top;e<=t.bottom;e++)i.push(Co(s,e));const n=this.createGenerator(i);for(let t=o.top;t<=o.bottom;t++)this.computeNewCell(n,s,t,e)}break;case"up":for(let s=t.left;s<=t.right;s++){const i=[];for(let e=t.bottom;e>=t.top;e--)i.push(Co(s,e));const n=this.createGenerator(i);for(let t=o.bottom;t>=o.top;t--)this.computeNewCell(n,s,t,e)}break;case"left":for(let s=t.top;s<=t.bottom;s++){const i=[];for(let e=t.right;e>=t.left;e--)i.push(Co(e,s));const n=this.createGenerator(i);for(let t=o.right;t>=o.left;t--)this.computeNewCell(n,t,s,e)}break;case"right":for(let s=t.top;s<=t.bottom;s++){const i=[];for(let e=t.left;e<=t.right;e++)i.push(Co(e,s));const n=this.createGenerator(i);for(let t=o.left;t<=o.right;t++)this.computeNewCell(n,t,s,e)}}e&&(this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0)}select(e,t){const o=this.getters.getSelectedZone();if(ls(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!==ri.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!==ri.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!==ri.empty;)s+=1,e={sheetId:t,col:o+1,row:s}}return s-1}computeNewCell(e,t,o,s){const{cellData:i,tooltip:n,origin:r}=e.next(),{content:a,style:l,border:c,format:h}=i;this.tooltip=n,s&&this.dispatch("AUTOFILL_CELL",{originCol:r.col,originRow:r.row,col:t,row:o,content:a,style:l,border:c,format:h})}getRule(e,t){const o=TS.getAll().sort(((e,t)=>e.sequence-t.sequence)).find((o=>o.condition(e,t)));return o&&o.generateRule(e,t)}createGenerator(e){const t=[],o=[],s=this.getters.getActiveSheetId();for(let t of e){const{col:e,row:i}=yo(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(let 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 WP(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,o,s){const i=this.getters.getActiveSheetId(),n={sheetId:i,col:o,row:s},r={sheetId:i,col:e,row:t};if(this.getters.isInMerge(n)&&!this.getters.isInMerge(r)){const e=this.getters.getMerge(n);e&&this.dispatch("REMOVE_MERGE",{sheetId:i,target:[e]})}const a=this.getters.getMerge(r);a?.left===e&&a?.top===t&&this.dispatch("ADD_MERGE",{sheetId:i,target:[{top:s,bottom:s+a.bottom-a.top,left:o,right:o+a.right-a.left}]})}autofillCF(e,t,o,s){const i=this.getters.getActiveSheetId(),n=this.getters.getRulesByCell(i,e,t);for(const e of n){const t=this.getters.getAdaptedCfRanges(i,e,[vs({col:o,row:s})],[]);t&&this.dispatch("ADD_CONDITIONAL_FORMAT",{cf:Be(e),ranges:t,sheetId:i})}}autofillDV(e,t,o,s){const i=this.getters.getActiveSheetId(),n={sheetId:i,col:e,row:t},r=this.getters.getValidationRuleForCell(n);if(!r)return;const a=r.ranges.map((e=>e.zone)),l=wo(a.concat(vs({col:o,row:s})),[]);this.dispatch("ADD_DATA_VALIDATION_RULE",{rule:r,ranges:l.map((e=>this.getters.getRangeDataFromZone(i,e))),sheetId:i})}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 $P{allowDispatch(e){return"SORT_CELLS"===e.type?ls(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 gs(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=>as(e,t))),s=hs(o[0]);let[i,n]=[s.numberOfCols,s.numberOfRows];return o.every((e=>{let[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 gs(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]===ri.empty&&(o=o.slice(1)),!o.some((e=>e[0]===ri.empty))&&!!o.some((e=>e[1]!==ri.empty&&e[0]!==e[1]))}sortZone(e,t,o,s,i){const[n,r]=this.mainCellsSteps(e,o);let a=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,l=Object.assign({},o),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===ri.empty?{...e,type:ri.number,value:0}:e)):s).sort(_p(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++){let{col:o,row:s,sheetId:i}=c[e][d[t]];const a=this.getters.getCell({sheetId:i,col:o,row:s});let 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=Ze(t.left,t.right+1,o),r=Ze(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 $P{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}=ls(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)||ds(is(n,t))?[{position:{col:s,row:i},zone:n}]:this.sumDimensions(e,is(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=Ze(o,-1,-1),n=Dt(i.filter((e=>s[e]&&!s[e].isAutoSummable))),r=je(i.filter((e=>this.isNumber(s[e]))))[0]||[];return Dt(r)<n?1/0:Ot(r)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===ri.number&&!(e.format&&ar(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 ds(t)?(o.add(1===hs(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)},gs(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)},gs(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 $P{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 wo(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=wo(s.map(vs));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:wo(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 wo(t))for(const t of gs(i)){const i=this.getCellNumberFormat({sheetId:e,...t});if(void 0!==i){const e=wr(i,o);s[e]=s[e]||[],s[e].push(t)}}for(const t in s){const o=wo(s[t].map((e=>vs(e))));this.setContextualFormat(e,o,t)}}getCellNumberFormat(e){for(const t of[e]){const e=this.getters.getEvaluatedCell(t);if(!(e.type!==ri.number||e.format&&ar(e.format)))return e.format||hr(e.value)}}}).add("insert_pivot",class extends $P{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===ys(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:Mo("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:Mo("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.getTableStructure().export(),"dynamic")}duplicatePivotInNewSheet(e,t,o){this.dispatch("DUPLICATE_PIVOT",{pivotId:e,newPivotId:t,duplicatedPivotName:Mo("%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(Mo("%(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.getTableStructure().export(),"dynamic")}}getPivotDuplicateSheetName(e){const t=this.getters.getSheetIds().map((e=>this.getters.getSheetName(e)));return Nt(Ge(e),t)}insertPivotWithTable(e,t,o,s,i,n){const{cols:r,rows:a,measures:l,fieldsType:c}=i,h=new iF(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:{...ke,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,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,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:Ql(n,t)});const a=this.getters.getCoreTable({sheetId:e,col:t,row:o});if("dynamic"===a?.type){const s=vs({col:t,row:o}),n=this.getters.getRangeDataFromZone(e,i);this.dispatch("UPDATE_TABLE",{sheetId:e,zone:s,newTableRange:n,tableType:"static"})}}}).add("split_to_columns",class extends $P{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===ri.text){const e=this.getAutoSeparatorForString(t.value);if(e)return e}return" "}getAutoSeparatorForString(e){const t=[Pe,";",","," ","."];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:Oa(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 Ze(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 Ze(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 Ze(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,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,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 $P{static getters=["getClientsToDisplay","getClient","getConnectedClients","isFullySynchronized"];static layers=["Selection"];availableColors=new go(12);colors={};session;constructor(e){super(e),this.session=e.session}isPositionValid(e){return e.row<this.getters.getNumberRows(e.sheetId)&&e.col<this.getters.getNumberCols(e.sheetId)}getClient(){return this.session.getClient()}getConnectedClients(){return this.session.getConnectedClients()}isFullySynchronized(){return this.session.isFullySynchronized()}getClientsToDisplay(){try{this.getters.getClient()}catch(e){if(e instanceof oN)return[];throw e}const e=this.getters.getActiveSheetId(),t=[];for(const o of this.getters.getConnectedClients())if(o.id!==this.getters.getClient().id&&o.position&&o.position.sheetId===e&&this.isPositionValid(o.position)){const e=o.position;this.colors[o.id]||(this.colors[o.id]=this.availableColors.next());const s=this.colors[o.id];t.push({...o,position:e,color:s})}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 $P{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=vN(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)&&(mi(t.rootCommand)?pN.contains(t.rootCommand.type):mN.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 $P{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===hs(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 cc(this.getters,this.dispatch),l=a.copy(ca(o,r));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 Ze(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:Mo("%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=wo(this.getters.getSelectedZones()),t=this.getters.getActiveSheetId();let o=0;for(const{col:s,row:i}of e.map(gs).flat()){const e=this.getters.getCell({col:s,row:i,sheetId:t});if(!e)continue;const n=Tt(e.content);n!==e.content&&(o+=1,this.dispatch("UPDATE_CELL",{sheetId:t,col:s,row:i,content:n}))}const s=o?Mo("Trimmed whitespace from %s cells.",o):Mo("No selected cells had whitespace trimmed.");this.ui.notifyUI({type:"info",text:s,sticky:!1})}}).add("table_autofill",class extends $P{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&&ls(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!==ri.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 $P{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 $P{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 Br(t)){const t=this.getters.getCell(e),o=this.getters.getEvaluatedCell(e);if(t?.content)if(t?.content&&o.type===ri.empty){let o;if(t.content.startsWith("=")){const s=this.getters.evaluateFormula(e.sheetId,t.content);o=(wi(s)?s[0][0]:s)?.toString()}else o=t.content;o&&Xe(o)||this.dispatch("UPDATE_CELL",{...e,content:"FALSE"})}else o.type!==ri.boolean&&this.dispatch("UPDATE_CELL",{...e,content:"FALSE"});else this.dispatch("UPDATE_CELL",{...e,content:"FALSE"})}}}}).add("geo_features",class extends $P{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")}}),CN=(new n).add("selection",class extends $P{static layers=["Selection"];static getters=["getActiveSheet","getActiveSheetId","getActiveCell","getActiveCols","getActiveRows","getCurrentStyle","getSelectedZones","getSelectedZone","getSelectedCells","getSelectedFigureId","getSelection","getActivePosition","getSheetPosition","isSingleColSelected","getElementsFromSelection","tryGetActiveSheetId","isGridSelectionActive"];gridSelection={anchor:{cell:{col:0,row:0},zone:{top:0,left:0,bottom:0,right:0}},zones:[{top:0,left:0,bottom:0,right:0}]};selectedFigureId=null;sheetsData={};moveClient;activeSheet=null;constructor(e){super(e),this.moveClient=e.moveClient}allowDispatch(e){switch(e.type){case"ACTIVATE_SHEET":try{if(!this.getters.getSheet(e.sheetIdTo).isVisible)return"SheetIsHidden";break}catch(e){return"InvalidSheetId"}case"MOVE_COLUMNS_ROWS":return this.isMoveElementAllowed(e)}return"Success"}handleEvent(e){const t=e.anchor;let o=[];switch(e.mode){case"overrideSelection":o=[t.zone];break;case"updateAnchor":o=[...this.gridSelection.zones];const s=o.findIndex((t=>rs(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,Be(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.id&&(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.id;break;case"ACTIVATE_NEXT_SHEET":this.activateNextSheet("right");break;case"ACTIVATE_PREVIOUS_SHEET":this.activateNextSheet("left");break;case"HIDE_SHEET":e.sheetId===this.getActiveSheetId()&&this.dispatch("ACTIVATE_SHEET",{sheetIdFrom:e.sheetId,sheetIdTo:this.getters.getVisibleSheetIds()[0]});break;case"UNDO":case"REDO":case"DELETE_SHEET":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:Be(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,Be(this.gridSelection.anchor))}isGridSelectionActive(){return this.selection.isListening(this)}getActiveSheet(){return this.activeSheet}getActiveSheetId(){return this.activeSheet.id}tryGetActiveSheetId(){return this.activeSheet?.id}getActiveCell(){return this.getters.getEvaluatedCell(this.getActivePosition())}getActiveCols(){const e=new Set;for(let 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(let 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 Be(this.gridSelection.zones)}getSelectedZone(){return Be(this.gridSelection.anchor.zone)}getSelection(){return Be(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:Be(this.gridSelection)},t in this.sheetsData)Object.assign(this,this.sheetsData[t]),this.selection.resetDefaultAnchor(this,Be(this.gridSelection.anchor));else{const{col:e,row:o}=this.getters.getNextVisibleCellPosition({sheetId:t,col:0,row:0});this.selectCell(e,o)}}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=os(o,"left",[...e.elements]);let i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=os(i,"left",[...e.elements]);const n={cell:{col:i.left,row:i.top},zone:s},r=this.gridSelection.zones.map((t=>os(t,"left",[...e.elements])));this.setSelectionMixin(n,r)}onRowsRemoved(e){const{cell:t,zone:o}=this.gridSelection.anchor,s=os(o,"top",[...e.elements]);let i={left:t.col,right:t.col,top:t.row,bottom:t.row};i=os(i,"top",[...e.elements]);const n={cell:{col:i.left,row:i.top},zone:s},r=this.gridSelection.zones.map((t=>os(t,"top",[...e.elements])));this.setSelectionMixin(n,r)}onAddElements(e){const t="COL"===e.dimension?"left":"top",o=ts(this.gridSelection.anchor.zone,t,e.base,e.position,e.quantity),s=this.gridSelection.zones.map((o=>ts(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;this.dispatch("ADD_COLUMNS_ROWS",{dimension:e.dimension,sheetId:e.sheetId,base:e.base,quantity:t,position:e.position});const o="COL"===e.dimension,s=e.elements[0],i=e.elements[t-1],n=e.base<s,r=n&&o?t:0,a=n&&!o?t:0,l=[{left:o?s+r:0,right:o?i+r:this.getters.getNumberCols(e.sheetId)-1,top:o?0:s+a,bottom:o?this.getters.getNumberRows(e.sheetId)-1:i+a}],c=this.getActiveSheetId(),h=new cc(this.getters,this.dispatch),d=h.copy(ca(c,l));if(!d)return;const u=n?e.base:e.base+1,g=[{left:o?u:0,right:o?u+t-1:this.getters.getNumberCols(e.sheetId)-1,top:o?0:u,bottom:o?this.getters.getNumberRows(e.sheetId)-1:u+t-1}];h.paste({zones:g,sheetId:c},d,{isCutOperation:!0});const p=g[0],m=p.left,f=p.top;this.setSelectionMixin({zone:p,cell:{col:m,row:f}},[p]);const v=n?e.elements.map((e=>e+t)):e.elements;let b=n?e.base:e.base+1;const S={};for(const t of v){const o=this.getters.getHeaderSize(e.sheetId,e.dimension,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,elements:v})}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":"Success"}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:qe(e.left,0,o),right:qe(e.right,0,o),top:qe(e.top,0,s),bottom:qe(e.bottom,0,s)}))),anchor:{cell:{col:qe(t.anchor.cell.col,0,o),row:qe(t.anchor.cell.row,0,s)},zone:{left:qe(t.anchor.zone.left,0,o),right:qe(t.anchor.zone.right,0,o),top:qe(t.anchor.zone.top,0,s),bottom:qe(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):vs(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 $P{static getters=["getFilterHiddenValues","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]=Be(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)}getFilterHiddenValues(e){const t=this.getters.getFilterId(e),o=e.sheetId;return t&&this.filterValues[o]&&this.filterValues[o][t]||[]}isFilterActive(e){const t=this.getters.getFilterId(e),o=e.sheetId;return Boolean(t&&this.filterValues[o]?.[t]?.length)}getFirstTableInSelection(){const e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZones();return this.getters.getTablesOverlappingZones(e,t)[0]}updateFilter({col:e,row:t,hiddenValues: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(let s of t){if(o.has(s.rangeWithHeaders.zone.top)||this.getters.isRowHiddenByUser(e,s.rangeWithHeaders.zone.top))continue;const t=this.filterValues[e]?.[s.id]?.map(ia),i=s.filteredRange?.zone;if(t&&i)for(let n=i.top;n<=i.bottom;n++){const i=this.getCellValueAsString(e,s.col,n);t.includes(i)&&o.add(n)}}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=Xo(o.range),i=[],n=[];for(const o of Ze(0,hs(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?gs(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=Co(r.col,r.row);t.cells[u]=d,t.cellValues[u]=d}o.filters=i}}}getUniqueColNameForExcel(e,t,o){return t||(t=`Column${e}`),Nt(t,o,{compute:(e,o)=>t+String(o),start:2})}}).add("header_visibility_ui",class extends $P{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 Ze(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 $P{static getters=["getCellComputedBorder","getCellComputedStyle"];styles={};borders={};handle(e){if(li.has(e.type)||"UPDATE_CELL"===e.type||"SET_FORMATTING"===e.type||"EVALUATE_CELLS"===e.type)return this.styles={},void(this.borders={});nN(e)?"sheetId"in e?(delete this.styles[e.sheetId],delete this.borders[e.sheetId]):(this.styles={},this.borders={}):di.has(e.type)?this.styles={}:ui.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={...bt(this.getters.getCellTableStyle(e)),...bt(t?.style),...bt(o)};return this.getters.getEvaluatedCell(e).link&&!s.textColor&&(s.textColor=b),s}}).add("table_computed_style",class extends $P{static getters=["getCellTableStyle","getCellTableBorder"];tableStyles={};handle(e){li.has(e.type)||"UPDATE_CELL"===e.type&&"content"in e||"EVALUATE_CELLS"===e.type?this.tableStyles={}:nN(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=OF(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 $P{static getters=["getColDimensions","getRowDimensions","getColRowOffset"];headerPositions={};isDirty=!0;handle(e){switch(li.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]=Be(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 $P{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"];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}=fs(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(li.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":this.sheetsWithDirtyViewports.add(e.sheetId);break;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":{const t="sheetId"in e?e.sheetId:this.getters.getActiveSheetId();this.sheetsWithDirtyViewports.add(t);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"UNFREEZE_ROWS":case"UNFREEZE_COLUMNS":case"FREEZE_COLUMNS":case"FREEZE_ROWS":case"UNFREEZE_COLUMNS_ROWS":this.resetViewports(this.getters.getActiveSheetId());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}}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=>Ze(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=>Ze(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);let{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+1),maxOffsetY:Math.max(0,o-s.viewportHeight+1)}}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)),r=i.findIndex((e=>o<=e)),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=kr(e-a),i=1):e<l&&o>=l&&c>0?(s=!0,n=kr(l-e),i=-1):r&&t<l&&e>l&&(s=!0,n=kr(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=kr(e-a),i=1):e<l&&o>=l&&c>0?(s=!0,n=kr(l-e),i=-1):r&&t<l&&e>l&&(s=!0,n=kr(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}}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 o={left:t,right:t,top:0,bottom:this.getters.getNumberRows(e)-1},{x:s,width:i}=this.getVisibleRect(o),n=s-this.gridOffsetX;return{start:n,size:i,end:n+i}}getRowDimensionsInViewport(e,t){const o={left:0,right:this.getters.getNumberCols(e)-1,top:t,bottom:t},{y:s,height:i}=this.getVisibleRect(o),n=s-this.gridOffsetY;return{start:n,size:i,end:n+i}}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(at)}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(qe(e,0,s),qe(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(qe(e,0,s),qe(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 bN(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 bN(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 bN(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 bN(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)}}getVisibleFigures(){const e=this.getters.getActiveSheetId(),t=[],o=this.getters.getFigures(e),{scrollX:s,scrollY:i}=this.getActiveSheetScrollInfo(),{x:n,y:r}=this.getters.getMainViewportCoordinates(),{width:a,height:l}=this.getters.getSheetViewDimensionWithHeaders();for(const e of o)e.x>=n&&(e.x+e.width<=n+s||e.x>=a+s+n)||e.y>=r&&(e.y+e.height<=r+i||e.y>=l+i+r)||t.push(e);return t}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 $P{static layers=["Clipboard"];static getters=["getClipboardContent","getClipboardId","getClipboardTextContent","isCutOperation"];status="invisible";originSheetId;copiedData;_isCutOperation=!1;clipboardId=(new la).uuidv4();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);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);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.copiedData=this.copy(t),this._isCutOperation="CUT"===e.type;break;case"PASTE_FROM_OS_CLIPBOARD":{this._isCutOperation=!1,this.copiedData=e.clipboardContent.data||this.convertTextToClipboardData(e.clipboardContent.text??"");const t=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:t,selectTarget:!0,isCutOperation:!1}),this.status="invisible";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(!Ko(t[0])){this.dispatch("CLEAR_CELLS",{target:[e.zone],sheetId:this.getters.getActiveSheetId()});break}const s=this.copy(t);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);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(let t of e.elements){if(this.isColRowDirtyingClipboard(t,e.dimension)){this.copiedData=void 0;break}}this.status="invisible";break;case"REPEAT_PASTE":this.paste(e.target,this.copiedData,{isCutOperation:!1,pasteOption:e.pasteOption,selectTarget:!0});break;case"DELETE_SHEET":if(!this._isCutOperation)return;this.originSheetId===e.sheetId&&(this.copiedData=void 0,this.status="invisible");break;default:mi(e)&&(this.status="invisible")}}convertTextToClipboardData(e){const t=this.selectClipboardHandlers({figureId:!0}).concat(this.selectClipboardHandlers({}));let 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?gc.figureHandlers:gc.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(let s of o){if("COL"===t&&e<=s.right)return!0;if("ROW"===t&&e<=s.bottom)return!0}return!1}copy(e){let t={};const o=this.getClipboardData(e);for(const{handlerName:e,handler:s}of this.selectClipboardHandlers(o)){const i=s.copy(o);t[e]=i;const n=["sheetId","cells","zones","figureId"];for(const e of n)i&&e in i&&(t[e]=i[e])}return t}paste(e,t,o){if(!t)return;let s,i=[];const n=this.getters.getActiveSheetId();let r={sheetId:n,zones:e};const a=this.selectClipboardHandlers(t);for(const{handlerName:l,handler:c}of a){const a=t[l];if(!a)continue;const h=c.getPasteTarget(n,e,a,o);h.figureId&&(r.figureId=h.figureId);for(const e of h.zones)i.push(e),s=void 0!==s?is(s,e):e}if(void 0!==s&&this.addMissingDimensions(this.getters.getActiveSheetId(),s.right-s.left+1,s.bottom-s.top+1,s.left,s.top),a.forEach((({handlerName:e,handler:s})=>{const i=t[e];i&&s.paste(r,i,o)})),!o?.selectTarget)return;const l=e[0],c=l.left,h=l.top;this.selection.getBackToDefault(),this.selection.selectZone({cell:{col:c,row:h},zone:is(...i)},{scrollIntoView:!1})}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,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,quantity:r,position:"after"})}getClipboardTextContent(){return this.getPlainTextContent()}getClipboardId(){return this.clipboardId}getClipboardContent(){return{[ai.PlainText]:this.getPlainTextContent(),[ai.Html]:this.getHTMLContent()}}getSheetData(){const e={version:tE,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"}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="${Lc(kc(this.getters.getCellComputedStyle(t.position)))}">`+Iw(this.getters.getCellText(t.position))+"</td>"}o+="</tr>"}o+="</table>",e=o}}else e="\t";return`<div data-osheet-clipboard='${Iw(JSON.stringify(this.getSheetData()))}'>${e}</div>`}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();return o?{figureId:o,sheetId:t}:ca(t,e)}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)}}}),wN=(new n).add("evaluation",class extends tP{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 MP(e.custom,this.getters)}beforeHandle(e){(li.has(e.type)||hi.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 wi(o)?ln(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 gs(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 gs(t).map((({col:t,row:o})=>this.getEvaluatedCell({sheetId:e,col:t,row:o}))).every((e=>e.type===ri.empty))}mapVisiblePositions(e,t){const{sheetId:o,zone:s}=e;return gs(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={};for(const t of this.evaluator.getEvaluatedPositions()){const o=this.evaluator.getEvaluatedCell(t),s=Co(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&&(a=fS(c.compiledFormula.tokens),r=a,!a&&""!==i)){n=(i??"").toString();const t=o.format;if(t){const o=Es(t,e.formats);l.formats[s]=o}}const h=l.cells[s];let d;d=a&&r&&c instanceof jM?c.contentWithFixedReferences:a?h:n,l.cells[s]=d,l.cellValues[s]=i}}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 tP{static getters=["getChartRuntime","getStyleOfSingleCellChart"];charts={};createRuntimeChart=SR(this.getters);handle(e){if(li.has(e.type)||di.has(e.type)||ci.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.id]=void 0;break;case"DELETE_SHEET":for(let 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:jc(e)};if(!t)return{background:m,fontColor:jc(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||jc(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=JS(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 tP{static getters=["getConditionalIcon","getCellConditionalFormatStyle","getConditionalDataBar"];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(li.has(e.type)||di.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(let o of this.getters.getConditionalFormats(e).reverse())switch(o.rule.type){case"ColorScaleRule":for(let s of o.ranges)this.applyColorScale(e,s,o.rule,t);break;case"CellIsRule":const s=o.rule.values.map((e=>e.startsWith("=")?uS(e):void 0));for(let 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=this.rulePredicate[o.rule.type],l={sheetId:e,col:r,row:i},c=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}));a&&a(l,{...o.rule,values:c})&&(t[r]||(t[r]=[]),t[r][i]=Object.assign(t[r]?.[i]||{},o.rule.style))}}}return t}getComputedIcons(e){const t={};for(let o of this.getters.getConditionalFormats(e).reverse())if("IconSetRule"===o.rule.type)for(let s of o.ranges)this.applyIcon(e,s,o.rule,t);return t}getComputedDataBars(e){const t={};for(let o of this.getters.getConditionalFormats(e).reverse())if("DataBarRule"===o.rule.type)for(let 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===ri.number)).map((e=>e.value));switch(o.type){case"value":return"max"===s?Dt(i):Ot(i);case"number":return Number(o.value);case"percentage":const t=Ot(i);return t+(Dt(i)-t)*Number(o.value)/100;case"percentile":return ni(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!==ri.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=Dt(this.getters.getEvaluatedCellsInZone(e,i.zone).filter((e=>e.type===ri.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});!ls(i,c,l)||h.type!==ri.number||h.value<=0||(s[o]||(s[o]=[]),s[o][t]={color:Ht(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=po(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===ri.number){const e=qe(n.value,i,r);s[o]||(s[o]=[]),s[o][t]=s[o]?.[t]||{},s[o][t].fillColor=c(e)}}}rulePredicate={CellIsRule:(e,t)=>{const o=this.getters.getEvaluatedCell(e);if(o.type===ri.error)return!1;let[s,i]=t.values.map((t=>t.startsWith("=")?this.getters.evaluateFormula(e.sheetId,t)??"":Tr(t,yi)));if(wi(s)||wi(i))return!1;const n=o.value??"";switch(s=s??"",i=i??"",t.operator){case"IsEmpty":return""===n.toString().trim();case"IsNotEmpty":return""!==n.toString().trim();case"BeginsWith":return""!==s&&n.toString().startsWith(s.toString());case"EndsWith":return""!==s&&n.toString().endsWith(s.toString());case"Between":return n>=s&&n<=i;case"NotBetween":return!(n>=s&&n<=i);case"ContainsText":return n.toString().indexOf(s.toString())>-1;case"NotContains":return!n||-1===n.toString().indexOf(s.toString());case"GreaterThan":return n>s;case"GreaterThanOrEqual":return n>=s;case"LessThan":return n<s;case"LessThanOrEqual":return n<=s;case"NotEqual":return""!==s&&n!==s;case"Equal":return""===s||n===s;default:console.warn(Mo("Not implemented operator %s for kind of conditional formatting: %s",t.operator,t.type))}return!1}}}).add("row_size",class extends tP{static getters=["getRowSize","getHeaderSize"];tallestCellInRow={};ctx=document.createElement("canvas").getContext("2d");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=Be(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=It(this.tallestCellInRow[e.sheetId],e.elements);this.history.update("tallestCellInRow",e.sheetId,t);break}case"ADD_COLUMNS_ROWS":{if("COL"===e.dimension)return;const t=pt(e.position,e.base),o=Array(e.quantity).fill(void 0),s=Rt(this.tallestCellInRow[e.sheetId],o,t);this.history.update("tallestCellInRow",e.sheetId,s);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 Ze(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 gs(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??se)}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<=se)&&(!s&&i>se||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 se;const t=this.getters.getCell(e),o=this.getters.getColSize(e.sheetId,e.col);return function(e,t,o){if(!t||!t.isFormula&&!t.content)return se;const s="wrap"===t.style?.wrapping?o-2*ne:void 0,i=t.isFormula?1:sa(e,t.content,t.style,s).length;return qr(ta(t.style),i)+6}(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>se&&(i=r,s={cell:n,size:r})}return s&&s.size>se?s:void 0}}).add("data_validation_ui",class extends tP{static getters=["getDataValidationInvalidCriterionValueMessage","getInvalidDataValidationMessage","getValidationResultForCellValue","isCellValidCheckbox","isDataValidationInvalid"];validationResults={};handle(e){if(li.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}getInvalidDataValidationMessage(e){const t=this.getValidationResultForCell(e);return t.isValid?void 0:t.error}getDataValidationInvalidCriterionValueMessage(e,t){const o=vO.get(e);return t.startsWith("=")?"onlyLiterals"===o.allowedValues?Mo("The value must not be a formula"):this.isValidFormula(t)?void 0:yE.CriterionError.validFormula:"onlyFormulas"===o.allowedValues?Mo("The value must be a formula"):o.isCriterionValueValid(t)?void 0:o.criterionValueErrorString}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 VP;const s=this.getRuleErrorForCellValue(e,t,o);return s?{error:s,rule:o,isValid:!1}:VP}isValidFormula(e){return!uS(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]?.()||VP}computeSheetValidationResults(e){const t={},o=this.getters.getDataValidationRules(e).map((e=>e.ranges));for(const e of Br(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===ri.empty?VP:this.getValidationResultForCellValue(t.value,e)}))}return t}getRuleErrorForCellValue(e,t,o){const{sheetId:s}=t,i=o.criterion,n=vO.get(i.type),r=this.getCellOffsetInRule(t,o),a=this.getEvaluatedCriterionValues(s,r,i),l={...i,values:a};if(!n.isValueValid(e,l,this.getters,s))return n.getErrorString(l,this.getters,s)}getCellOffsetInRule(e,t){const o=t.ranges.find((t=>ls(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 o;const s=uS(o),i=this.getters.getTranslatedCellFormula(e,t.col,t.row,s.tokens),n=this.getters.evaluateFormula(e,i);return n&&!wi(n)?n.toString():""}))}}).add("dynamic_tables",class extends tP{static getters=["canCreateDynamicTableOnZones","doesZonesContainFilter","getFilter","getFilters","getTable","getTables","getTablesOverlappingZones","getFilterId","getFilterHeaders","isFilterHeader"];tables={};handle(e){if(li.has(e.type)||"UPDATE_CELL"===e.type&&"content"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)as(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=>ls(t,o,e.range.zone)))}getTablesOverlappingZones(e,t){return this.getTables(e).filter((e=>t.some((t=>as(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(!Cs(t))return!1;const o=is(...t),s={col:o.left,row:o.top,sheetId:e},i=this.getters.getArrayFormulaSpreadingOn(s);if(!i)return!1;if(mt(i,s)&&1===ys(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=_F(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=Xo(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=Qo(n.range.zone))}}}).add("custom_colors",class extends tP{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.id));break;case"UPDATE_CELL":case"ADD_CONDITIONAL_FORMAT":case"SET_BORDER":case"SET_ZONE_BORDERS":case"SET_FORMATTING":case"CREATE_TABLE":case"UPDATE_TABLE":this.history.update("shouldUpdateColors",!0)}}finalize(){this.shouldUpdateColors&&(this.history.update("shouldUpdateColors",!1),this.tryToAddColors(this.computeCustomColors()))}getCustomColors(){return function(e){const t=[{leadColor:Gt(255,0,0),colors:[]},{leadColor:Gt(255,128,0),colors:[]},{leadColor:Gt(128,128,0),colors:[]},{leadColor:Gt(128,255,0),colors:[]},{leadColor:Gt(0,255,0),colors:[]},{leadColor:Gt(0,255,128),colors:[]},{leadColor:Gt(0,255,255),colors:[]},{leadColor:Gt(0,127,255),colors:[]},{leadColor:Gt(0,0,255),colors:[]},{leadColor:Gt(127,0,255),colors:[]},{leadColor:Gt(128,0,128),colors:[]},{leadColor:Gt(255,0,128),colors:[]}];for(const o of e.map(jt)){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)=>Xt(e).s-Xt(t).s)))).flat().map(Zt)}(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(Ht(t.minimum.color)),o.push(t.midpoint?Ht(t.midpoint.color):void 0),o.push(Ht(t.maximum.color)))}return o.filter(at)}getChartColors(e){const t=this.getters.getChart(e);if(void 0===t)return[];return[...JSON.stringify(t.getDefinition()).matchAll(LP)].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(at):[]}tryToAddColors(e){for(const t of e){if(!$t(t))continue;const e=zt(t);t&&!Q.includes(e)&&this.history.update("customColors",e,!0)}}}).add("pivot_ui",class extends tP{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(li.has(e.type))for(const e of this.getters.getPivotIds())fF.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(zP);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 pF)pF[e].set.clear(),pF[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=ES(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=Nf(t);return this.getters.evaluateFormula(e,o)}))}}getPivotCellFromPosition(e){const t=this.getters.getCorrespondingFormulaCell(e);if(!t||!t.isFormula||0===xS(t.compiledFormula.tokens))return nF;const o=this.getters.getCellPosition(t.id),s=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula.tokens);if(!s)return nF;const{functionName:i,args:n}=s,r=n[0];if(!r)return nF;const a=this.getters.getPivotId(r.toString());if(!a)return nF;const l=this.getPivot(a);if(!l.isValid())return nF;if("PIVOT"===i&&!t.content.replaceAll(" ","").toUpperCase().startsWith("=PIVOT"))return nF;if("PIVOT"===i){const t=Qa(n[2]),s=void 0===t||Xi(t),i=Qa(n[3]),r=void 0===i||Xi(i),a=l.getTableStructure().getPivotCells(s,r),c=e.col-o.col,h=e.row-o.row;return a[c][h]}try{if("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){return{type:"HEADER",domain:l.parseArgsToPivotDomain(n.slice(1).map((e=>({value:e}))))}}const[e,...t]=n.slice(1);return{type:"VALUE",domain:l.parseArgsToPivotDomain(t.map((e=>({value:e})))),measure:e?.toString()||""}}catch(e){return nF}}generateNewCalculatedMeasureName(e){const t=e.map((e=>e.fieldName));return Nt(Mo("Calculated measure 1"),t,{compute:(e,t)=>Mo("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=HP(fF.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}}),EN=new n;EN.add("link",{condition:(e,t)=>!!t.getEvaluatedCell(e).link,execute:(e,t,o)=>An(t.model.getters.getEvaluatedCell(e).link,t,o),sequence:5});class xN{fileStore;constructor(e){this.fileStore=e}async requestImage(){const e=await this.getImageFromUser(),t=await this.fileStore.upload(e);return{path:t,size:await this.getImageOriginalSize(t),mimetype:e.type}}getImageFromUser(){return new Promise(((e,t)=>{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.src=e,s.addEventListener("load",(()=>{const e={width:s.width,height:s.height};t(e)})),s.addEventListener("error",o)}))}}const IN=[{transform:"scale(0)"},{transform:"scale(0.8)",offset:.33},{opacity:"0",transform:"scale(1)",offset:1}];Pc`
|
|
1823
1823
|
.o-ripple {
|
|
1824
1824
|
z-index: 1;
|
|
1825
1825
|
}
|
|
1826
|
-
`;class
|
|
1826
|
+
`;class RN extends t.Component{static template="o-spreadsheet-RippleEffect";static props={x:String,y:String,color:String,opacity:Number,duration:Number,width:Number,height:Number,offsetY:Number,offsetX:Number,allowOverflow:Boolean,onAnimationEnd:Function,style:String};rippleRef=t.useRef("ripple");setup(){let e;t.onMounted((()=>{const t=this.rippleRef.el;t&&t.animate&&(e=t.animate(IN,{duration:this.props.duration,easing:"ease-out"}),e.addEventListener("finish",this.props.onAnimationEnd))})),t.onWillUnmount((()=>{e?.removeEventListener("finish",this.props.onAnimationEnd)}))}get rippleStyle(){const{x:e,y:t,width:o,height:s}=this.props;return Lc({transform:"scale(0)",left:e,top:t,"margin-left":`${-o/2+(this.props.offsetX||0)}px`,"margin-top":`${-s/2+(this.props.offsetY||0)}px`,width:`${o}px`,height:`${s}px`,background:this.props.color,"border-radius":"100%",opacity:`${this.props.opacity}`})}}class TN extends t.Component{static template="o-spreadsheet-Ripple";static props={color:{type:String,optional:!0},opacity:{type:Number,optional:!0},duration:{type:Number,optional:!0},ignoreClickPosition:{type:Boolean,optional:!0},width:{type:Number,optional:!0},height:{type:Number,optional:!0},offsetY:{type:Number,optional:!0},offsetX:{type:Number,optional:!0},allowOverflow:{type:Boolean,optional:!0},enabled:{type:Boolean,optional:!0},onAnimationEnd:{type:Function,optional:!0},slots:Object,class:{type:String,optional:!0}};static components={RippleEffect:RN};static defaultProps={color:"#aaaaaa",opacity:.4,duration:800,enabled:!0,onAnimationEnd:()=>{},class:""};childContainer=t.useRef("childContainer");state=t.useState({ripples:[]});currentId=1;onClick(e){if(!this.props.enabled)return;if(!this.childContainer.el)return;const t=this.getRippleChildRectInfo(),{x:o,y:s,width:i,height:n}=t,r=Math.max(i,n),a={x:e.clientX-o,y:e.clientY-s,width:this.props.width||2.85*r,height:this.props.height||2.85*r};this.state.ripples.push({rippleRect:a,id:this.currentId++})}getRippleStyle(){const e=this.childContainer.el;if(!e||1!==e.childElementCount||!e.firstElementChild)return"";const t=this.getRippleChildRectInfo();return Lc({top:t.marginTop+"px",left:t.marginLeft+"px",width:t.width+"px",height:t.height+"px"})}getRippleChildRectInfo(){const e=this.childContainer.el;if(!e)throw new Error("No child container element found");if(1!==e.childElementCount||!e.firstElementChild){return{...YI(e),marginLeft:0,marginTop:0}}const t=e.firstElementChild,o=function(e){const t=window.getComputedStyle(e);return{top:parseInt(t.marginTop,10)||0,bottom:parseInt(t.marginBottom,10)||0,left:parseInt(t.marginLeft,10)||0,right:parseInt(t.marginRight,10)||0}}(t);return{...YI(t),marginLeft:o.left,marginTop:o.top}}removeRipple(e){const t=this.state.ripples.findIndex((t=>t.id===e));-1!==t&&this.state.ripples.splice(t,1)}getRippleEffectProps(e){const t=this.state.ripples.find((t=>t.id===e))?.rippleRect;if(!t)throw new Error("Cannot find a ripple with the id "+e);return{color:this.props.color,opacity:this.props.opacity,duration:this.props.duration,x:this.props.ignoreClickPosition?"50%":t.x+"px",y:this.props.ignoreClickPosition?"50%":t.y+"px",width:t.width,height:t.height,offsetX:this.props.offsetX||0,offsetY:this.props.offsetY||0,allowOverflow:this.props.allowOverflow||!1,style:this.getRippleStyle(),onAnimationEnd:()=>this.removeRipple(e)}}}Pc`
|
|
1827
1827
|
.o-sheet {
|
|
1828
1828
|
padding: 0 15px;
|
|
1829
1829
|
padding-right: 10px;
|
|
@@ -1871,7 +1871,7 @@
|
|
|
1871
1871
|
width: calc(100% - 1px);
|
|
1872
1872
|
}
|
|
1873
1873
|
}
|
|
1874
|
-
`;class
|
|
1874
|
+
`;class AN extends t.Component{static template="o-spreadsheet-BottomBarSheet";static props={sheetId:String,openContextMenu:Function,style:{type:String,optional:!0},onMouseDown:{type:Function,optional:!0}};static components={Ripple:TN,ColorPicker:yD};static defaultProps={onMouseDown:()=>{},style:""};state=t.useState({isEditing:!1,pickerOpened:!1});sheetDivRef=t.useRef("sheetDiv");sheetNameRef=t.useRef("sheetNameSpan");editionState="initializing";DOMFocusableElementStore;setup(){t.onPatched((()=>{this.sheetNameRef.el&&this.state.isEditing&&"initializing"===this.editionState&&(this.editionState="editing",this.focusInputAndSelectContent())})),this.DOMFocusableElementStore=Cc(PD),t.useExternalListener(window,"click",(()=>this.state.pickerOpened=!1)),t.useEffect((e=>{this.props.sheetId===e&&this.scrollToSheet()}),(()=>[this.env.model.getters.getActiveSheetId()]))}focusInputAndSelectContent(){if(!this.state.isEditing||!this.sheetNameRef.el)return;this.sheetNameRef.el.focus();const e=window.getSelection();e&&this.sheetNameRef.el.firstChild&&e.setBaseAndExtent(this.sheetNameRef.el.firstChild,0,this.sheetNameRef.el.firstChild,this.sheetNameRef.el.textContent?.length||0)}scrollToSheet(){this.sheetDivRef.el?.scrollIntoView?.({behavior:"smooth",inline:"nearest"})}onFocusOut(){this.state.isEditing&&"initializing"!==this.editionState&&this.stopEdition()}onMouseDown(e){this.activateSheet(),this.props.onMouseDown(e)}activateSheet(){this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:this.env.model.getters.getActiveSheetId(),sheetIdTo:this.props.sheetId}),this.scrollToSheet()}onDblClick(){this.env.model.getters.isReadonly()||this.startEdition()}onKeyDown(e){this.state.isEditing&&("Enter"===e.key&&(e.preventDefault(),this.stopEdition(),this.DOMFocusableElementStore.focusableElement?.focus()),"Escape"===e.key&&(this.cancelEdition(),this.DOMFocusableElementStore.focusableElement?.focus()))}onMouseEventSheetName(e){this.state.isEditing&&e.stopPropagation()}startEdition(){this.state.isEditing=!0,this.editionState="initializing"}stopEdition(){const e=this.sheetNameRef.el;if(!this.state.isEditing||!e)return;this.state.isEditing=!1,this.editionState="initializing",e.blur();const t=this.getInputContent()||"";e.innerText=t,function(e,t,o,s){const i=e.model.dispatch("RENAME_SHEET",{sheetId:t,name:o});i.reasons.includes("MissingSheetName")?e.raiseError(Mo("The sheet name cannot be empty."),s):i.reasons.includes("DuplicatedSheetName")?e.raiseError(Mo("A sheet with the name %s already exists. Please select another name.",o),s):i.reasons.includes("ForbiddenCharactersInSheetName")&&e.raiseError(Mo("Some used characters are not allowed in a sheet name (Forbidden characters are %s).",Ae.join(" ")),s)}(this.env,this.props.sheetId,t,(()=>this.startEdition()))}cancelEdition(){this.state.isEditing=!1,this.editionState="initializing",this.sheetNameRef.el?.blur(),this.setInputContent(this.sheetName)}onIconClick(e){this.isSheetActive||this.activateSheet(),this.props.openContextMenu(this.contextMenuRegistry,e)}onContextMenu(e){this.isSheetActive||this.activateSheet(),this.props.openContextMenu(this.contextMenuRegistry,e)}getInputContent(){return this.sheetNameRef.el?.textContent}setInputContent(e){this.sheetNameRef.el&&(this.sheetNameRef.el.textContent=e)}onColorPicked(e){this.state.pickerOpened=!1,this.env.model.dispatch("COLOR_SHEET",{sheetId:this.props.sheetId,color:e})}get colorPickerAnchorRect(){return YI(this.sheetDivRef.el)}get contextMenuRegistry(){return function(e){const t=new xI;return t.add("delete",{...aR,sequence:10}).add("hide_sheet",{...gR,sequence:20}).add("duplicate",{...lR,sequence:30,separator:!0}).add("rename",{...cR(e),sequence:40}).add("change_color",{...hR(e),sequence:50,separator:!0}).add("move_right",{...dR,sequence:60}).add("move_left",{...uR,sequence:70}),t}({renameSheetCallback:()=>{this.scrollToSheet(),this.startEdition()},openSheetColorPickerCallback:()=>{this.state.pickerOpened=!0}})}get isSheetActive(){return this.env.model.getters.getActiveSheetId()===this.props.sheetId}get sheetName(){return this.env.model.getters.getSheetName(this.props.sheetId)}get sheetColorStyle(){return Lc({background:this.env.model.getters.getSheet(this.props.sheetId).color||""})}}const _N=[{name:Mo("Sum"),types:[ri.number],compute:(e,t)=>Za([[e]],t)},{name:Mo("Avg"),types:[ri.number],compute:(e,t)=>tl([[e]],t)},{name:Mo("Min"),types:[ri.number],compute:(e,t)=>nl([[e]],t).value},{name:Mo("Max"),types:[ri.number],compute:(e,t)=>il([[e]],t).value},{name:Mo("Count"),types:[ri.number,ri.text,ri.boolean,ri.error],compute:e=>sl([[e]])},{name:Mo("Count Numbers"),types:[ri.number,ri.text,ri.boolean,ri.error],compute:(e,t)=>ol([[e]],t)}];class DN extends _c{statisticFnResults=this._computeStatisticFnResults();isDirty=!1;constructor(e){super(e),this.model.selection.observe(this,{handleEvent:this.handleEvent.bind(this)})}handle(e){switch((li.has(e.type)||"UPDATE_CELL"===e.type&&"content"in e)&&(this.isDirty=!0),e.type){case"HIDE_COLUMNS_ROWS":case"UNHIDE_COLUMNS_ROWS":case"GROUP_HEADERS":case"UNGROUP_HEADERS":case"ACTIVATE_SHEET":case"ACTIVATE_NEXT_SHEET":case"ACTIVATE_PREVIOUS_SHEET":case"EVALUATE_CELLS":case"UNDO":case"REDO":this.isDirty=!0}}finalize(){this.isDirty&&(this.isDirty=!1,this.statisticFnResults=this._computeStatisticFnResults())}handleEvent(){this.getters.isGridSelectionActive()&&(this.statisticFnResults=this._computeStatisticFnResults())}_computeStatisticFnResults(){const e=this.getters,t=e.getActiveSheetId(),o=[],s=wo(e.getSelectedZones(),[]),i=this.getters.getSheetSize(t).numberOfRows-1,n=this.getters.getSheetSize(t).numberOfCols-1;for(const r of s)for(let s=r.left;s<=(r.right??n);s++)for(let n=r.top;n<=(r.bottom??i);n++){if(e.isRowHidden(t,n)||e.isColHidden(t,s))continue;const i=e.getEvaluatedCell({sheetId:t,col:s,row:n});i.type!==ri.empty&&o.push(i)}const r=e.getLocale();let a={};const l=xt((e=>{const t=e.split(",");return o.filter((e=>t.includes(e.type)))}));for(let e of _N){let t;const o=l(e.types.sort().join(","));o.length&&(t=ut((()=>e.compute(o,r)))),a[e.name]=t}return a}}Pc`
|
|
1875
1875
|
.o-selection-statistic {
|
|
1876
1876
|
margin-right: 20px;
|
|
1877
1877
|
padding: 4px 4px 4px 8px;
|
|
@@ -1881,7 +1881,7 @@
|
|
|
1881
1881
|
background-color: rgba(0, 0, 0, 0.08) !important;
|
|
1882
1882
|
}
|
|
1883
1883
|
}
|
|
1884
|
-
`;class
|
|
1884
|
+
`;class ON extends t.Component{static template="o-spreadsheet-BottomBarStatistic";static props={openContextMenu:Function,closeContextMenu:Function};static components={Ripple:TN};selectedStatisticFn="";store;setup(){this.store=Cc(DN),t.onWillUpdateProps((()=>{Object.values(this.store.statisticFnResults).every((e=>void 0===e))&&this.props.closeContextMenu()}))}getSelectedStatistic(){if(!Object.values(this.store.statisticFnResults).every((e=>void 0===e)))return""===this.selectedStatisticFn&&(this.selectedStatisticFn=Object.keys(this.store.statisticFnResults)[0]),this.getComposedFnName(this.selectedStatisticFn)}listSelectionStatistics(e){const t=new xI;let o=0;for(let[e]of Object.entries(this.store.statisticFnResults))t.add(e,{name:()=>this.getComposedFnName(e),sequence:o,isReadonlyAllowed:!0,execute:()=>{this.selectedStatisticFn=e}}),o++;const s=e.currentTarget,{top:i,left:n,width:r}=s.getBoundingClientRect();this.props.openContextMenu(n+r,i,t)}getComposedFnName(e){const t=this.env.model.getters.getLocale(),o=this.store.statisticFnResults[e];return e+": "+(void 0!==o?Qn(o(),{locale:t}):"__")}}Pc`
|
|
1885
1885
|
.o-spreadsheet-bottom-bar {
|
|
1886
1886
|
background-color: ${l};
|
|
1887
1887
|
padding-left: ${te}px;
|
|
@@ -1934,12 +1934,12 @@
|
|
|
1934
1934
|
}
|
|
1935
1935
|
}
|
|
1936
1936
|
}
|
|
1937
|
-
`;class
|
|
1937
|
+
`;class FN extends t.Component{static template="o-spreadsheet-BottomBar";static props={onClick:Function};static components={Menu:mR,Ripple:TN,BottomBarSheet:AN,BottomBarStatistic:ON};bottomBarRef=t.useRef("bottomBar");sheetListRef=t.useRef("sheetList");dragAndDrop=Q_();targetScroll=void 0;state=t.useState({isSheetListScrollableLeft:!1,isSheetListScrollableRight:!1});menuMaxHeight=250;menuState=t.useState({isOpen:!1,menuId:void 0,position:null,menuItems:[]});sheetList=this.getVisibleSheets();setup(){t.onWillUpdateProps((()=>{this.updateScrollState();const e=this.getVisibleSheets();mt(this.sheetList,e)||this.dragAndDrop.cancel(),this.sheetList=e}))}clickAddSheet(e){const t=this.env.model.getters.getActiveSheetId(),o=this.env.model.getters.getSheetIds().findIndex((e=>e===t))+1,s=this.env.model.uuidGenerator.smallUuid(),i=this.env.model.getters.getNextSheetName(Mo("Sheet"));this.env.model.dispatch("CREATE_SHEET",{sheetId:s,position:o,name:i}),this.env.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:t,sheetIdTo:s})}getVisibleSheets(){return this.env.model.getters.getVisibleSheetIds().map((e=>{const t=this.env.model.getters.getSheet(e);return{id:t.id,name:t.name}}))}clickListSheets(e){const t=new xI,o=this.env.model.getters.getActiveSheetId();let s=0;for(const e of this.env.model.getters.getSheetIds()){const i=this.env.model.getters.getSheet(e);t.add(e,{name:i.name,sequence:s,isReadonlyAllowed:!0,textColor:i.isVisible?void 0:"#808080",execute:t=>{this.env.model.getters.isSheetVisible(e)||this.env.model.dispatch("SHOW_SHEET",{sheetId:e}),t.model.dispatch("ACTIVATE_SHEET",{sheetIdFrom:o,sheetIdTo:e})},isEnabled:e=>!e.model.getters.isReadonly()||i.isVisible,icon:i.color?"o-spreadsheet-Icon.SMALL_DOT_RIGHT_ALIGN":void 0,iconColor:i.color}),s++}const i=e.currentTarget,{left:n}=i.getBoundingClientRect(),r=this.bottomBarRef.el.getBoundingClientRect().top;this.openContextMenu(n,r,"listSheets",t)}openContextMenu(e,t,o,s){this.menuState.isOpen=!0,this.menuState.menuId=o,this.menuState.menuItems=s.getMenuItems(),this.menuState.position={x:e,y:t}}onSheetContextMenu(e,t,o){const s=o.currentTarget,{top:i,left:n}=s.getBoundingClientRect();o.closedMenuId!==e?this.openContextMenu(n,i,e,t):this.closeMenu()}closeMenu(){this.menuState.isOpen=!1,this.menuState.menuId=void 0,this.menuState.menuItems=[],this.menuState.position=null}closeContextMenuWithId(e){this.menuState.menuId===e&&this.closeMenu()}onWheel(e){this.targetScroll=void 0;e.currentTarget.scrollLeft+=.5*e.deltaY}onScroll(){this.updateScrollState(),this.targetScroll===this.sheetListCurrentScroll&&(this.targetScroll=void 0)}onArrowLeft(e){if(!this.state.isSheetListScrollableLeft)return;this.targetScroll||(this.targetScroll=this.sheetListCurrentScroll);const t=this.targetScroll-this.sheetListWidth;this.scrollSheetListTo(Math.max(0,t))}onArrowRight(e){if(!this.state.isSheetListScrollableRight)return;this.targetScroll||(this.targetScroll=this.sheetListCurrentScroll);const t=this.targetScroll+this.sheetListWidth;this.scrollSheetListTo(Math.min(this.sheetListMaxScroll,t))}updateScrollState(){this.state.isSheetListScrollableLeft=this.sheetListCurrentScroll>0,this.state.isSheetListScrollableRight=this.sheetListCurrentScroll<this.sheetListMaxScroll}scrollSheetListTo(e){this.sheetListRef.el&&(this.targetScroll=e,this.sheetListRef.el.scrollTo({top:0,left:e,behavior:"smooth"}))}onSheetMouseDown(e,t){if(0!==t.button||this.env.model.getters.isReadonly())return;this.closeMenu();const o=this.getVisibleSheets(),s=this.getSheetItemRects(),i=o.map(((e,t)=>({id:e.id,size:s[t].width,position:s[t].x})));this.dragAndDrop.start("horizontal",{draggedItemId:e,initialMousePosition:t.clientX,items:i,scrollableContainerEl:this.sheetListRef.el,onDragEnd:(e,t)=>this.onDragEnd(e,t)})}onDragEnd(e,t){const o=t-this.getVisibleSheets().findIndex((t=>t.id===e));e&&0!==o&&this.env.model.dispatch("MOVE_SHEET",{sheetId:e,delta:o})}getSheetStyle(e){return this.dragAndDrop.itemsStyle[e]||""}getSheetItemRects(){return Array.from(this.bottomBarRef.el.querySelectorAll(".o-sheet")).map((e=>e.getBoundingClientRect())).map((e=>({x:e.x,width:e.width-1,y:e.y,height:e.height})))}get sheetListCurrentScroll(){return this.sheetListRef.el?this.sheetListRef.el.scrollLeft:0}get sheetListWidth(){return this.sheetListRef.el?this.sheetListRef.el.clientWidth:0}get sheetListMaxScroll(){return this.sheetListRef.el?this.sheetListRef.el.scrollWidth-this.sheetListRef.el.clientWidth:0}}class MN extends _c{_clickableCells=t.markRaw({});_registryItems=t.markRaw(EN.getAll().sort(((e,t)=>e.sequence-t.sequence)));handle(e){(li.has(e.type)||"EVALUATE_CELLS"===e.type||"UPDATE_CELL"===e.type&&("content"in e||"format"in e))&&(this._clickableCells=t.markRaw({}),this._registryItems=t.markRaw(EN.getAll().sort(((e,t)=>e.sequence-t.sequence))))}getClickableItem(e){const{sheetId:t,col:o,row:s}=e,i=this._clickableCells,n=Co(o,s);if(i[t]||(i[t]={}),!(n in i[t])){const o=this.findClickableItem(e);o&&(i[t][n]=o)}return i[t][n]}findClickableItem(e){const t=this.getters;for(const o of this._registryItems)if(o.condition(e,t))return o}get clickableCells(){const e=[],t=this.getters,o=t.getActiveSheetId();for(const s of this.getters.getVisibleCellPositions()){const i=this.getClickableItem(s);if(!i)continue;const n=t.expandZone(o,vs(s));e.push({coordinates:t.getVisibleRect(n),position:s,action:i.execute,title:i.title||""})}return e}}Pc`
|
|
1938
1938
|
.o-dashboard-clickable-cell {
|
|
1939
1939
|
position: absolute;
|
|
1940
1940
|
cursor: pointer;
|
|
1941
1941
|
}
|
|
1942
|
-
`;class
|
|
1942
|
+
`;class PN extends t.Component{static template="o-spreadsheet-SpreadsheetDashboard";static props={};static components={GridOverlay:xM,GridPopover:IM,Popover:PI,VerticalScrollBar:UM,HorizontalScrollBar:VM};cellPopovers;onMouseWheel;canvasPosition;hoveredCell;clickableCellsStore;setup(){const e=t.useRef("grid");this.canvasPosition=MI(e),this.hoveredCell=Cc(TI),this.clickableCellsStore=Cc(MN),t.useChildSubEnv({getPopoverContainerRect:()=>this.getGridRect()}),FM("canvas",this.env.model,(()=>this.env.model.getters.getSheetViewDimension())),this.onMouseWheel=MM(((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()})),this.cellPopovers=Cc(AI)}onCellHovered({col:e,row:t}){this.hoveredCell.hover({col:e,row:t})}get gridContainer(){const e=this.env.model.getters.getActiveSheetId(),{right:t}=this.env.model.getters.getSheetZone(e),{end:o}=this.env.model.getters.getColDimensions(e,t);return Lc({"max-width":`${o}px`})}get gridOverlayDimensions(){return Lc({height:"100%",width:"100%"})}getCellClickableStyle(e){return Lc({top:`${e.y}px`,left:`${e.x}px`,width:`${e.width}px`,height:`${e.height}px`})}getClickableCells(){return t.toRaw(this.clickableCellsStore.clickableCells)}selectClickableCell(e,t){const{position:o,action:s}=t;s(o,this.env,sR(e))}onClosePopover(){this.cellPopovers.close()}onGridResized({height:e,width:t}){this.env.model.dispatch("RESIZE_SHEETVIEW",{width:t,height:e,gridOffsetX:0,gridOffsetY:0})}moveCanvas(e,t){const{scrollX:o,scrollY:s}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch("SET_VIEWPORT_OFFSET",{offsetX:o+e,offsetY:s+t})}getGridRect(){return{...this.canvasPosition,...this.env.model.getters.getSheetViewDimensionWithHeaders()}}}Pc`
|
|
1943
1943
|
.o-header-group {
|
|
1944
1944
|
.o-header-group-header {
|
|
1945
1945
|
z-index: ${Oe.HeaderGroupingButton};
|
|
@@ -1959,7 +1959,7 @@
|
|
|
1959
1959
|
}
|
|
1960
1960
|
}
|
|
1961
1961
|
}
|
|
1962
|
-
`;class
|
|
1962
|
+
`;class NN extends t.Component{static template="o-spreadsheet-HeaderGroup";static props={group:Object,layerOffset:Number,openContextMenu:Function};toggleGroup(){const e=this.env.model.getters.getActiveSheetId(),{start:t,end:o}=this.props.group;jF(this.env,e,this.dimension,t,o)}get groupBoxStyle(){const e=this.groupBox;return Lc({top:`${e.groupRect.y}px`,left:`${e.groupRect.x}px`,width:`${e.groupRect.width}px`,height:`${e.groupRect.height}px`})}get groupButtonStyle(){return Lc({"background-color":this.isGroupFolded?"#333":"#fff",color:this.isGroupFolded?"#fff":"#333"})}get groupButtonIcon(){return this.isGroupFolded?"o-spreadsheet-Icon.PLUS":"o-spreadsheet-Icon.MINUS"}get isGroupFolded(){const e=this.env.model.getters.getActiveSheetId(),t=this.props.group;return this.env.model.getters.isGroupFolded(e,this.dimension,t.start,t.end)}onContextMenu(e){const t=this.env.model.getters.getActiveSheetId(),s={x:e.clientX,y:e.clientY},i=this.props.group,n=function(e,t,s,i){const n=o([{id:"toggle_group",name:e=>{const o=e.model.getters.getActiveSheetId(),n=e.model.getters.isGroupFolded(o,t,s,i);return Mo(n?"ROW"===t?"Expand row group":"Expand column group":"ROW"===t?"Collapse row group":"Collapse column group")},execute:e=>{const o=e.model.getters.getActiveSheetId();jF(e,o,t,s,i)}},{id:"remove_group",name:Mo("ROW"===t?"Remove row group":"Remove column group"),execute:e=>{const o=e.model.getters.getActiveSheetId();e.model.dispatch("UNGROUP_HEADERS",{sheetId:o,dimension:t,start:s,end:i})},separator:!0}]);return[...n,...YF(e,t)]}(t,this.dimension,i.start,i.end);this.props.openContextMenu(s,n)}}class kN extends NN{dimension="ROW";get groupBorderStyle(){const e=this.groupBox;return 0===this.groupBox.groupRect.height?"":Lc({top:e.headerRect.height/2+"px",left:"calc(50% - 1px)",width:"30%",height:`calc(100% - ${e.headerRect.height/2}px)`,"border-left":`1px solid ${w}`,"border-bottom":e.isEndHidden?"":`1px solid ${w}`})}get groupHeaderStyle(){return Lc({width:"100%",height:`${this.groupBox.headerRect.height}px`})}get groupBox(){const e=this.env.model.getters.getActiveSheetId(),{start:t,end:o}=this.props.group,s=this.env.model.getters.getRowDimensions(e,t).start,i=this.env.model.getters.getRowDimensions(e,o).end;let n=0,r=ee;if(0!==t){const o=this.env.model.getters.getRowDimensions(e,t-1);n=ee+o.start,r=o.end-o.start}const a={x:this.props.layerOffset,y:n,width:ae,height:r};return{headerRect:a,groupRect:{x:this.props.layerOffset,y:a.y,width:ae,height:a.height+(i-s)},isEndHidden:this.env.model.getters.isRowHidden(e,o)}}}class LN extends NN{dimension="COL";get groupBorderStyle(){const e=this.groupBox;return 0===e.groupRect.width?"":Lc({top:"calc(50% - 1px)",left:e.headerRect.width/2+"px",width:`calc(100% - ${e.headerRect.width/2}px)`,height:"30%","border-top":`1px solid ${w}`,"border-right":e.isEndHidden?"":`1px solid ${w}`})}get groupHeaderStyle(){return Lc({width:`${this.groupBox.headerRect.width}px`,height:"100%"})}get groupBox(){const e=this.env.model.getters.getActiveSheetId(),{start:t,end:o}=this.props.group,s=this.env.model.getters.getColDimensions(e,t).start,i=this.env.model.getters.getColDimensions(e,o).end;let n=0,r=te;if(0!==t){const o=this.env.model.getters.getColDimensions(e,t-1);n=te+o.start,r=o.end-o.start}const a={x:n,y:this.props.layerOffset,width:r,height:ae};return{headerRect:a,groupRect:{x:a.x,y:this.props.layerOffset,width:a.width+(i-s),height:ae},isEndHidden:this.env.model.getters.isColHidden(e,o)}}}Pc`
|
|
1963
1963
|
.o-header-group-frozen-pane-border {
|
|
1964
1964
|
&.o-group-rows {
|
|
1965
1965
|
margin-top: -1px;
|
|
@@ -1979,7 +1979,7 @@
|
|
|
1979
1979
|
margin-left: -2px;
|
|
1980
1980
|
}
|
|
1981
1981
|
}
|
|
1982
|
-
`;class
|
|
1982
|
+
`;class VN extends t.Component{static template="o-spreadsheet-HeaderGroupContainer";static props={dimension:String,layers:Array};static components={RowGroup:kN,ColGroup:LN,Menu:mR};menu=t.useState({isOpen:!1,position:null,menuItems:[]});getLayerOffset(e){return e*ae}onContextMenu(e){const t=this.env.model.getters.getActiveSheetId(),o={x:e.clientX,y:e.clientY},s=YF(t,this.props.dimension);this.openContextMenu(o,s)}openContextMenu(e,t){this.menu.isOpen=!0,this.menu.position=e,this.menu.menuItems=t}closeMenu(){this.menu.isOpen=!1,this.menu.position=null,this.menu.menuItems=[]}get groupComponent(){return"ROW"===this.props.dimension?kN:LN}get hasFrozenPane(){const e=this.env.model.getters.getMainViewportCoordinates();return"COL"===this.props.dimension?e.x>0:e.y>0}get scrollContainerStyle(){const{scrollX:e,scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo(),o={};return"COL"===this.props.dimension?o.left=-e-this.frozenPaneContainerSize+"px":o.top=-t-this.frozenPaneContainerSize+"px",Lc(o)}get frozenPaneContainerStyle(){const e={};return"COL"===this.props.dimension?e.width=`${this.frozenPaneContainerSize}px`:e.height=`${this.frozenPaneContainerSize}px`,Lc(e)}get frozenPaneContainerSize(){if(!this.hasFrozenPane)return 0;const e=this.env.model.getters.getMainViewportCoordinates();return"COL"===this.props.dimension?te+e.x:ee+e.y}}Pc`
|
|
1983
1983
|
.o-sidePanel {
|
|
1984
1984
|
display: flex;
|
|
1985
1985
|
flex-direction: column;
|
|
@@ -2081,7 +2081,7 @@
|
|
|
2081
2081
|
.o-fw-bold {
|
|
2082
2082
|
font-weight: 500;
|
|
2083
2083
|
}
|
|
2084
|
-
`;class
|
|
2084
|
+
`;class UN extends t.Component{static template="o-spreadsheet-SidePanel";static props={};sidePanelStore;spreadsheetRect=FI();setup(){this.sidePanelStore=Cc(BM),t.useEffect((e=>{e||this.sidePanelStore.close()}),(()=>[this.sidePanelStore.isOpen]))}get panel(){return WF.get(this.sidePanelStore.componentTag)}close(){this.sidePanelStore.close()}getTitle(){const e=this.panel;return"function"==typeof e.title?e.title(this.env,this.sidePanelStore.panelProps):e.title}startHandleDrag(e){const t=document.body.style.cursor,o=this.sidePanelStore.panelSize,s=e.clientX;K_((e=>{document.body.style.cursor="col-resize";const t=o+s-e.clientX;this.sidePanelStore.changePanelSize(t,this.spreadsheetRect.width)}),(()=>{document.body.style.cursor=t}))}}Pc`
|
|
2085
2085
|
.o-menu-item-button {
|
|
2086
2086
|
display: flex;
|
|
2087
2087
|
justify-content: center;
|
|
@@ -2095,7 +2095,7 @@
|
|
|
2095
2095
|
opacity: 0.6;
|
|
2096
2096
|
cursor: default;
|
|
2097
2097
|
}
|
|
2098
|
-
`;class
|
|
2098
|
+
`;class HN extends t.Component{static template="o-spreadsheet-ActionButton";static props={action:Object,hasTriangleDownIcon:{type:Boolean,optional:!0},selectedColor:{type:String,optional:!0},class:{type:String,optional:!0},onClick:{type:Function,optional:!0}};actionButton=i(this.props.action);setup(){t.onWillUpdateProps((e=>{e.action!==this.props.action&&(this.actionButton=i(e.action))}))}get isVisible(){return this.actionButton.isVisible(this.env)}get isEnabled(){return this.actionButton.isEnabled(this.env)}get isActive(){return this.actionButton.isActive?.(this.env)}get title(){const e=this.actionButton.name(this.env),t=this.actionButton.description(this.env);return e+(t?` (${t})`:"")}get iconTitle(){return this.actionButton.icon(this.env)}onClick(e){this.isEnabled&&(this.props.onClick?.(e),this.actionButton.execute?.(this.env))}get buttonStyle(){return this.props.selectedColor?Lc({"border-bottom":`4px solid ${this.props.selectedColor}`,height:"16px","margin-top":"2px"}):""}}const BN=[[["all","o-spreadsheet-Icon.BORDERS"],["hv","o-spreadsheet-Icon.BORDER_HV"],["h","o-spreadsheet-Icon.BORDER_H"],["v","o-spreadsheet-Icon.BORDER_V"],["external","o-spreadsheet-Icon.BORDER_EXTERNAL"]],[["left","o-spreadsheet-Icon.BORDER_LEFT"],["top","o-spreadsheet-Icon.BORDER_TOP"],["right","o-spreadsheet-Icon.BORDER_RIGHT"],["bottom","o-spreadsheet-Icon.BORDER_BOTTOM"],["clear","o-spreadsheet-Icon.BORDER_CLEAR"]]];Pc`
|
|
2099
2099
|
.o-border-selector {
|
|
2100
2100
|
padding: 4px;
|
|
2101
2101
|
background-color: white;
|
|
@@ -2167,7 +2167,7 @@
|
|
|
2167
2167
|
height: 25px !important;
|
|
2168
2168
|
}
|
|
2169
2169
|
}
|
|
2170
|
-
`;class
|
|
2170
|
+
`;class zN extends t.Component{static template="o-spreadsheet-BorderEditor";static props={class:{type:String,optional:!0},currentBorderColor:{type:String,optional:!1},currentBorderStyle:{type:String,optional:!1},currentBorderPosition:{type:String,optional:!0},onBorderColorPicked:Function,onBorderStylePicked:Function,onBorderPositionPicked:Function,maxHeight:{type:Number,optional:!0},anchorRect:Object};static components={ColorPickerWidget:CD,Popover:PI};BORDER_POSITIONS=BN;lineStyleButtonRef=t.useRef("lineStyleButton");borderStyles=Ci;state=t.useState({activeTool:void 0});toggleDropdownTool(e){const t=this.state.activeTool===e;this.state.activeTool=t?void 0:e}closeDropdown(){this.state.activeTool=void 0}setBorderPosition(e){this.props.onBorderPositionPicked(e),this.closeDropdown()}setBorderColor(e){this.props.onBorderColorPicked(e),this.closeDropdown()}setBorderStyle(e){this.props.onBorderStylePicked(e),this.closeDropdown()}get lineStylePickerPopoverProps(){return{anchorRect:this.lineStylePickerAnchorRect,positioning:"BottomLeft",verticalOffset:0}}get popoverProps(){return{anchorRect:this.props.anchorRect,maxHeight:this.props.maxHeight,positioning:"BottomLeft",verticalOffset:0}}get lineStylePickerAnchorRect(){const e=this.lineStyleButtonRef.el;if(null===e)return{x:0,y:0,width:0,height:0};const t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}}class $N extends t.Component{static template="o-spreadsheet-BorderEditorWidget";static props={toggleBorderEditor:Function,showBorderEditor:Boolean,disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};static components={BorderEditor:zN};borderEditorButtonRef=t.useRef("borderEditorButton");state=t.useState({currentColor:be,currentStyle:ve,currentPosition:void 0});setup(){t.onWillUpdateProps((e=>{e.showBorderEditor||(this.state.currentPosition=void 0)}))}get borderEditorAnchorRect(){const e=this.borderEditorButtonRef.el.getBoundingClientRect();return{x:e.x,y:e.y,width:e.width,height:e.height}}onBorderPositionPicked(e){this.state.currentPosition=e,this.updateBorder()}onBorderColorPicked(e){this.state.currentColor=e,this.updateBorder()}onBorderStylePicked(e){this.state.currentStyle=e,this.updateBorder()}updateBorder(){void 0!==this.state.currentPosition&&this.env.model.dispatch("SET_ZONE_BORDERS",{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),border:{position:this.state.currentPosition,color:this.state.currentColor,style:this.state.currentStyle}})}}Pc`
|
|
2171
2171
|
.o-topbar-composer-container {
|
|
2172
2172
|
height: ${34}px;
|
|
2173
2173
|
}
|
|
@@ -2189,7 +2189,7 @@
|
|
|
2189
2189
|
.user-select-text {
|
|
2190
2190
|
user-select: text;
|
|
2191
2191
|
}
|
|
2192
|
-
`;class
|
|
2192
|
+
`;class WN extends t.Component{static template="o-spreadsheet-TopBarComposer";static props={};static components={Composer:WD};composerFocusStore;composerStore;composerInterface;setup(){this.composerFocusStore=Cc(Oc);const e=Cc(sM);this.composerStore=e,this.composerInterface={id:"topbarComposer",get editionMode(){return e.editionMode},startEdition:this.composerStore.startEdition,setCurrentContent:this.composerStore.setCurrentContent,stopEdition:this.composerStore.stopEdition}}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:"inactive"}get composerStyle(){const e={padding:"5px 0px 5px 8px","max-height":"100px","line-height":"24px"};return e.height="inactive"===this.focus?"34px":"fit-content",Lc(e)}get containerStyle(){return"inactive"===this.focus?Lc({"border-color":y,"border-right":"none"}):Lc({"border-color":p,"z-index":String(Oe.TopBarComposer)})}onFocus(e){this.composerFocusStore.focusComposer(this.composerInterface,{selection:e})}}class GN extends t.Component{static template="o-spreadsheet-TableDropdownButton";static components={TableStylesPopover:UF,ActionButton:HN};static props={};state=t.useState({popoverProps:void 0});onStylePicked(e){const t=this.env.model.getters.getActiveSheetId(),o={...this.tableConfig,styleId:e};xR(this.env,t,o).isSuccessful&&this.env.openSidePanel("TableSidePanel",{}),this.closePopover()}onClick(e){if(e.hasClosedTableStylesPopover||this.state.popoverProps)return void this.closePopover();if(this.env.model.getters.getFirstTableInSelection())return void this.env.toggleSidePanel("TableSidePanel",{});const t=e.currentTarget,{bottom:o,left:s}=t.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:s,y:o,width:0,height:0},positioning:"BottomLeft",verticalOffset:0}}closePopover(){this.state.popoverProps=void 0}get action(){return{name:e=>this.env.model.getters.getFirstTableInSelection()?Mo("Edit table"):Mo("Insert table"),icon:e=>this.env.model.getters.getFirstTableInSelection()?"o-spreadsheet-Icon.EDIT_TABLE":"o-spreadsheet-Icon.PAINT_TABLE"}}get tableConfig(){return{...tw,numberOfHeaders:1,bandedRows:!0}}}class qN extends t.Component{static template="o-spreadsheet-PaintFormatButton";static props={class:{type:String,optional:!0}};paintFormatStore;setup(){this.paintFormatStore=Cc(wM)}get isActive(){return this.paintFormatStore.isActive}onDblClick(){this.paintFormatStore.activate({persistent:!0})}togglePaintFormat(){this.isActive?this.paintFormatStore.cancel():this.paintFormatStore.activate({persistent:!1})}}Pc`
|
|
2193
2193
|
.o-spreadsheet-topbar {
|
|
2194
2194
|
line-height: 1.2;
|
|
2195
2195
|
font-size: 13px;
|
|
@@ -2283,7 +2283,7 @@
|
|
|
2283
2283
|
}
|
|
2284
2284
|
}
|
|
2285
2285
|
}
|
|
2286
|
-
`;class
|
|
2286
|
+
`;class ZN extends t.Component{static template="o-spreadsheet-TopBar";static props={onClick:Function,dropdownMaxHeight:Number};static components={ColorPickerWidget:CD,ColorPicker:yD,Menu:mR,TopBarComposer:WN,FontSizeEditor:wD,ActionButton:HN,PaintFormatButton:qN,BorderEditorWidget:$N,TableDropdownButton:GN};state=t.useState({menuState:{isOpen:!1,position:null,menuItems:[]},activeTool:"",fillColor:"#ffffff",textColor:"#000000"});isSelectingMenu=!1;openedEl=null;menus=[];EDIT=dT;FORMAT=d_;DATA=hA;formatNumberMenuItemSpec=G_;isntToolbarMenu=!1;composerFocusStore;fingerprints;setup(){this.composerFocusStore=Cc(Oc),this.fingerprints=Cc(p_),t.useExternalListener(window,"click",this.onExternalClick),t.onWillStart((()=>this.updateCellState())),t.onWillUpdateProps((()=>this.updateCellState()))}get topbarComponents(){return GF.getAllOrdered().filter((e=>!e.isVisible||e.isVisible(this.env)))}get currentFontSize(){return this.env.model.getters.getCurrentStyle().fontSize||me}onExternalClick(e){this.openedEl!==e.target&&this.closeMenus()}onClick(){this.props.onClick(),this.closeMenus()}onMenuMouseOver(e,t){this.isSelectingMenu&&this.isntToolbarMenu&&this.openMenu(e,t)}toggleDropdownTool(e,t){const o=this.state.activeTool===e;this.closeMenus(),this.state.activeTool=o?"":e,this.openedEl=o?null:t.target}toggleContextMenu(e,t){this.state.menuState.isOpen&&this.isntToolbarMenu?this.closeMenus():(this.openMenu(e,t),this.isntToolbarMenu=!0)}toggleToolbarContextMenu(e,t){if(this.state.menuState.isOpen&&!this.isntToolbarMenu)this.closeMenus();else{const o=i(e);this.openMenu(o,t),this.isntToolbarMenu=!1}}openMenu(e,t){const{left:o,top:s,height:i}=t.currentTarget.getBoundingClientRect();this.state.activeTool="",this.state.menuState.isOpen=!0,this.state.menuState.position={x:o,y:s+i},this.state.menuState.menuItems=e.children(this.env).sort(((e,t)=>e.sequence-t.sequence)),this.state.menuState.parentMenu=e,this.isSelectingMenu=!0,this.openedEl=t.target,this.composerFocusStore.activeComposer.stopEdition()}closeMenus(){this.state.activeTool="",this.state.menuState.isOpen=!1,this.state.menuState.parentMenu=void 0,this.isSelectingMenu=!1,this.openedEl=null}updateCellState(){const e=this.env.model.getters.getCurrentStyle();this.state.fillColor=e.fillColor||"#ffffff",this.state.textColor=e.textColor||"#000000",this.menus=j_.getMenuItems()}getMenuName(e){return e.name(this.env)}setColor(e,t){RR(this.env,{[e]:t}),this.onClick()}setFontSize(e){RR(this.env,{fontSize:e})}}class jN{clipboard;constructor(e){this.clipboard=e}async write(e){if(this.clipboard?.write)try{await(this.clipboard?.write(this.getClipboardItems(e)))}catch(t){try{await(this.clipboard?.write([new ClipboardItem({[ai.PlainText]:this.getBlob(e,ai.PlainText),[ai.Html]:this.getBlob(e,ai.Html)})]))}catch(e){}}else await this.writeText(e[ai.PlainText]??"")}async writeText(e){try{this.clipboard?.writeText(e)}catch(e){}}async read(){let e;try{e=await navigator.permissions.query({name:"clipboard-read"})}catch(e){}if(!this.clipboard?.read)return{status:"ok",content:{[ai.PlainText]:await(this.clipboard?.readText())}};try{const e=await this.clipboard.read(),t={};for(const o of e)for(const e of o.types){const s=await o.getType(e);t[e]=await s.text()}return{status:"ok",content:t}}catch(t){return{status:"denied"===e?.state?"permissionDenied":"notImplemented"}}}getClipboardItems(e){const t={[ai.PlainText]:this.getBlob(e,ai.PlainText),[ai.Html]:this.getBlob(e,ai.Html)};return[new ClipboardItem(t)]}getBlob(e,t){return new Blob([e[t]||""],{type:t})}}Pc`
|
|
2287
2287
|
.o-spreadsheet {
|
|
2288
2288
|
position: relative;
|
|
2289
2289
|
display: grid;
|
|
@@ -2510,20 +2510,20 @@
|
|
|
2510
2510
|
color: ${M};
|
|
2511
2511
|
}
|
|
2512
2512
|
}
|
|
2513
|
-
`;class jN extends t.Component{static template="o-spreadsheet-Spreadsheet";static props={model:Object,notifyUser:{type:Function,optional:!0},raiseError:{type:Function,optional:!0},askConfirmation:{type:Function,optional:!0}};static components={TopBar:qN,Grid:WM,BottomBar:ON,SidePanel:VN,SpreadsheetDashboard:MN,HeaderGroupContainer:LN};sidePanel;spreadsheetRef=t.useRef("spreadsheet");spreadsheetRect=FI();_focusGrid;isViewportTooSmall=!1;notificationStore;composerFocusStore;get model(){return this.props.model}getStyle(){const e={};return this.env.isDashboard()?e["grid-template-rows"]="auto":e["grid-template-rows"]="max-content auto 37px",e["grid-template-columns"]=`auto ${this.sidePanel.panelSize}px`,Lc(e)}setup(){const e=yc();e.inject(Rc,this.model),this.notificationStore=Cc(Qb),this.composerFocusStore=Cc(Oc),this.sidePanel=Cc(HM);const o=this.model.config.external.fileStore;t.useSubEnv({model:this.model,imageProvider:o?new EN(o):void 0,loadCurrencies:this.model.config.external.loadCurrencies,loadLocales:this.model.config.external.loadLocales,isDashboard:()=>this.model.getters.isDashboard(),openSidePanel:this.sidePanel.open.bind(this.sidePanel),toggleSidePanel:this.sidePanel.toggle.bind(this.sidePanel),clipboard:this.env.clipboard||new ZN(navigator.clipboard),startCellEdition:e=>this.composerFocusStore.focusActiveComposer({content:e}),notifyUser:e=>this.notificationStore.notifyUser(e),askConfirmation:(e,t,o)=>this.notificationStore.askConfirmation(e,t,o),raiseError:(e,t)=>this.notificationStore.raiseError(e,t)}),this.notificationStore.updateNotificationCallbacks({...this.props}),t.useEffect((()=>{!this.spreadsheetRef.el.contains(document.activeElement)&&document.activeElement?.contains(this.spreadsheetRef.el)&&this.focusGrid()}),(()=>[this.env.model.getters.getActiveSheetId()])),t.useExternalListener(window,"resize",(()=>this.render(!0))),t.useExternalListener(document.body,"wheel",(()=>{})),this.bindModelEvents(),t.onWillUpdateProps((e=>{if(e.model!==this.props.model)throw new Error("Changing the props model is not supported at the moment.");e.notifyUser===this.props.notifyUser&&e.askConfirmation===this.props.askConfirmation&&e.raiseError===this.props.raiseError||this.notificationStore.updateNotificationCallbacks({...e})}));const s=function(e){let t=!1;return async(...o)=>{t||(t=!0,await Promise.resolve(),t=!1,e(...o))}}(this.render.bind(this,!0));t.onMounted((()=>{this.checkViewportSize(),e.on("store-updated",this,s),i.observe(this.spreadsheetRef.el)})),t.onWillUnmount((()=>{this.unbindModelEvents(),e.off("store-updated",this),i.disconnect()})),t.onPatched((()=>{this.checkViewportSize()}));const i=new ResizeObserver((()=>{this.sidePanel.changePanelSize(this.sidePanel.panelSize,this.spreadsheetRect.width)}))}bindModelEvents(){this.model.on("update",this,(()=>this.render(!0))),this.model.on("notify-ui",this,(e=>this.notificationStore.notifyUser(e))),this.model.on("raise-error-ui",this,(({text:e})=>this.notificationStore.raiseError(e)))}unbindModelEvents(){this.model.off("update",this),this.model.off("notify-ui",this),this.model.off("raise-error-ui",this)}checkViewportSize(){const{xRatio:e,yRatio:t}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());if(isFinite(e)&&isFinite(t))if(t>.85||e>.85){if(this.isViewportTooSmall)return;this.notificationStore.notifyUser({text:Mo("The current window is too small to display this sheet properly. Consider resizing your browser window or adjusting frozen rows and columns."),type:"warning",sticky:!1}),this.isViewportTooSmall=!0}else this.isViewportTooSmall=!1}focusGrid(){this._focusGrid&&this._focusGrid()}get gridHeight(){const{height:e}=this.env.model.getters.getSheetViewDimension();return e}get gridContainerStyle(){const e=ae*this.rowLayers.length,t=ae*this.colLayers.length;return Lc({"grid-template-columns":`${e?e+2:0}px auto`,"grid-template-rows":`${t?t+2:0}px auto`})}get rowLayers(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,"ROW")}get colLayers(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,"COL")}}class YN{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))}}function XN(e){return wI.get(e.type)(e)}class KN{buildTransformation;operations;constructor(e,t=[]){this.buildTransformation=e,this.operations=t}getOperations(){return this.operations}getOperation(e){const t=this.operations.find((t=>t.id===e));if(!t)throw new Error(`Operation ${e} not found`);return t}getLastOperationId(){return this.operations[this.operations.length-1]?.id}getFirstOperationAmong(e,t){for(const o of this.operations){if(o.id===e)return e;if(o.id===t)return t}throw new Error(`Operation ${e} and ${t} not found`)}contains(e){return!!this.operations.find((t=>t.id===e))}prepend(e){const t=this.buildTransformation.with(e.data);this.operations=[e,...this.operations.map((e=>e.transformed(t)))]}insert(e,t){const o=this.buildTransformation.with(e.data),{before:s,operation:i,after:n}=this.locateOperation(t);this.operations=[...s,i,e,...n.map((e=>e.transformed(o)))]}append(e){this.operations.push(e)}appendBranch(e){this.operations=this.operations.concat(e.operations)}fork(e){const{after:t}=this.locateOperation(e);return new KN(this.buildTransformation,t)}transform(e){this.operations=this.operations.map((t=>t.transformed(e)))}cutBefore(e){this.operations=this.locateOperation(e).before}cutAfter(e){const{before:t,operation:o}=this.locateOperation(e);this.operations=t.concat([o])}locateOperation(e){const t=this.operations.findIndex((t=>t.id===e));if(-1===t)throw new Error(`Operation ${e} not found`);return{before:this.operations.slice(0,t),operation:this.operations[t],after:this.operations.slice(t+1)}}}class JN{id;data;constructor(e,t){this.id=e,this.data=t}transformed(e){return new QN(this.id,ut((()=>e(this.data))))}}class QN{id;lazyData;constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(e){return new QN(this.id,this.lazyData.map(e))}}class ek{operations;constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(e){return new ek(function*(e,t){for(const o of e)if(yield o,o.operation.id===t)return}(this.operations,e))}stopBefore(e){return new ek(function*(e,t){for(const o of e){if(o.operation.id===t)return;yield o}}(this.operations,e))}startAfter(e){return new ek(function*(e,t){let o=!0;for(const s of e)o||(yield s),s.operation.id===t&&(o=!1)}(this.operations,e))}}class tk{buildTransformation;branches;branchingOperationIds=new Map;constructor(e,t){this.buildTransformation=e,this.branches=[t]}getLastBranch(){return this.branches[this.branches.length-1]}execution(e){return new ek(Ye(this._execution(e),this._execution(e)))}revertedExecution(e){return new ek(Ye(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){const o=e.getLastOperationId()||this.previousBranch(e)?.getLastOperationId();e.append(t),o&&this.insertPrevious(e,t,o)}insertOperationAfter(e,t,o){e.insert(t,o),this.updateNextWith(e,t,o),this.insertPrevious(e,t,o)}undo(e,t){const o=this.buildTransformation.without(t.data),s=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);const i=e.fork(t.id);s&&this.branchingOperationIds.set(i,s),this.insertBranchAfter(e,i),this.transform(i,o)}redo(e){const t=this.nextBranch(e);if(!t)return;const o=this.nextBranch(t);this.removeBranchFromTree(t);const s=this.branchingOperationIds.get(t);s?this.branchingOperationIds.set(e,s):this.branchingOperationIds.delete(e),o&&this.rebaseUp(o)}drop(e){for(const t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(const o of this.revertedExecution(e))if(o.operation.id===t)return o;throw new Error(`Operation ${t} not found`)}rebaseUp(e){const{previousBranch:t,branchingOperation:o}=this.findPreviousBranchingOperation(e);if(!t||!o)return;const s=this.buildTransformation.without(o.data),i=t.fork(o.id);this.branchingOperationIds.set(i,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,i),i.transform(s);const n=this.nextBranch(i);n&&this.rebaseUp(n)}removeBranchFromTree(e){const t=this.branches.findIndex((t=>t===e));this.branches.splice(t,1)}insertBranchAfter(e,t){const o=this.branches.findIndex((t=>t===e));this.branches.splice(o+1,0,t)}updateNextWith(e,t,o){const s=this.branchingOperationIds.get(e),i=this.nextBranch(e);if(s&&i)if(e.getFirstOperationAmong(o,s)===s){const n=this.addToNextBranch(e,i,s,t,o);this.updateNextWith(i,n,o)}else{const e=this.buildTransformation.with(t.data);this.transform(i,e)}}addToNextBranch(e,t,o,s,i){let n=s;return i===o?(n=this.getTransformedOperation(e,o,s),t.prepend(n)):t.contains(i)?(n=this.getTransformedOperation(e,o,s),t.insert(n,i)):t.append(s),n}getTransformedOperation(e,t,o){const s=e.getOperation(t),i=this.buildTransformation.without(s.data);return o.transformed(i)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);const o=this.nextBranch(e);o&&this.transform(o,t)}insertPrevious(e,t,o){const{previousBranch:s,branchingOperation:i}=this.findPreviousBranchingOperation(e);if(!s||!i)return;const n=this.buildTransformation.with(i.data),r=e.fork(o);r.transform(n),s.cutAfter(o),s.appendBranch(r);const a=t.transformed(n);this.insertPrevious(s,a,o)}findPreviousBranchingOperation(e){const t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};const o=this.branchingOperationIds.get(t);return o?{previousBranch:t,branchingOperation:t.getOperation(o)}:{previousBranch:void 0,branchingOperation:void 0}}nextBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t+1]}previousBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t-1]}*_revertedExecution(e){const t=this.branchingOperationIds.get(e);let o=!!t;const s=e.getOperations();for(let i=s.length-1;i>=0;i--){const n=s[i];n.id===t&&(o=!1),o||(yield{operation:n,branch:e,isCancelled:!this.shouldExecute(e,n)})}const i=this.previousBranch(e);yield*i?this._revertedExecution(i):[]}*_execution(e){for(const t of e.getOperations())if(yield{operation:t,branch:e,isCancelled:!this.shouldExecute(e,t)},t.id===this.branchingOperationIds.get(e)){const t=this.nextBranch(e);return void(yield*t?this._execution(t):[])}if(!this.branchingOperationIds.get(e)){const t=this.nextBranch(e);yield*t?this._execution(t):[]}}}class ok{HEAD_BRANCH;HEAD_OPERATION;tree;applyOperation;revertOperation;buildEmpty;buildTransformation;constructor(e){this.applyOperation=e.applyOperation,this.revertOperation=e.revertOperation,this.buildEmpty=e.buildEmpty,this.buildTransformation=e.buildTransformation,this.HEAD_BRANCH=new KN(this.buildTransformation),this.tree=new tk(this.buildTransformation,this.HEAD_BRANCH);const t=e.initialOperationId,o=new JN(t,this.buildEmpty(t));this.tree.insertOperationLast(this.HEAD_BRANCH,o),this.HEAD_OPERATION=o}get(e){return this.tree.findOperation(this.HEAD_BRANCH,e).operation.data}append(e,t){const o=new JN(e,t),s=this.tree.getLastBranch();this.tree.insertOperationLast(s,o),this.HEAD_BRANCH=s,this.HEAD_OPERATION=o}insert(e,t,o){const s=new JN(e,t);this.revertTo(o),this.tree.insertOperationAfter(this.HEAD_BRANCH,s,o),this.fastForward()}undo(e,t,o){const{branch:s,operation:i}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(s,i),this.fastForward(),this.insert(t,this.buildEmpty(t),o)}redo(e,t,o){const{branch:s}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(s),this.fastForward(),this.insert(t,this.buildEmpty(t),o)}rebase(e){const t=this.get(e),o=[...this.tree.execution(this.HEAD_BRANCH).startAfter(e)];this.revertBefore(e);const s=this.HEAD_OPERATION.id;this.tree.drop(e),this.insert(e,t,s);for(const{operation:e}of o)this.insert(e.id,e.data,this.HEAD_OPERATION.id)}revertBefore(e){const t=this.tree.revertedExecution(this.HEAD_BRANCH).stopWith(e);this.revert(t)}revertTo(e){const t=e?this.tree.revertedExecution(this.HEAD_BRANCH).stopBefore(e):this.tree.revertedExecution(this.HEAD_BRANCH);this.revert(t)}revert(e){for(const{next:t,operation:o,isCancelled:s}of e)s||this.revertOperation(o.data),t&&(this.HEAD_BRANCH=t.branch,this.HEAD_OPERATION=t.operation)}fastForward(){const e=this.HEAD_OPERATION?this.tree.execution(this.HEAD_BRANCH).startAfter(this.HEAD_OPERATION.id):this.tree.execution(this.HEAD_BRANCH);for(const{operation:t,branch:o,isCancelled:s}of e)s||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=o}}function sk(e){return new ok({initialOperationId:e.initialRevisionId,applyOperation:t=>{const o=t.commands.slice(),{changes:s}=e.recordChanges((()=>{for(const t of o)e.dispatch(t)}));t.setChanges(s)},revertOperation:e=>function(e){for(const t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){ik(t.changes[e])}}([e]),buildEmpty:e=>new eN(e,"empty",[]),buildTransformation:{with:e=>t=>new eN(t.id,t.clientId,JP(t.commands,e.commands),t.rootCommand,void 0,t.timestamp),without:e=>t=>new eN(t.id,t.clientId,JP(t.commands,e.commands.map(XN).flat()),t.rootCommand,void 0,t.timestamp)}})}function ik(e){const t=e.target,o=e.key,s=e.before;void 0===s?delete t[o]:t[o]=s}class nk{observers=new Map;defaultSubscription;mainSubscription;registerAsDefault(e,t){this.defaultSubscription={owner:e,callbacks:t},this.mainSubscription||(this.mainSubscription=this.defaultSubscription)}observe(e,t){this.observers.set(e,{owner:e,callbacks:t})}detachObserver(e){this.observers.delete(e)}capture(e,t){if(this.observers.get(e))throw new Error("You are already subscribed forever");this.mainSubscription?.owner&&this.mainSubscription.owner!==e&&this.mainSubscription.callbacks.release?.(),this.mainSubscription={owner:e,callbacks:t}}release(e){this.mainSubscription?.owner!==e||this.observers.get(e)||(this.mainSubscription=this.defaultSubscription)}getBackToDefault(){this.mainSubscription!==this.defaultSubscription&&(this.mainSubscription?.callbacks.release?.(),this.mainSubscription=this.defaultSubscription)}isListening(e){return this.mainSubscription?.owner===e}send(e){this.mainSubscription?.callbacks.handleEvent(e),this.observers.forEach((t=>t.callbacks.handleEvent(e)))}}class rk{getters;stream;anchor;defaultAnchor;constructor(e){this.getters=e,this.stream=new nk,this.anchor={cell:{col:0,row:0},zone:vs({col:0,row:0})},this.defaultAnchor=this.anchor}capture(e,t,o){this.stream.capture(e,o),this.anchor=t}registerAsDefault(e,t,o){this.checkAnchorZoneOrThrow(t),this.stream.registerAsDefault(e,o),this.defaultAnchor=t,this.capture(e,t,o)}resetDefaultAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t),this.defaultAnchor=t}resetAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t)}observe(e,t){this.stream.observe(e,t)}detachObserver(e){this.stream.detachObserver(e)}release(e){this.stream.isListening(e)&&(this.stream.release(e),this.anchor=this.defaultAnchor)}getBackToDefault(){this.stream.getBackToDefault()}modifyAnchor(e,t,o){const s=this.getters.getActiveSheetId();return e={...e,zone:this.getters.expandZone(s,e.zone)},this.processEvent({options:o,anchor:e,mode:t})}selectZone(e,t={scrollIntoView:!0}){return this.modifyAnchor(e,"overrideSelection",t)}selectCell(e,t){const o=vs({col:e,row:t});return this.selectZone({zone:o,cell:{col:e,row:t}},{scrollIntoView:!0})}moveAnchorCell(e,t=1){if("end"!==t&&t<=0)return new fi("InvalidSelectionStep");const{col:o,row:s}=this.getNextAvailablePosition(e,t);return this.selectCell(o,s)}setAnchorCorner(e,t){const o=this.getters.getActiveSheetId(),{col:s,row:i}=this.anchor.cell,n={left:Math.min(s,e),top:Math.min(i,t),right:Math.max(s,e),bottom:Math.max(i,t)},r={zone:this.getters.expandZone(o,n),cell:{col:s,row:i}};return this.processEvent({mode:"updateAnchor",anchor:r,options:{scrollIntoView:!1}})}addCellToSelection(e,t){const o=this.getters.getActiveSheetId();({col:e,row:t}=this.getters.getMainCellPosition({sheetId:o,col:e,row:t}));const s=this.getters.expandZone(o,vs({col:e,row:t}));return this.processEvent({options:{scrollIntoView:!0},anchor:{zone:s,cell:{col:e,row:t}},mode:"newAnchor"})}resizeAnchorZone(e,t=1){if("end"!==t&&t<=0)return new fi("InvalidSelectionStep");const o=this.getters.getActiveSheetId(),s=this.anchor,{col:i,row:n}=s.cell,{left:r,right:a,top:l,bottom:c}=s.zone,h=this.getStartingPosition(e);let[d,u]=this.deltaToTarget(h,e,t);if(0===d&&0===u)return fi.Success;let g=s.zone;const p=e=>{e=ps(e);const{left:t,right:s,top:i,bottom:n}=this.getters.expandZone(o,e);return{left:Math.max(0,t),right:Math.min(this.getters.getNumberCols(o)-1,s),top:Math.max(0,i),bottom:Math.min(this.getters.getNumberRows(o)-1,n)}},{col:m,row:f}=this.getReferencePosition();let v=0;for(;null!==g;){if(v++,d<0){const e=this.getNextAvailableCol(d,a-(v-1),f);g=m<=a-v?p({top:l,left:r,bottom:c,right:e}):null}if(d>0){const e=this.getNextAvailableCol(d,r+(v-1),f);g=r+v<=m?p({top:l,left:e,bottom:c,right:a}):null}if(u<0){const e=this.getNextAvailableRow(u,m,c-(v-1));g=f<=c-v?p({top:l,left:r,bottom:e,right:a}):null}if(u>0){const e=this.getNextAvailableRow(u,m,l+(v-1));g=l+v<=f?p({top:e,left:r,bottom:c,right:a}):null}if(g=g?ps(g):g,g&&!rs(g,s.zone))return this.processEvent({options:{scrollIntoView:!0},mode:"updateAnchor",anchor:{zone:g,cell:{col:i,row:n}}})}g=p(is({top:n,bottom:n,left:i,right:i},ps({top:this.getNextAvailableRow(u,m,l),left:this.getNextAvailableCol(d,r,f),bottom:this.getNextAvailableRow(u,m,c),right:this.getNextAvailableCol(d,a,f)})));const b={zone:g,cell:{col:i,row:n}};return this.processEvent({anchor:b,mode:"updateAnchor",options:{scrollIntoView:!0}})}selectColumn(e,t){const o=this.getters.getActiveSheetId(),s=this.getters.getNumberRows(o)-1;let i={left:e,right:e,top:0,bottom:s};const n=this.getters.findFirstVisibleColRowIndex(o,"ROW");let r,a;switch(t){case"overrideSelection":case"newAnchor":r=e,a=n;break;case"updateAnchor":({col:r,row:a}=this.anchor.cell),i=is(i,{left:r,right:r,top:n,bottom:s})}return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:{zone:i,cell:{col:r,row:a}},mode:t})}selectRow(e,t){const o=this.getters.getActiveSheetId(),s=this.getters.getNumberCols(o)-1;let i={top:e,bottom:e,left:0,right:s};const n=this.getters.findFirstVisibleColRowIndex(o,"COL");let r,a;switch(t){case"overrideSelection":case"newAnchor":r=n,a=e;break;case"updateAnchor":({col:r,row:a}=this.anchor.cell),i=is(i,{left:n,right:s,top:a,bottom:a})}return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:{zone:i,cell:{col:r,row:a}},mode:t})}loopSelection(){const e=this.getters.getActiveSheetId(),t=this.anchor;if(rs(this.anchor.zone,this.getters.getSheetZone(e)))return this.modifyAnchor({...t,zone:vs(t.cell)},"updateAnchor",{scrollIntoView:!1});const o=this.getters.getContiguousZone(e,t.zone);return mt(o,t.zone)?this.selectAll():this.modifyAnchor({...t,zone:o},"updateAnchor",{scrollIntoView:!1})}selectTableAroundSelection(){const e=this.getters.getActiveSheetId(),t=this.getters.getContiguousZone(e,this.anchor.zone);return this.modifyAnchor({...this.anchor,zone:t},"updateAnchor",{scrollIntoView:!1})}selectAll(){const e=this.getters.getActiveSheetId(),t={left:0,top:0,bottom:this.getters.getNumberRows(e)-1,right:this.getters.getNumberCols(e)-1};return this.processEvent({mode:"overrideSelection",anchor:{zone:t,cell:this.anchor.cell},options:{scrollIntoView:!1}})}isListening(e){return this.stream.isListening(e)}processEvent(e){const t={...e,previousAnchor:Be(this.anchor)},o=this.checkEventAnchorZone(t);return"Success"!==o?new fi(o):(this.anchor=t.anchor,this.stream.send(t),fi.Success)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){const{cell:t,zone:o}=e;if(!ls(t.col,t.row,o))return"InvalidAnchorZone";const{left:s,right:i,top:n,bottom:r}=o,a=this.getters.getActiveSheetId(),l=this.getters.findVisibleHeader(a,"COL",s,i);return void 0===this.getters.findVisibleHeader(a,"ROW",n,r)||void 0===l?"SelectionOutOfBound":"Success"}checkAnchorZoneOrThrow(e){if("InvalidAnchorZone"===this.checkAnchorZone(e))throw new Error(Mo("The provided anchor is invalid. The cell must be part of the zone."))}getNextAvailablePosition(e,t=1){const{col:o,row:s}=this.anchor.cell,i=this.deltaToTarget({col:o,row:s},e,t);return{col:this.getNextAvailableCol(i[0],o,s),row:this.getNextAvailableRow(i[1],o,s)}}getNextAvailableCol(e,t,o){const s=this.getters.getActiveSheetId(),i={col:t,row:o};return this.getNextAvailableHeader(e,"COL",t,i,(e=>this.getters.isInSameMerge(s,t,o,e,o)))}getNextAvailableRow(e,t,o){const s=this.getters.getActiveSheetId(),i={col:t,row:o};return this.getNextAvailableHeader(e,"ROW",o,i,(e=>this.getters.isInSameMerge(s,t,o,t,e)))}getNextAvailableHeader(e,t,o,s,i){const n=this.getters.getActiveSheetId();if(0===e)return o;const r=Math.sign(e);let a=o+e;for(;i(a);)a+=r;for(;this.getters.isHeaderHidden(n,t,a);)a+=r;return a<0||a>this.getters.getNumberHeaders(n,t)-1?this.getters.isHeaderHidden(n,t,o)?this.getNextAvailableHeader(-r,t,o,s,i):o:a}getReferencePosition(){const e=this.getters.getActiveSheetId(),t=this.anchor,{left:o,right:s,top:i,bottom:n}=t.zone,{col:r,row:a}=t.cell;return{col:this.getters.isColHidden(e,r)&&this.getters.findVisibleHeader(e,"COL",o,s)||r,row:this.getters.isRowHidden(e,a)&&this.getters.findVisibleHeader(e,"ROW",i,n)||a}}deltaToTarget(e,t,o){switch(t){case"up":return"end"!==o?[0,-o]:[0,this.getEndOfCluster(e,"rows",-1)-e.row];case"down":return"end"!==o?[0,o]:[0,this.getEndOfCluster(e,"rows",1)-e.row];case"left":return"end"!==o?[-o,0]:[this.getEndOfCluster(e,"cols",-1)-e.col,0];case"right":return"end"!==o?[o,0]:[this.getEndOfCluster(e,"cols",1)-e.col,0]}}getStartingPosition(e){let{col:t,row:o}=this.getPosition();const s=this.anchor.zone;switch(e){case"down":case"up":o=o===s.top?s.bottom:s.top;break;case"left":case"right":t=t===s.right?s.left:s.right}return{col:t,row:o}}getEndOfCluster(e,t,o){const s=this.getters.getActiveSheetId();let i=e;const n=this.getNextCellPosition(e,t,o);let r=this.isCellSkippableInCluster({...i,sheetId:s})||this.isCellSkippableInCluster({...n,sheetId:s})?"nextCluster":"endOfCluster";for(;;){const e=this.getNextCellPosition(i,t,o);if(i.col===e.col&&i.row===e.row)break;const n=this.isCellSkippableInCluster({...e,sheetId:s});if("endOfCluster"===r&&n)break;if("nextCluster"===r&&!n){i=e;break}i=e}return"cols"===t?i.col:i.row}getNextCellPosition(e,t,o){const s={...e};return s["cols"===t?"col":"row"]="cols"===t?this.getNextAvailableCol(o,s.col,s.row):this.getNextAvailableRow(o,s.col,s.row),{col:s.col,row:s.row}}getPosition(){return{...this.anchor.cell}}isCellSkippableInCluster(e){const t=this.getters.getMainCellPosition(e),o=this.getters.getEvaluatedCell(t);return o.type===ri.empty||o.type===ri.text&&""===o.value}}function ak(e){if("string"==typeof e)return{};if("number"==typeof e)return[];throw new Error("Cannot create new node")}class lk{changes;commands=[];recordChanges(e){return this.changes=[],this.commands=[],e(),{changes:this.changes,commands:this.commands}}addCommand(e){this.commands.push(e)}addChange(...e){const t=e.pop();let o=e[0],s=e.at(-1);const i=e.length-2;for(let t=1;t<=i;t++){const s=e[t];if(void 0===o[s]){const i=e[t+1];o[s]=ak(i)}o=o[s]}o[s]!==t&&(this.changes?.push({key:s,target:o,before:o[s]}),void 0===t?delete o[s]:o[s]=t)}}const ck=17781237,hk=17781238,dk=88853993,uk=88853994;function gk(e,t,o){const s=[["xmlns:r",cy],["xmlns:a",ny],["xmlns:c",ry]],i=pk({backgroundColor:e.data.backgroundColor,line:{color:"000000"}});let n=Ow``;if(e.data.title?.text){const t=XS(Yc(e.data.backgroundColor)),o=e.data.title.fontSize??X;n=Ow`
|
|
2513
|
+
`;class YN extends t.Component{static template="o-spreadsheet-Spreadsheet";static props={model:Object,notifyUser:{type:Function,optional:!0},raiseError:{type:Function,optional:!0},askConfirmation:{type:Function,optional:!0}};static components={TopBar:ZN,Grid:GM,BottomBar:FN,SidePanel:UN,SpreadsheetDashboard:PN,HeaderGroupContainer:VN};sidePanel;spreadsheetRef=t.useRef("spreadsheet");spreadsheetRect=FI();_focusGrid;isViewportTooSmall=!1;notificationStore;composerFocusStore;get model(){return this.props.model}getStyle(){const e={};return this.env.isDashboard()?e["grid-template-rows"]="auto":e["grid-template-rows"]="max-content auto 37px",e["grid-template-columns"]=`auto ${this.sidePanel.panelSize}px`,Lc(e)}setup(){const e=yc();e.inject(Rc,this.model),this.notificationStore=Cc(Qb),this.composerFocusStore=Cc(Oc),this.sidePanel=Cc(BM);const o=this.model.config.external.fileStore;t.useSubEnv({model:this.model,imageProvider:o?new xN(o):void 0,loadCurrencies:this.model.config.external.loadCurrencies,loadLocales:this.model.config.external.loadLocales,isDashboard:()=>this.model.getters.isDashboard(),openSidePanel:this.sidePanel.open.bind(this.sidePanel),toggleSidePanel:this.sidePanel.toggle.bind(this.sidePanel),clipboard:this.env.clipboard||new jN(navigator.clipboard),startCellEdition:e=>this.composerFocusStore.focusActiveComposer({content:e}),notifyUser:e=>this.notificationStore.notifyUser(e),askConfirmation:(e,t,o)=>this.notificationStore.askConfirmation(e,t,o),raiseError:(e,t)=>this.notificationStore.raiseError(e,t)}),this.notificationStore.updateNotificationCallbacks({...this.props}),t.useEffect((()=>{!this.spreadsheetRef.el.contains(document.activeElement)&&document.activeElement?.contains(this.spreadsheetRef.el)&&this.focusGrid()}),(()=>[this.env.model.getters.getActiveSheetId()])),t.useExternalListener(window,"resize",(()=>this.render(!0))),t.useExternalListener(document.body,"wheel",(()=>{})),this.bindModelEvents(),t.onWillUpdateProps((e=>{if(e.model!==this.props.model)throw new Error("Changing the props model is not supported at the moment.");e.notifyUser===this.props.notifyUser&&e.askConfirmation===this.props.askConfirmation&&e.raiseError===this.props.raiseError||this.notificationStore.updateNotificationCallbacks({...e})}));const s=function(e){let t=!1;return async(...o)=>{t||(t=!0,await Promise.resolve(),t=!1,e(...o))}}(this.render.bind(this,!0));t.onMounted((()=>{this.checkViewportSize(),e.on("store-updated",this,s),i.observe(this.spreadsheetRef.el)})),t.onWillUnmount((()=>{this.unbindModelEvents(),e.off("store-updated",this),i.disconnect()})),t.onPatched((()=>{this.checkViewportSize()}));const i=new ResizeObserver((()=>{this.sidePanel.changePanelSize(this.sidePanel.panelSize,this.spreadsheetRect.width)}))}bindModelEvents(){this.model.on("update",this,(()=>this.render(!0))),this.model.on("notify-ui",this,(e=>this.notificationStore.notifyUser(e))),this.model.on("raise-error-ui",this,(({text:e})=>this.notificationStore.raiseError(e)))}unbindModelEvents(){this.model.off("update",this),this.model.off("notify-ui",this),this.model.off("raise-error-ui",this)}checkViewportSize(){const{xRatio:e,yRatio:t}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());if(isFinite(e)&&isFinite(t))if(t>.85||e>.85){if(this.isViewportTooSmall)return;this.notificationStore.notifyUser({text:Mo("The current window is too small to display this sheet properly. Consider resizing your browser window or adjusting frozen rows and columns."),type:"warning",sticky:!1}),this.isViewportTooSmall=!0}else this.isViewportTooSmall=!1}focusGrid(){this._focusGrid&&this._focusGrid()}get gridHeight(){const{height:e}=this.env.model.getters.getSheetViewDimension();return e}get gridContainerStyle(){const e=ae*this.rowLayers.length,t=ae*this.colLayers.length;return Lc({"grid-template-columns":`${e?e+2:0}px auto`,"grid-template-rows":`${t?t+2:0}px auto`})}get rowLayers(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,"ROW")}get colLayers(){const e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getVisibleGroupLayers(e,"COL")}}class XN{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))}}function KN(e){return wI.get(e.type)(e)}class JN{buildTransformation;operations;constructor(e,t=[]){this.buildTransformation=e,this.operations=t}getOperations(){return this.operations}getOperation(e){const t=this.operations.find((t=>t.id===e));if(!t)throw new Error(`Operation ${e} not found`);return t}getLastOperationId(){return this.operations[this.operations.length-1]?.id}getFirstOperationAmong(e,t){for(const o of this.operations){if(o.id===e)return e;if(o.id===t)return t}throw new Error(`Operation ${e} and ${t} not found`)}contains(e){return!!this.operations.find((t=>t.id===e))}prepend(e){const t=this.buildTransformation.with(e.data);this.operations=[e,...this.operations.map((e=>e.transformed(t)))]}insert(e,t){const o=this.buildTransformation.with(e.data),{before:s,operation:i,after:n}=this.locateOperation(t);this.operations=[...s,i,e,...n.map((e=>e.transformed(o)))]}append(e){this.operations.push(e)}appendBranch(e){this.operations=this.operations.concat(e.operations)}fork(e){const{after:t}=this.locateOperation(e);return new JN(this.buildTransformation,t)}transform(e){this.operations=this.operations.map((t=>t.transformed(e)))}cutBefore(e){this.operations=this.locateOperation(e).before}cutAfter(e){const{before:t,operation:o}=this.locateOperation(e);this.operations=t.concat([o])}locateOperation(e){const t=this.operations.findIndex((t=>t.id===e));if(-1===t)throw new Error(`Operation ${e} not found`);return{before:this.operations.slice(0,t),operation:this.operations[t],after:this.operations.slice(t+1)}}}class QN{id;data;constructor(e,t){this.id=e,this.data=t}transformed(e){return new ek(this.id,ut((()=>e(this.data))))}}class ek{id;lazyData;constructor(e,t){this.id=e,this.lazyData=t}get data(){return this.lazyData()}transformed(e){return new ek(this.id,this.lazyData.map(e))}}class tk{operations;constructor(e){this.operations=e}[Symbol.iterator](){return this.operations[Symbol.iterator]()}stopWith(e){return new tk(function*(e,t){for(const o of e)if(yield o,o.operation.id===t)return}(this.operations,e))}stopBefore(e){return new tk(function*(e,t){for(const o of e){if(o.operation.id===t)return;yield o}}(this.operations,e))}startAfter(e){return new tk(function*(e,t){let o=!0;for(const s of e)o||(yield s),s.operation.id===t&&(o=!1)}(this.operations,e))}}class ok{buildTransformation;branches;branchingOperationIds=new Map;constructor(e,t){this.buildTransformation=e,this.branches=[t]}getLastBranch(){return this.branches[this.branches.length-1]}execution(e){return new tk(Ye(this._execution(e),this._execution(e)))}revertedExecution(e){return new tk(Ye(this._revertedExecution(e),this._revertedExecution(e)))}insertOperationLast(e,t){const o=e.getLastOperationId()||this.previousBranch(e)?.getLastOperationId();e.append(t),o&&this.insertPrevious(e,t,o)}insertOperationAfter(e,t,o){e.insert(t,o),this.updateNextWith(e,t,o),this.insertPrevious(e,t,o)}undo(e,t){const o=this.buildTransformation.without(t.data),s=this.branchingOperationIds.get(e);this.branchingOperationIds.set(e,t.id);const i=e.fork(t.id);s&&this.branchingOperationIds.set(i,s),this.insertBranchAfter(e,i),this.transform(i,o)}redo(e){const t=this.nextBranch(e);if(!t)return;const o=this.nextBranch(t);this.removeBranchFromTree(t);const s=this.branchingOperationIds.get(t);s?this.branchingOperationIds.set(e,s):this.branchingOperationIds.delete(e),o&&this.rebaseUp(o)}drop(e){for(const t of this.branches)t.contains(e)&&t.cutBefore(e)}findOperation(e,t){for(const o of this.revertedExecution(e))if(o.operation.id===t)return o;throw new Error(`Operation ${t} not found`)}rebaseUp(e){const{previousBranch:t,branchingOperation:o}=this.findPreviousBranchingOperation(e);if(!t||!o)return;const s=this.buildTransformation.without(o.data),i=t.fork(o.id);this.branchingOperationIds.set(i,this.branchingOperationIds.get(e)),this.removeBranchFromTree(e),this.insertBranchAfter(t,i),i.transform(s);const n=this.nextBranch(i);n&&this.rebaseUp(n)}removeBranchFromTree(e){const t=this.branches.findIndex((t=>t===e));this.branches.splice(t,1)}insertBranchAfter(e,t){const o=this.branches.findIndex((t=>t===e));this.branches.splice(o+1,0,t)}updateNextWith(e,t,o){const s=this.branchingOperationIds.get(e),i=this.nextBranch(e);if(s&&i)if(e.getFirstOperationAmong(o,s)===s){const n=this.addToNextBranch(e,i,s,t,o);this.updateNextWith(i,n,o)}else{const e=this.buildTransformation.with(t.data);this.transform(i,e)}}addToNextBranch(e,t,o,s,i){let n=s;return i===o?(n=this.getTransformedOperation(e,o,s),t.prepend(n)):t.contains(i)?(n=this.getTransformedOperation(e,o,s),t.insert(n,i)):t.append(s),n}getTransformedOperation(e,t,o){const s=e.getOperation(t),i=this.buildTransformation.without(s.data);return o.transformed(i)}shouldExecute(e,t){return t.id!==this.branchingOperationIds.get(e)}transform(e,t){e.transform(t);const o=this.nextBranch(e);o&&this.transform(o,t)}insertPrevious(e,t,o){const{previousBranch:s,branchingOperation:i}=this.findPreviousBranchingOperation(e);if(!s||!i)return;const n=this.buildTransformation.with(i.data),r=e.fork(o);r.transform(n),s.cutAfter(o),s.appendBranch(r);const a=t.transformed(n);this.insertPrevious(s,a,o)}findPreviousBranchingOperation(e){const t=this.previousBranch(e);if(!t)return{previousBranch:void 0,branchingOperation:void 0};const o=this.branchingOperationIds.get(t);return o?{previousBranch:t,branchingOperation:t.getOperation(o)}:{previousBranch:void 0,branchingOperation:void 0}}nextBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t+1]}previousBranch(e){const t=this.branches.findIndex((t=>t===e));if(-1!==t)return this.branches[t-1]}*_revertedExecution(e){const t=this.branchingOperationIds.get(e);let o=!!t;const s=e.getOperations();for(let i=s.length-1;i>=0;i--){const n=s[i];n.id===t&&(o=!1),o||(yield{operation:n,branch:e,isCancelled:!this.shouldExecute(e,n)})}const i=this.previousBranch(e);yield*i?this._revertedExecution(i):[]}*_execution(e){for(const t of e.getOperations())if(yield{operation:t,branch:e,isCancelled:!this.shouldExecute(e,t)},t.id===this.branchingOperationIds.get(e)){const t=this.nextBranch(e);return void(yield*t?this._execution(t):[])}if(!this.branchingOperationIds.get(e)){const t=this.nextBranch(e);yield*t?this._execution(t):[]}}}class sk{HEAD_BRANCH;HEAD_OPERATION;tree;applyOperation;revertOperation;buildEmpty;buildTransformation;constructor(e){this.applyOperation=e.applyOperation,this.revertOperation=e.revertOperation,this.buildEmpty=e.buildEmpty,this.buildTransformation=e.buildTransformation,this.HEAD_BRANCH=new JN(this.buildTransformation),this.tree=new ok(this.buildTransformation,this.HEAD_BRANCH);const t=e.initialOperationId,o=new QN(t,this.buildEmpty(t));this.tree.insertOperationLast(this.HEAD_BRANCH,o),this.HEAD_OPERATION=o}get(e){return this.tree.findOperation(this.HEAD_BRANCH,e).operation.data}append(e,t){const o=new QN(e,t),s=this.tree.getLastBranch();this.tree.insertOperationLast(s,o),this.HEAD_BRANCH=s,this.HEAD_OPERATION=o}insert(e,t,o){const s=new QN(e,t);this.revertTo(o),this.tree.insertOperationAfter(this.HEAD_BRANCH,s,o),this.fastForward()}undo(e,t,o){const{branch:s,operation:i}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.undo(s,i),this.fastForward(),this.insert(t,this.buildEmpty(t),o)}redo(e,t,o){const{branch:s}=this.tree.findOperation(this.HEAD_BRANCH,e);this.revertBefore(e),this.tree.redo(s),this.fastForward(),this.insert(t,this.buildEmpty(t),o)}rebase(e){const t=this.get(e),o=[...this.tree.execution(this.HEAD_BRANCH).startAfter(e)];this.revertBefore(e);const s=this.HEAD_OPERATION.id;this.tree.drop(e),this.insert(e,t,s);for(const{operation:e}of o)this.insert(e.id,e.data,this.HEAD_OPERATION.id)}revertBefore(e){const t=this.tree.revertedExecution(this.HEAD_BRANCH).stopWith(e);this.revert(t)}revertTo(e){const t=e?this.tree.revertedExecution(this.HEAD_BRANCH).stopBefore(e):this.tree.revertedExecution(this.HEAD_BRANCH);this.revert(t)}revert(e){for(const{next:t,operation:o,isCancelled:s}of e)s||this.revertOperation(o.data),t&&(this.HEAD_BRANCH=t.branch,this.HEAD_OPERATION=t.operation)}fastForward(){const e=this.HEAD_OPERATION?this.tree.execution(this.HEAD_BRANCH).startAfter(this.HEAD_OPERATION.id):this.tree.execution(this.HEAD_BRANCH);for(const{operation:t,branch:o,isCancelled:s}of e)s||this.applyOperation(t.data),this.HEAD_OPERATION=t,this.HEAD_BRANCH=o}}function ik(e){return new sk({initialOperationId:e.initialRevisionId,applyOperation:t=>{const o=t.commands.slice(),{changes:s}=e.recordChanges((()=>{for(const t of o)e.dispatch(t)}));t.setChanges(s)},revertOperation:e=>function(e){for(const t of e.slice().reverse())for(let e=t.changes.length-1;e>=0;e--){nk(t.changes[e])}}([e]),buildEmpty:e=>new tN(e,"empty",[]),buildTransformation:{with:e=>t=>new tN(t.id,t.clientId,QP(t.commands,e.commands),t.rootCommand,void 0,t.timestamp),without:e=>t=>new tN(t.id,t.clientId,QP(t.commands,e.commands.map(KN).flat()),t.rootCommand,void 0,t.timestamp)}})}function nk(e){const t=e.target,o=e.key,s=e.before;void 0===s?delete t[o]:t[o]=s}class rk{observers=new Map;defaultSubscription;mainSubscription;registerAsDefault(e,t){this.defaultSubscription={owner:e,callbacks:t},this.mainSubscription||(this.mainSubscription=this.defaultSubscription)}observe(e,t){this.observers.set(e,{owner:e,callbacks:t})}detachObserver(e){this.observers.delete(e)}capture(e,t){if(this.observers.get(e))throw new Error("You are already subscribed forever");this.mainSubscription?.owner&&this.mainSubscription.owner!==e&&this.mainSubscription.callbacks.release?.(),this.mainSubscription={owner:e,callbacks:t}}release(e){this.mainSubscription?.owner!==e||this.observers.get(e)||(this.mainSubscription=this.defaultSubscription)}getBackToDefault(){this.mainSubscription!==this.defaultSubscription&&(this.mainSubscription?.callbacks.release?.(),this.mainSubscription=this.defaultSubscription)}isListening(e){return this.mainSubscription?.owner===e}send(e){this.mainSubscription?.callbacks.handleEvent(e),this.observers.forEach((t=>t.callbacks.handleEvent(e)))}}class ak{getters;stream;anchor;defaultAnchor;constructor(e){this.getters=e,this.stream=new rk,this.anchor={cell:{col:0,row:0},zone:vs({col:0,row:0})},this.defaultAnchor=this.anchor}capture(e,t,o){this.stream.capture(e,o),this.anchor=t}registerAsDefault(e,t,o){this.checkAnchorZoneOrThrow(t),this.stream.registerAsDefault(e,o),this.defaultAnchor=t,this.capture(e,t,o)}resetDefaultAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t),this.defaultAnchor=t}resetAnchor(e,t){this.checkAnchorZoneOrThrow(t),this.stream.isListening(e)&&(this.anchor=t)}observe(e,t){this.stream.observe(e,t)}detachObserver(e){this.stream.detachObserver(e)}release(e){this.stream.isListening(e)&&(this.stream.release(e),this.anchor=this.defaultAnchor)}getBackToDefault(){this.stream.getBackToDefault()}modifyAnchor(e,t,o){const s=this.getters.getActiveSheetId();return e={...e,zone:this.getters.expandZone(s,e.zone)},this.processEvent({options:o,anchor:e,mode:t})}selectZone(e,t={scrollIntoView:!0}){return this.modifyAnchor(e,"overrideSelection",t)}selectCell(e,t){const o=vs({col:e,row:t});return this.selectZone({zone:o,cell:{col:e,row:t}},{scrollIntoView:!0})}moveAnchorCell(e,t=1){if("end"!==t&&t<=0)return new fi("InvalidSelectionStep");const{col:o,row:s}=this.getNextAvailablePosition(e,t);return this.selectCell(o,s)}setAnchorCorner(e,t){const o=this.getters.getActiveSheetId(),{col:s,row:i}=this.anchor.cell,n={left:Math.min(s,e),top:Math.min(i,t),right:Math.max(s,e),bottom:Math.max(i,t)},r={zone:this.getters.expandZone(o,n),cell:{col:s,row:i}};return this.processEvent({mode:"updateAnchor",anchor:r,options:{scrollIntoView:!1}})}addCellToSelection(e,t){const o=this.getters.getActiveSheetId();({col:e,row:t}=this.getters.getMainCellPosition({sheetId:o,col:e,row:t}));const s=this.getters.expandZone(o,vs({col:e,row:t}));return this.processEvent({options:{scrollIntoView:!0},anchor:{zone:s,cell:{col:e,row:t}},mode:"newAnchor"})}resizeAnchorZone(e,t=1){if("end"!==t&&t<=0)return new fi("InvalidSelectionStep");const o=this.getters.getActiveSheetId(),s=this.anchor,{col:i,row:n}=s.cell,{left:r,right:a,top:l,bottom:c}=s.zone,h=this.getStartingPosition(e);let[d,u]=this.deltaToTarget(h,e,t);if(0===d&&0===u)return fi.Success;let g=s.zone;const p=e=>{e=ps(e);const{left:t,right:s,top:i,bottom:n}=this.getters.expandZone(o,e);return{left:Math.max(0,t),right:Math.min(this.getters.getNumberCols(o)-1,s),top:Math.max(0,i),bottom:Math.min(this.getters.getNumberRows(o)-1,n)}},{col:m,row:f}=this.getReferencePosition();let v=0;for(;null!==g;){if(v++,d<0){const e=this.getNextAvailableCol(d,a-(v-1),f);g=m<=a-v?p({top:l,left:r,bottom:c,right:e}):null}if(d>0){const e=this.getNextAvailableCol(d,r+(v-1),f);g=r+v<=m?p({top:l,left:e,bottom:c,right:a}):null}if(u<0){const e=this.getNextAvailableRow(u,m,c-(v-1));g=f<=c-v?p({top:l,left:r,bottom:e,right:a}):null}if(u>0){const e=this.getNextAvailableRow(u,m,l+(v-1));g=l+v<=f?p({top:e,left:r,bottom:c,right:a}):null}if(g=g?ps(g):g,g&&!rs(g,s.zone))return this.processEvent({options:{scrollIntoView:!0},mode:"updateAnchor",anchor:{zone:g,cell:{col:i,row:n}}})}g=p(is({top:n,bottom:n,left:i,right:i},ps({top:this.getNextAvailableRow(u,m,l),left:this.getNextAvailableCol(d,r,f),bottom:this.getNextAvailableRow(u,m,c),right:this.getNextAvailableCol(d,a,f)})));const b={zone:g,cell:{col:i,row:n}};return this.processEvent({anchor:b,mode:"updateAnchor",options:{scrollIntoView:!0}})}selectColumn(e,t){const o=this.getters.getActiveSheetId(),s=this.getters.getNumberRows(o)-1;let i={left:e,right:e,top:0,bottom:s};const n=this.getters.findFirstVisibleColRowIndex(o,"ROW");let r,a;switch(t){case"overrideSelection":case"newAnchor":r=e,a=n;break;case"updateAnchor":({col:r,row:a}=this.anchor.cell),i=is(i,{left:r,right:r,top:n,bottom:s})}return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:{zone:i,cell:{col:r,row:a}},mode:t})}selectRow(e,t){const o=this.getters.getActiveSheetId(),s=this.getters.getNumberCols(o)-1;let i={top:e,bottom:e,left:0,right:s};const n=this.getters.findFirstVisibleColRowIndex(o,"COL");let r,a;switch(t){case"overrideSelection":case"newAnchor":r=n,a=e;break;case"updateAnchor":({col:r,row:a}=this.anchor.cell),i=is(i,{left:n,right:s,top:a,bottom:a})}return this.processEvent({options:{scrollIntoView:!1,unbounded:!0},anchor:{zone:i,cell:{col:r,row:a}},mode:t})}loopSelection(){const e=this.getters.getActiveSheetId(),t=this.anchor;if(rs(this.anchor.zone,this.getters.getSheetZone(e)))return this.modifyAnchor({...t,zone:vs(t.cell)},"updateAnchor",{scrollIntoView:!1});const o=this.getters.getContiguousZone(e,t.zone);return mt(o,t.zone)?this.selectAll():this.modifyAnchor({...t,zone:o},"updateAnchor",{scrollIntoView:!1})}selectTableAroundSelection(){const e=this.getters.getActiveSheetId(),t=this.getters.getContiguousZone(e,this.anchor.zone);return this.modifyAnchor({...this.anchor,zone:t},"updateAnchor",{scrollIntoView:!1})}selectAll(){const e=this.getters.getActiveSheetId(),t={left:0,top:0,bottom:this.getters.getNumberRows(e)-1,right:this.getters.getNumberCols(e)-1};return this.processEvent({mode:"overrideSelection",anchor:{zone:t,cell:this.anchor.cell},options:{scrollIntoView:!1}})}isListening(e){return this.stream.isListening(e)}processEvent(e){const t={...e,previousAnchor:Be(this.anchor)},o=this.checkEventAnchorZone(t);return"Success"!==o?new fi(o):(this.anchor=t.anchor,this.stream.send(t),fi.Success)}checkEventAnchorZone(e){return this.checkAnchorZone(e.anchor)}checkAnchorZone(e){const{cell:t,zone:o}=e;if(!ls(t.col,t.row,o))return"InvalidAnchorZone";const{left:s,right:i,top:n,bottom:r}=o,a=this.getters.getActiveSheetId(),l=this.getters.findVisibleHeader(a,"COL",s,i);return void 0===this.getters.findVisibleHeader(a,"ROW",n,r)||void 0===l?"SelectionOutOfBound":"Success"}checkAnchorZoneOrThrow(e){if("InvalidAnchorZone"===this.checkAnchorZone(e))throw new Error(Mo("The provided anchor is invalid. The cell must be part of the zone."))}getNextAvailablePosition(e,t=1){const{col:o,row:s}=this.anchor.cell,i=this.deltaToTarget({col:o,row:s},e,t);return{col:this.getNextAvailableCol(i[0],o,s),row:this.getNextAvailableRow(i[1],o,s)}}getNextAvailableCol(e,t,o){const s=this.getters.getActiveSheetId(),i={col:t,row:o};return this.getNextAvailableHeader(e,"COL",t,i,(e=>this.getters.isInSameMerge(s,t,o,e,o)))}getNextAvailableRow(e,t,o){const s=this.getters.getActiveSheetId(),i={col:t,row:o};return this.getNextAvailableHeader(e,"ROW",o,i,(e=>this.getters.isInSameMerge(s,t,o,t,e)))}getNextAvailableHeader(e,t,o,s,i){const n=this.getters.getActiveSheetId();if(0===e)return o;const r=Math.sign(e);let a=o+e;for(;i(a);)a+=r;for(;this.getters.isHeaderHidden(n,t,a);)a+=r;return a<0||a>this.getters.getNumberHeaders(n,t)-1?this.getters.isHeaderHidden(n,t,o)?this.getNextAvailableHeader(-r,t,o,s,i):o:a}getReferencePosition(){const e=this.getters.getActiveSheetId(),t=this.anchor,{left:o,right:s,top:i,bottom:n}=t.zone,{col:r,row:a}=t.cell;return{col:this.getters.isColHidden(e,r)&&this.getters.findVisibleHeader(e,"COL",o,s)||r,row:this.getters.isRowHidden(e,a)&&this.getters.findVisibleHeader(e,"ROW",i,n)||a}}deltaToTarget(e,t,o){switch(t){case"up":return"end"!==o?[0,-o]:[0,this.getEndOfCluster(e,"rows",-1)-e.row];case"down":return"end"!==o?[0,o]:[0,this.getEndOfCluster(e,"rows",1)-e.row];case"left":return"end"!==o?[-o,0]:[this.getEndOfCluster(e,"cols",-1)-e.col,0];case"right":return"end"!==o?[o,0]:[this.getEndOfCluster(e,"cols",1)-e.col,0]}}getStartingPosition(e){let{col:t,row:o}=this.getPosition();const s=this.anchor.zone;switch(e){case"down":case"up":o=o===s.top?s.bottom:s.top;break;case"left":case"right":t=t===s.right?s.left:s.right}return{col:t,row:o}}getEndOfCluster(e,t,o){const s=this.getters.getActiveSheetId();let i=e;const n=this.getNextCellPosition(e,t,o);let r=this.isCellSkippableInCluster({...i,sheetId:s})||this.isCellSkippableInCluster({...n,sheetId:s})?"nextCluster":"endOfCluster";for(;;){const e=this.getNextCellPosition(i,t,o);if(i.col===e.col&&i.row===e.row)break;const n=this.isCellSkippableInCluster({...e,sheetId:s});if("endOfCluster"===r&&n)break;if("nextCluster"===r&&!n){i=e;break}i=e}return"cols"===t?i.col:i.row}getNextCellPosition(e,t,o){const s={...e};return s["cols"===t?"col":"row"]="cols"===t?this.getNextAvailableCol(o,s.col,s.row):this.getNextAvailableRow(o,s.col,s.row),{col:s.col,row:s.row}}getPosition(){return{...this.anchor.cell}}isCellSkippableInCluster(e){const t=this.getters.getMainCellPosition(e),o=this.getters.getEvaluatedCell(t);return o.type===ri.empty||o.type===ri.text&&""===o.value}}function lk(e){if("string"==typeof e)return{};if("number"==typeof e)return[];throw new Error("Cannot create new node")}class ck{changes;commands=[];recordChanges(e){return this.changes=[],this.commands=[],e(),{changes:this.changes,commands:this.commands}}addCommand(e){this.commands.push(e)}addChange(...e){const t=e.pop();let o=e[0],s=e.at(-1);const i=e.length-2;for(let t=1;t<=i;t++){const s=e[t];if(void 0===o[s]){const i=e[t+1];o[s]=lk(i)}o=o[s]}o[s]!==t&&(this.changes?.push({key:s,target:o,before:o[s]}),void 0===t?delete o[s]:o[s]=t)}}const hk=17781237,dk=17781238,uk=88853993,gk=88853994;function pk(e,t,o){const s=[["xmlns:r",cy],["xmlns:a",ny],["xmlns:c",ry]],i=mk({backgroundColor:e.data.backgroundColor,line:{color:"000000"}});let n=Ow``;if(e.data.title?.text){const t=XS(Yc(e.data.backgroundColor)),o=e.data.title.fontSize??X;n=Ow`
|
|
2514
2514
|
<c:title>
|
|
2515
|
-
${
|
|
2515
|
+
${vk(e.data.title.text,t,o,e.data.title)}
|
|
2516
2516
|
<c:overlay val="0" />
|
|
2517
2517
|
</c:title>
|
|
2518
|
-
`}let r=Ow``;switch(e.data.type){case"bar":r=function(e){const t=e.dataSets.map((e=>e.backgroundColor??"")),o=new uo(e.dataSets.length,t),s=[],i=[];for(const[t,n]of Object.entries(e.dataSets)){const r=XS(o.next()),a=
|
|
2518
|
+
`}let r=Ow``;switch(e.data.type){case"bar":r=function(e){const t=e.dataSets.map((e=>e.backgroundColor??"")),o=new uo(e.dataSets.length,t),s=[],i=[];for(const[t,n]of Object.entries(e.dataSets)){const r=XS(o.next()),a=mk({backgroundColor:r,line:{color:r}}),l=Ow`
|
|
2519
2519
|
<c:ser>
|
|
2520
2520
|
<c:idx val="${t}"/>
|
|
2521
2521
|
<c:order val="${t}"/>
|
|
2522
|
-
${
|
|
2522
|
+
${Sk(n.label)}
|
|
2523
2523
|
${a}
|
|
2524
|
-
${e.labelRange?Ow`<c:cat>${
|
|
2524
|
+
${e.labelRange?Ow`<c:cat>${wk(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
|
|
2525
2525
|
<c:val> <!-- x-coordinate values -->
|
|
2526
|
-
${
|
|
2526
|
+
${Ek(n.range)}
|
|
2527
2527
|
</c:val>
|
|
2528
2528
|
</c:ser>
|
|
2529
2529
|
`;n.rightYAxis?i.push(l):s.push(l)}const n=e.stacked?"stacked":"clustered",r=e.stacked?100:-20;return Ow`
|
|
@@ -2536,11 +2536,11 @@
|
|
|
2536
2536
|
<!-- each data marker in the series does not have a different color -->
|
|
2537
2537
|
<c:varyColors val="0"/>
|
|
2538
2538
|
${Dw(s)}
|
|
2539
|
-
<c:axId val="${
|
|
2540
|
-
<c:axId val="${
|
|
2539
|
+
<c:axId val="${hk}" />
|
|
2540
|
+
<c:axId val="${uk}" />
|
|
2541
2541
|
</c:barChart>
|
|
2542
|
-
${
|
|
2543
|
-
${
|
|
2542
|
+
${Ck("b","c:catAx",hk,uk,e.axesDesign?.x?.title,e.fontColor)}
|
|
2543
|
+
${Ck("l","c:valAx",uk,hk,e.axesDesign?.y?.title,e.fontColor)}
|
|
2544
2544
|
`:""}
|
|
2545
2545
|
${i.length?Ow`
|
|
2546
2546
|
<c:barChart>
|
|
@@ -2551,24 +2551,24 @@
|
|
|
2551
2551
|
<!-- each data marker in the series does not have a different color -->
|
|
2552
2552
|
<c:varyColors val="0"/>
|
|
2553
2553
|
${Dw(i)}
|
|
2554
|
-
<c:axId val="${
|
|
2555
|
-
<c:axId val="${
|
|
2554
|
+
<c:axId val="${hk+1}" />
|
|
2555
|
+
<c:axId val="${uk+1}" />
|
|
2556
2556
|
</c:barChart>
|
|
2557
|
-
${
|
|
2558
|
-
${
|
|
2557
|
+
${Ck("b","c:catAx",hk+1,uk+1,e.axesDesign?.x?.title,e.fontColor,s.length?1:0)}
|
|
2558
|
+
${Ck("r","c:valAx",uk+1,hk+1,e.axesDesign?.y1?.title,e.fontColor)}
|
|
2559
2559
|
`:""}`}(e.data);break;case"combo":r=function(e){const t=e.dataSets,o=t.map((e=>e.backgroundColor??"")),s=new uo(t.length,o);let i=t[0];const n=XS(s.next()),r=i.rightYAxis??!1,a=Ow`
|
|
2560
2560
|
<c:ser>
|
|
2561
2561
|
<c:idx val="0"/>
|
|
2562
2562
|
<c:order val="0"/>
|
|
2563
|
-
${
|
|
2564
|
-
${
|
|
2565
|
-
${e.labelRange?Ow`<c:cat>${
|
|
2563
|
+
${Sk(i.label)}
|
|
2564
|
+
${mk({backgroundColor:n,line:{color:n}})}
|
|
2565
|
+
${e.labelRange?Ow`<c:cat>${wk(e.labelRange)}</c:cat>`:""}
|
|
2566
2566
|
<!-- x-coordinate values -->
|
|
2567
2567
|
<c:val>
|
|
2568
|
-
${
|
|
2568
|
+
${Ek(i.range)}
|
|
2569
2569
|
</c:val>
|
|
2570
2570
|
</c:ser>
|
|
2571
|
-
`,l=[],c=[];for(let o=1;o<t.length;o++){i=t[o];const n=XS(s.next()),r=
|
|
2571
|
+
`,l=[],c=[];for(let o=1;o<t.length;o++){i=t[o];const n=XS(s.next()),r=mk({backgroundColor:n,line:{color:n}}),a=Ow`
|
|
2572
2572
|
<c:ser>
|
|
2573
2573
|
<c:idx val="${o}"/>
|
|
2574
2574
|
<c:order val="${o}"/>
|
|
@@ -2578,12 +2578,12 @@
|
|
|
2578
2578
|
<c:size val="5"/>
|
|
2579
2579
|
${r}
|
|
2580
2580
|
</c:marker>
|
|
2581
|
-
${
|
|
2581
|
+
${Sk(i.label)}
|
|
2582
2582
|
${r}
|
|
2583
|
-
${e.labelRange?Ow`<c:cat>${
|
|
2583
|
+
${e.labelRange?Ow`<c:cat>${wk(e.labelRange)}</c:cat>`:""}
|
|
2584
2584
|
<!-- x-coordinate values -->
|
|
2585
2585
|
<c:val>
|
|
2586
|
-
${
|
|
2586
|
+
${Ek(i.range)}
|
|
2587
2587
|
</c:val>
|
|
2588
2588
|
</c:ser>
|
|
2589
2589
|
`;i.rightYAxis?c.push(a):l.push(a)}const h=e.stacked?100:-20;return Ow`
|
|
@@ -2595,8 +2595,8 @@
|
|
|
2595
2595
|
<!-- each data marker in the series does not have a different color -->
|
|
2596
2596
|
<c:varyColors val="0"/>
|
|
2597
2597
|
${a}
|
|
2598
|
-
<c:axId val="${r?hk
|
|
2599
|
-
<c:axId val="${r?uk
|
|
2598
|
+
<c:axId val="${r?dk:hk}" />
|
|
2599
|
+
<c:axId val="${r?gk:uk}" />
|
|
2600
2600
|
</c:barChart>
|
|
2601
2601
|
${l.length?Ow`
|
|
2602
2602
|
<c:lineChart>
|
|
@@ -2604,8 +2604,8 @@
|
|
|
2604
2604
|
<!-- each data marker in the series does not have a different color -->
|
|
2605
2605
|
<c:varyColors val="0"/>
|
|
2606
2606
|
${Dw(l)}
|
|
2607
|
-
<c:axId val="${
|
|
2608
|
-
<c:axId val="${
|
|
2607
|
+
<c:axId val="${hk}" />
|
|
2608
|
+
<c:axId val="${uk}" />
|
|
2609
2609
|
</c:lineChart>
|
|
2610
2610
|
`:""}
|
|
2611
2611
|
${c.length?Ow`
|
|
@@ -2614,19 +2614,19 @@
|
|
|
2614
2614
|
<!-- each data marker in the series does not have a different color -->
|
|
2615
2615
|
<c:varyColors val="0"/>
|
|
2616
2616
|
${Dw(c)}
|
|
2617
|
-
<c:axId val="${
|
|
2618
|
-
<c:axId val="${
|
|
2617
|
+
<c:axId val="${dk}" />
|
|
2618
|
+
<c:axId val="${gk}" />
|
|
2619
2619
|
</c:lineChart>
|
|
2620
2620
|
`:""}
|
|
2621
2621
|
${!r||l.length?Ow`
|
|
2622
|
-
${
|
|
2623
|
-
${
|
|
2622
|
+
${Ck("b","c:catAx",hk,uk,e.axesDesign?.x?.title,e.fontColor,l.length?1:0)}
|
|
2623
|
+
${Ck("l","c:valAx",uk,hk,e.axesDesign?.y?.title,e.fontColor)}
|
|
2624
2624
|
`:""}
|
|
2625
2625
|
${r||c.length?Ow`
|
|
2626
|
-
${
|
|
2627
|
-
${
|
|
2626
|
+
${Ck("b","c:catAx",dk,gk,e.axesDesign?.x?.title,e.fontColor,l.length||!r?1:0)}
|
|
2627
|
+
${Ck("r","c:valAx",gk,dk,e.axesDesign?.y1?.title,e.fontColor)}
|
|
2628
2628
|
`:""}
|
|
2629
|
-
`}(e.data);break;case"line":r=function(e){const t=e.dataSets.map((e=>e.backgroundColor??"")),o=new uo(e.dataSets.length,t),s=[],i=[];for(const[t,n]of Object.entries(e.dataSets)){const r=XS(o.next()),a=
|
|
2629
|
+
`}(e.data);break;case"line":r=function(e){const t=e.dataSets.map((e=>e.backgroundColor??"")),o=new uo(e.dataSets.length,t),s=[],i=[];for(const[t,n]of Object.entries(e.dataSets)){const r=XS(o.next()),a=mk({line:{width:2.5,style:"solid",color:r}}),l=Ow`
|
|
2630
2630
|
<c:ser>
|
|
2631
2631
|
<c:idx val="${t}"/>
|
|
2632
2632
|
<c:order val="${t}"/>
|
|
@@ -2634,13 +2634,13 @@
|
|
|
2634
2634
|
<c:marker>
|
|
2635
2635
|
<c:symbol val="circle" />
|
|
2636
2636
|
<c:size val="5"/>
|
|
2637
|
-
${
|
|
2637
|
+
${mk({backgroundColor:r,line:{color:r}})}
|
|
2638
2638
|
</c:marker>
|
|
2639
|
-
${
|
|
2639
|
+
${Sk(n.label)}
|
|
2640
2640
|
${a}
|
|
2641
|
-
${e.labelRange?Ow`<c:cat>${
|
|
2641
|
+
${e.labelRange?Ow`<c:cat>${wk(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
|
|
2642
2642
|
<c:val> <!-- x-coordinate values -->
|
|
2643
|
-
${
|
|
2643
|
+
${Ek(n.range)}
|
|
2644
2644
|
</c:val>
|
|
2645
2645
|
</c:ser>
|
|
2646
2646
|
`;n.rightYAxis?i.push(l):s.push(l)}const n=e.stacked?"stacked":"standard";return Ow`
|
|
@@ -2650,11 +2650,11 @@
|
|
|
2650
2650
|
<!-- each data marker in the series does not have a different color -->
|
|
2651
2651
|
<c:varyColors val="0"/>
|
|
2652
2652
|
${Dw(s)}
|
|
2653
|
-
<c:axId val="${
|
|
2654
|
-
<c:axId val="${
|
|
2653
|
+
<c:axId val="${hk}" />
|
|
2654
|
+
<c:axId val="${uk}" />
|
|
2655
2655
|
</c:lineChart>
|
|
2656
|
-
${
|
|
2657
|
-
${
|
|
2656
|
+
${Ck("b","c:catAx",hk,uk,e.axesDesign?.x?.title,e.fontColor)}
|
|
2657
|
+
${Ck("l","c:valAx",uk,hk,e.axesDesign?.y?.title,e.fontColor)}
|
|
2658
2658
|
`:""}
|
|
2659
2659
|
${i.length?Ow`
|
|
2660
2660
|
<c:lineChart>
|
|
@@ -2662,11 +2662,11 @@
|
|
|
2662
2662
|
<!-- each data marker in the series does not have a different color -->
|
|
2663
2663
|
<c:varyColors val="0"/>
|
|
2664
2664
|
${Dw(i)}
|
|
2665
|
-
<c:axId val="${
|
|
2666
|
-
<c:axId val="${
|
|
2665
|
+
<c:axId val="${hk+1}" />
|
|
2666
|
+
<c:axId val="${uk+1}" />
|
|
2667
2667
|
</c:lineChart>
|
|
2668
|
-
${
|
|
2669
|
-
${
|
|
2668
|
+
${Ck("b","c:catAx",hk+1,uk+1,e.axesDesign?.x?.title,e.fontColor,s.length?1:0)}
|
|
2669
|
+
${Ck("r","c:valAx",uk+1,hk+1,e.axesDesign?.y1?.title,e.fontColor)}
|
|
2670
2670
|
`:""}
|
|
2671
2671
|
`}(e.data);break;case"scatter":r=function(e){const t=e.dataSets.map((e=>e.backgroundColor??"")),o=new uo(e.dataSets.length,t),s=[],i=[];for(const[t,n]of Object.entries(e.dataSets)){const r=XS(o.next()),a=Ow`
|
|
2672
2672
|
<c:ser>
|
|
@@ -2683,14 +2683,14 @@
|
|
|
2683
2683
|
<c:marker>
|
|
2684
2684
|
<c:symbol val="circle" />
|
|
2685
2685
|
<c:size val="5"/>
|
|
2686
|
-
${
|
|
2686
|
+
${mk({backgroundColor:r,line:{color:r}})}
|
|
2687
2687
|
</c:marker>
|
|
2688
|
-
${
|
|
2688
|
+
${Sk(n.label)}
|
|
2689
2689
|
${e.labelRange?Ow`<c:xVal> <!-- x-coordinate values -->
|
|
2690
|
-
${
|
|
2690
|
+
${Ek(e.labelRange)}
|
|
2691
2691
|
</c:xVal>`:""}
|
|
2692
2692
|
<c:yVal> <!-- y-coordinate values -->
|
|
2693
|
-
${
|
|
2693
|
+
${Ek(n.range)}
|
|
2694
2694
|
</c:yVal>
|
|
2695
2695
|
</c:ser>
|
|
2696
2696
|
`;n.rightYAxis?i.push(a):s.push(a)}return Ow`
|
|
@@ -2700,11 +2700,11 @@
|
|
|
2700
2700
|
<c:varyColors val="0"/>
|
|
2701
2701
|
<c:scatterStyle val="lineMarker"/>
|
|
2702
2702
|
${Dw(s)}
|
|
2703
|
-
<c:axId val="${
|
|
2704
|
-
<c:axId val="${
|
|
2703
|
+
<c:axId val="${hk}" />
|
|
2704
|
+
<c:axId val="${uk}" />
|
|
2705
2705
|
</c:scatterChart>
|
|
2706
|
-
${
|
|
2707
|
-
${
|
|
2706
|
+
${Ck("b","c:valAx",hk,uk,e.axesDesign?.x?.title,e.fontColor)}
|
|
2707
|
+
${Ck("l","c:valAx",uk,hk,e.axesDesign?.y?.title,e.fontColor)}
|
|
2708
2708
|
`:""}
|
|
2709
2709
|
${i.length?Ow`
|
|
2710
2710
|
<c:scatterChart>
|
|
@@ -2712,12 +2712,12 @@
|
|
|
2712
2712
|
<c:varyColors val="0"/>
|
|
2713
2713
|
<c:scatterStyle val="lineMarker"/>
|
|
2714
2714
|
${Dw(i)}
|
|
2715
|
-
<c:axId val="${
|
|
2716
|
-
<c:axId val="${
|
|
2715
|
+
<c:axId val="${hk+1}" />
|
|
2716
|
+
<c:axId val="${uk+1}" />
|
|
2717
2717
|
</c:scatterChart>
|
|
2718
|
-
${
|
|
2719
|
-
${
|
|
2720
|
-
`:""}`}(e.data);break;case"pie":r=function(e,t,o,{holeSize:s}={holeSize:50}){const i=Dt(e.dataSets.map((e=>TC(e.range,t,o)))),n=new uo(i),r=Ze(0,i).map((()=>XS(n.next()))),a=[];for(const[s,i]of Object.entries(e.dataSets).reverse()){const n=TC(i.range,t,o),l=[];for(const e of Ze(0,n)){const t=
|
|
2718
|
+
${Ck("b","c:valAx",hk+1,uk+1,e.axesDesign?.x?.title,e.fontColor,s.length?1:0)}
|
|
2719
|
+
${Ck("r","c:valAx",uk+1,hk+1,e.axesDesign?.y1?.title,e.fontColor)}
|
|
2720
|
+
`:""}`}(e.data);break;case"pie":r=function(e,t,o,{holeSize:s}={holeSize:50}){const i=Dt(e.dataSets.map((e=>TC(e.range,t,o)))),n=new uo(i),r=Ze(0,i).map((()=>XS(n.next()))),a=[];for(const[s,i]of Object.entries(e.dataSets).reverse()){const n=TC(i.range,t,o),l=[];for(const e of Ze(0,n)){const t=mk({backgroundColor:r[e],line:{color:"FFFFFF",width:1.5}});l.push(Ow`
|
|
2721
2721
|
<c:dPt>
|
|
2722
2722
|
<c:idx val="${e}"/>
|
|
2723
2723
|
${t}
|
|
@@ -2726,22 +2726,22 @@
|
|
|
2726
2726
|
<c:ser>
|
|
2727
2727
|
<c:idx val="${s}"/>
|
|
2728
2728
|
<c:order val="${s}"/>
|
|
2729
|
-
${
|
|
2729
|
+
${Sk(i.label)}
|
|
2730
2730
|
${Dw(l)}
|
|
2731
|
-
${
|
|
2732
|
-
${e.labelRange?Ow`<c:cat>${
|
|
2731
|
+
${yk({showLeaderLines:!0})}
|
|
2732
|
+
${e.labelRange?Ow`<c:cat>${wk(e.labelRange)}</c:cat>`:""}
|
|
2733
2733
|
<c:val>
|
|
2734
|
-
${
|
|
2734
|
+
${Ek(i.range)}
|
|
2735
2735
|
</c:val>
|
|
2736
2736
|
</c:ser>
|
|
2737
2737
|
`)}return Ow`
|
|
2738
2738
|
<c:doughnutChart>
|
|
2739
2739
|
<c:varyColors val="1" />
|
|
2740
2740
|
<c:holeSize val="${s}" />
|
|
2741
|
-
${
|
|
2741
|
+
${yk()}
|
|
2742
2742
|
${Dw(a)}
|
|
2743
2743
|
</c:doughnutChart>
|
|
2744
|
-
`}(e.data,t,o,{holeSize:0});break;case"radar":r=function(e){const t=e.dataSets.map((e=>e.backgroundColor??"")),o=new uo(e.dataSets.length,t),s=[];for(const[t,i]of Object.entries(e.dataSets)){const n=XS(o.next()),r=
|
|
2744
|
+
`}(e.data,t,o,{holeSize:0});break;case"radar":r=function(e){const t=e.dataSets.map((e=>e.backgroundColor??"")),o=new uo(e.dataSets.length,t),s=[];for(const[t,i]of Object.entries(e.dataSets)){const n=XS(o.next()),r=mk({line:{width:2.5,style:"solid",color:n}}),a=Ow`
|
|
2745
2745
|
<c:ser>
|
|
2746
2746
|
<c:idx val="${t}"/>
|
|
2747
2747
|
<c:order val="${t}"/>
|
|
@@ -2749,13 +2749,13 @@
|
|
|
2749
2749
|
<c:marker>
|
|
2750
2750
|
<c:symbol val="circle" />
|
|
2751
2751
|
<c:size val="5"/>
|
|
2752
|
-
${
|
|
2752
|
+
${mk({backgroundColor:n,line:{color:n}})}
|
|
2753
2753
|
</c:marker>
|
|
2754
|
-
${
|
|
2754
|
+
${Sk(i.label)}
|
|
2755
2755
|
${r}
|
|
2756
|
-
${e.labelRange?Ow`<c:cat>${
|
|
2756
|
+
${e.labelRange?Ow`<c:cat>${wk(e.labelRange)}</c:cat>`:""} <!-- x-coordinate values -->
|
|
2757
2757
|
<c:val> <!-- x-coordinate values -->
|
|
2758
|
-
${
|
|
2758
|
+
${Ek(i.range)}
|
|
2759
2759
|
</c:val>
|
|
2760
2760
|
</c:ser>
|
|
2761
2761
|
`;s.push(a)}return Ow`
|
|
@@ -2764,11 +2764,11 @@
|
|
|
2764
2764
|
<c:radarStyle val="marker"/>
|
|
2765
2765
|
<c:varyColors val="0"/>
|
|
2766
2766
|
${Dw(s)}
|
|
2767
|
-
<c:axId val="${
|
|
2768
|
-
<c:axId val="${
|
|
2767
|
+
<c:axId val="${hk}" />
|
|
2768
|
+
<c:axId val="${uk}" />
|
|
2769
2769
|
</c:radarChart>
|
|
2770
|
-
${
|
|
2771
|
-
${
|
|
2770
|
+
${Ck("b","c:catAx",hk,uk,e.axesDesign?.x?.title,e.fontColor)}
|
|
2771
|
+
${Ck("l","c:valAx",uk,hk,e.axesDesign?.y?.title,e.fontColor)}
|
|
2772
2772
|
`}
|
|
2773
2773
|
`}(e.data)}let a="t";switch(e.data.legendPosition){case"bottom":a="b";break;case"left":a="l";break;case"right":a="r";break;case"top":a="t"}const l=e.data.fontColor,c=Ow`
|
|
2774
2774
|
<c:chartSpace ${Rw(s)}>
|
|
@@ -2782,32 +2782,32 @@
|
|
|
2782
2782
|
<!-- how the chart element is placed on the chart -->
|
|
2783
2783
|
<c:layout />
|
|
2784
2784
|
${r}
|
|
2785
|
-
${
|
|
2785
|
+
${mk({backgroundColor:e.data.backgroundColor})}
|
|
2786
2786
|
</c:plotArea>
|
|
2787
2787
|
${function(e,t){return Ow`
|
|
2788
2788
|
<c:legend>
|
|
2789
2789
|
<c:legendPos val="${e}"/>
|
|
2790
2790
|
<c:overlay val="0"/>
|
|
2791
|
-
${
|
|
2791
|
+
${bk(10,t)}
|
|
2792
2792
|
</c:legend>
|
|
2793
2793
|
`}(a,l)}
|
|
2794
2794
|
</c:chart>
|
|
2795
2795
|
</c:chartSpace>
|
|
2796
|
-
`;return Tw(c)}function
|
|
2796
|
+
`;return Tw(c)}function mk(e){return Ow`
|
|
2797
2797
|
<c:spPr>
|
|
2798
|
-
${e.backgroundColor?
|
|
2798
|
+
${e.backgroundColor?fk(e.backgroundColor):""}
|
|
2799
2799
|
${e.line?function(e){const t=[["cmpd","sng"]];e.width&&t.push(["w",RC(e.width)]);const o=e.style?Ow`<a:prstDash val="${e.style}"/>`:"";return Ow`
|
|
2800
2800
|
<a:ln ${Rw(t)}>
|
|
2801
|
-
${
|
|
2801
|
+
${fk(e.color)}
|
|
2802
2802
|
${o}
|
|
2803
2803
|
</a:ln>
|
|
2804
2804
|
`}(e.line):""}
|
|
2805
2805
|
</c:spPr>
|
|
2806
|
-
`}function
|
|
2806
|
+
`}function fk(e){return Ow`
|
|
2807
2807
|
<a:solidFill>
|
|
2808
2808
|
<a:srgbClr val="${e}"/>
|
|
2809
2809
|
</a:solidFill>
|
|
2810
|
-
`}function
|
|
2810
|
+
`}function vk(e,t="000000",o=X,s={}){return Ow`
|
|
2811
2811
|
<c:tx>
|
|
2812
2812
|
<c:rich>
|
|
2813
2813
|
<a:bodyPr />
|
|
@@ -2815,7 +2815,7 @@
|
|
|
2815
2815
|
<a:p>
|
|
2816
2816
|
<a:pPr lvl="0">
|
|
2817
2817
|
<a:defRPr b="${s?.bold?1:0}" i="${s?.italic?1:0}">
|
|
2818
|
-
${
|
|
2818
|
+
${fk(t)}
|
|
2819
2819
|
<a:latin typeface="+mn-lt"/>
|
|
2820
2820
|
</a:defRPr>
|
|
2821
2821
|
</a:pPr>
|
|
@@ -2826,26 +2826,26 @@
|
|
|
2826
2826
|
</a:p>
|
|
2827
2827
|
</c:rich>
|
|
2828
2828
|
</c:tx>
|
|
2829
|
-
`}function
|
|
2829
|
+
`}function bk(e=12,t="000000",o=!1,s=!1){return Ow`
|
|
2830
2830
|
<c:txPr>
|
|
2831
2831
|
<a:bodyPr/>
|
|
2832
2832
|
<a:lstStyle/>
|
|
2833
2833
|
<a:p>
|
|
2834
2834
|
<a:pPr lvl="0">
|
|
2835
2835
|
<a:defRPr ${Rw([["b",o?"1":"0"],["i",s?"1":"0"],["sz",100*e]])}>
|
|
2836
|
-
${
|
|
2836
|
+
${fk(t)}
|
|
2837
2837
|
<a:latin typeface="+mn-lt"/>
|
|
2838
2838
|
</a:defRPr>
|
|
2839
2839
|
</a:pPr>
|
|
2840
2840
|
</a:p>
|
|
2841
2841
|
</c:txPr>
|
|
2842
|
-
`}function
|
|
2842
|
+
`}function Sk(e){return e?"text"in e&&e.text?Ow`
|
|
2843
2843
|
<c:tx><c:v>${e.text}</c:v></c:tx>
|
|
2844
2844
|
`:"reference"in e&&e.reference?Ow`
|
|
2845
2845
|
<c:tx>
|
|
2846
|
-
${
|
|
2846
|
+
${wk(e.reference)}
|
|
2847
2847
|
</c:tx>
|
|
2848
|
-
`:Ow``:Ow``}function
|
|
2848
|
+
`:Ow``:Ow``}function yk({showLeaderLines:e}={showLeaderLines:!1}){return Ow`
|
|
2849
2849
|
<dLbls>
|
|
2850
2850
|
<c:showLegendKey val="0"/>
|
|
2851
2851
|
<c:showVal val="0"/>
|
|
@@ -2855,7 +2855,7 @@
|
|
|
2855
2855
|
<c:showBubbleSize val="0"/>
|
|
2856
2856
|
<c:showLeaderLines val="${e?"1":"0"}"/>
|
|
2857
2857
|
</dLbls>
|
|
2858
|
-
`}function
|
|
2858
|
+
`}function Ck(e,t,o,s,i,n,r=0){const a=i?.color?XS(i.color):n,l=i?.fontSize??K;return Ow`
|
|
2859
2859
|
<${t}>
|
|
2860
2860
|
<c:axId val="${o}"/>
|
|
2861
2861
|
<c:crossAx val="${s}"/> <!-- reference to the other axe of the chart -->
|
|
@@ -2867,34 +2867,34 @@
|
|
|
2867
2867
|
<c:axPos val="${e}" />
|
|
2868
2868
|
${function(e="B7B7B7"){return Ow`
|
|
2869
2869
|
<c:majorGridlines>
|
|
2870
|
-
${
|
|
2870
|
+
${mk({line:{color:e}})}
|
|
2871
2871
|
</c:majorGridlines>
|
|
2872
2872
|
`}()}
|
|
2873
2873
|
<c:majorTickMark val="out" />
|
|
2874
2874
|
<c:minorTickMark val="none" />
|
|
2875
2875
|
<c:numFmt formatCode="General" sourceLinked="1" />
|
|
2876
2876
|
<c:title>
|
|
2877
|
-
${
|
|
2877
|
+
${vk(i?.text??"",a,l,i)}
|
|
2878
2878
|
</c:title>
|
|
2879
|
-
${
|
|
2879
|
+
${bk(10,n)}
|
|
2880
2880
|
</${t}>
|
|
2881
2881
|
<!-- <tickLblPos/> omitted -->
|
|
2882
|
-
`}function
|
|
2882
|
+
`}function wk(e){return Ow`
|
|
2883
2883
|
<c:strRef>
|
|
2884
2884
|
<c:f>${e}</c:f>
|
|
2885
2885
|
</c:strRef>
|
|
2886
|
-
`}function
|
|
2886
|
+
`}function Ek(e){return Ow`
|
|
2887
2887
|
<c:numRef>
|
|
2888
2888
|
<c:f>${e}</c:f>
|
|
2889
2889
|
<c:numCache />
|
|
2890
2890
|
</c:numRef>
|
|
2891
|
-
`}function
|
|
2891
|
+
`}function xk(e,t){if(!e)return{attrs:[],node:Ow``};const o=function(e){switch(typeof e){case"boolean":return"b";case"string":return"str";case"number":return"n";default:return}}(t);if(void 0===o)return{attrs:[],node:Ow``};var s;return{attrs:[["t",o]],node:Ow`<f>${Rk(e)}</f><v>${(s=t)===Ri.InvalidReference?"#REF!":s}</v>`}}function Ik(e,t,o=!1){let s=e;const i=[],n=s.trim().toUpperCase();return!o&&["TRUE","FALSE"].includes(n)?(s="TRUE"===n?"1":"0",i.push(["t","b"])):!o&&oi(s,yi)||(s=CC(e,t),i.push(["t","s"])),{attrs:i,node:Ow`<v>${s}</v>`}}function Rk(e){let t;"="===e[0]&&(e=e.slice(1));try{t=_f(e)}catch(t){return e}return t=Of(t,"STRING",Tk),t=Of(t,"FUNCALL",(e=>e=function(e){const t=e.value.toUpperCase(),o=e.args,s=vy[t];if(s){const i=Gb.content[t].args.filter((e=>!e.optional)),n=i.length-e.args.length;if(n)for(let t=e.args.length;t<i.length;t++){const e=s[t-n];o.push({type:e.type,value:e.value})}}return{...e,args:o}}(e=function(e){const t=e.value.toUpperCase();return{...e,value:by.includes(t)?`_xlfn.${t}`:t}}(e={...e,value:e.value.toUpperCase()})))),t=Of(t,"REFERENCE",(e=>e.value===Ri.InvalidReference?{...e,value:"#REF!"}:e)),t?Nf(t):e}function Tk(e){const t=e.value.replace(new RegExp('"',"g"),""),o=Bs(t,yi);if(o){let s=[];return(Ms.test(t)||Ps.test(t))&&s.push("yyyy-mm-dd"),Ls.test(t)&&s.push("hh:mm:ss"),{...e,value:Qn(o.value,{format:s.join(" "),locale:yi})}}return{...e,value:e.value.replace(/\\"/g,'""')}}function Ak(e,t){const o=[];for(const s of t)switch(s.rule.type){case"CellIsRule":o.push(_k(s,s.rule,e));break;case"ColorScaleRule":o.push(Ok(s,s.rule));break;case"IconSetRule":o.push(Fk(s,s.rule));break;case"DataBarRule":o.push(Dk(s,s.rule));break;default:console.warn(`Conditional formatting ${s.rule.type} not implemented`)}return o}function _k(e,t,o){const s=Mk(e),i=mC(t.operator);s.push(...function(e){const t=mC(e.operator);switch(e.operator){case"ContainsText":case"NotContains":case"BeginsWith":case"EndsWith":return[["type",t],["text",e.values[0]]];case"IsEmpty":case"IsNotEmpty":return[["type",t]];case"Equal":case"NotEqual":case"GreaterThan":case"GreaterThanOrEqual":case"LessThan":case"LessThanOrEqual":case"Between":case"NotBetween":return[["type","cellIs"]]}}(t),["operator",i]);const n=function(e,t){const o=e[0].split(":")[0],s=t.values;switch(t.operator){case"ContainsText":return[`NOT(ISERROR(SEARCH("${s[0]}",${o})))`];case"NotContains":return[`ISERROR(SEARCH("${s[0]}",${o}))`];case"BeginsWith":return[`LEFT(${o},LEN("${s[0]}"))="${s[0]}"`];case"EndsWith":return[`RIGHT(${o},LEN("${s[0]}"))="${s[0]}"`];case"IsEmpty":return[`LEN(TRIM(${o}))=0`];case"IsNotEmpty":return[`LEN(TRIM(${o}))>0`];case"Equal":case"NotEqual":case"GreaterThan":case"GreaterThanOrEqual":case"LessThan":case"LessThanOrEqual":return[s[0]];case"Between":case"NotBetween":return[s[0],s[1]]}}(e.ranges,t).map((e=>Ow`<formula>${e}</formula>`)),r={font:{color:{rgb:t.style.textColor},bold:t.style.bold,italic:t.style.italic,strike:t.style.strikethrough,underline:t.style.underline}};return t.style.fillColor&&(r.fill={fgColor:{rgb:t.style.fillColor}}),s.push(["dxfId",CC(r,o)]),Ow`
|
|
2892
2892
|
<conditionalFormatting sqref="${e.ranges.join(" ")}">
|
|
2893
2893
|
<cfRule ${Rw(s)}>
|
|
2894
2894
|
${Dw(n)}
|
|
2895
2895
|
</cfRule>
|
|
2896
2896
|
</conditionalFormatting>
|
|
2897
|
-
`}function
|
|
2897
|
+
`}function Dk(e,t){const o=Mk(e);return o.push(["type","dataBar"]),Ow`
|
|
2898
2898
|
<conditionalFormatting sqref="${e.ranges.join(" ")}">
|
|
2899
2899
|
<cfRule ${Rw(o)}>
|
|
2900
2900
|
<dataBar>
|
|
@@ -2904,7 +2904,7 @@
|
|
|
2904
2904
|
</dataBar>
|
|
2905
2905
|
</cfRule>
|
|
2906
2906
|
</conditionalFormatting>
|
|
2907
|
-
`}function
|
|
2907
|
+
`}function Ok(e,t){const o=Mk(e);o.push(["type","colorScale"]);const s=[];for(const i of e.ranges){const e=[],n=[];let r=!0;for(let o of["minimum","midpoint","maximum"]){const s=t[o];s&&("formula"!==s.type?(e.push(Nk(s,o)),n.push([["rgb",XS(Ht(s.color))]])):r=!1)}if(!r){console.warn("Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.");continue}const a=e.map((e=>Ow`<cfvo ${Rw(e)}/>`)),l=n.map((e=>Ow`<color ${Rw(e)}/>`));s.push(Ow`
|
|
2908
2908
|
<conditionalFormatting sqref="${i}">
|
|
2909
2909
|
<cfRule ${Rw(o)}>
|
|
2910
2910
|
<colorScale>
|
|
@@ -2913,15 +2913,15 @@
|
|
|
2913
2913
|
</colorScale>
|
|
2914
2914
|
</cfRule>
|
|
2915
2915
|
</conditionalFormatting>
|
|
2916
|
-
`)}return Dw(s)}function
|
|
2916
|
+
`)}return Dw(s)}function Fk(e,t){const o=Mk(e);o.push(["type","iconSet"]);const s=[];for(const i of e.ranges){const e=[[["type","percent"],["val",0]]];let n=!0;for(let o of["lowerInflectionPoint","upperInflectionPoint"]){if("formula"===t[o].type){n=!1;continue}const s=t[o];e.push([...Nk(s,o),["gte","ge"===s.operator?"1":"0"]])}if(!n){console.warn("Conditional formats with formula rules are not supported at the moment. The rule is therefore skipped.");continue}const r=e.map((e=>Ow`<cfvo ${Rw(e)} />`));s.push(Ow`
|
|
2917
2917
|
<conditionalFormatting sqref="${i}">
|
|
2918
2918
|
<cfRule ${Rw(o)}>
|
|
2919
|
-
<iconSet iconSet="${
|
|
2919
|
+
<iconSet iconSet="${Pk(t.icons)}">
|
|
2920
2920
|
${Dw(r)}
|
|
2921
2921
|
</iconSet>
|
|
2922
2922
|
</cfRule>
|
|
2923
2923
|
</conditionalFormatting>
|
|
2924
|
-
`)}return Dw(s)}function
|
|
2924
|
+
`)}return Dw(s)}function Mk(e){return[["priority",1],["stopIfTrue",e.stopIfTrue?1:0]]}function Pk(e){return sy[Object.keys(sy).find((t=>e.upper.toLowerCase().startsWith(t)))||"dots"]}function Nk(e,t){const o=function(e,t){switch(e){case"value":return"minimum"===t?"min":"max";case"number":return"num";case"percentage":return"percent";default:return e}}(e.type,t),s=[["type",o]];if("min"!==o&&"max"!==o){let t=e.value;if("formula"===o)try{t=Rk(e.value)}catch(o){t=e.value}s.push(["val",t])}return s}function kk(e){const t=e.length;if(0===t)return[];const o=[new ey(`<dataValidations count="${t}">`)];for(const t of e)switch(t.criterion.type){case"dateIs":case"dateIsBefore":case"dateIsOnOrBefore":case"dateIsAfter":case"dateIsOnOrAfter":case"dateIsBetween":case"dateIsNotBetween":o.push(Lk(t));break;case"isEqual":case"isNotEqual":case"isGreaterThan":case"isGreaterOrEqualTo":case"isLessThan":case"isLessOrEqualTo":case"isBetween":case"isNotBetween":o.push(Vk(t));break;case"isValueInRange":case"isValueInList":o.push(Uk(t));break;case"customFormula":o.push(Hk(t));break;default:console.warn(`Data validation ${t.criterion.type} is not supported in xlsx.`)}return o.push(new ey("</dataValidations>")),o}function Lk(e){const t=e.criterion,o=Rk(t.values[0]),s=t.values[1]?Rk(t.values[1]):void 0,i=function(e){return Object.keys(Yy).find((t=>Yy[t]===e))}(e.criterion.type),n=Bk(e);return n.push(["type","date"],["operator",i]),s?Ow`
|
|
2925
2925
|
<dataValidation ${Rw(n)}>
|
|
2926
2926
|
<formula1>${Ui(o,yi)}</formula1>
|
|
2927
2927
|
<formula2>${Ui(s,yi)}</formula2>
|
|
@@ -2930,7 +2930,7 @@
|
|
|
2930
2930
|
<dataValidation ${Rw(n)}>
|
|
2931
2931
|
<formula1>${Ui(o,yi)}</formula1>
|
|
2932
2932
|
</dataValidation>
|
|
2933
|
-
`}function
|
|
2933
|
+
`}function Vk(e){const t=e.criterion,o=Rk(t.values[0]),s=t.values[1]?Rk(t.values[1]):void 0,i=function(e){return Object.keys(jy).find((t=>jy[t]===e))}(e.criterion.type),n=Bk(e);return n.push(["type","decimal"],["operator",i]),s?Ow`
|
|
2934
2934
|
<dataValidation ${Rw(n)}>
|
|
2935
2935
|
<formula1>${o}</formula1>
|
|
2936
2936
|
<formula2>${s}</formula2>
|
|
@@ -2939,19 +2939,19 @@
|
|
|
2939
2939
|
<dataValidation ${Rw(n)}>
|
|
2940
2940
|
<formula1>${o}</formula1>
|
|
2941
2941
|
</dataValidation>
|
|
2942
|
-
`}function
|
|
2942
|
+
`}function Uk(e){const t=e.criterion,o="isValueInRange"===e.criterion.type?Rk(t.values[0]):`"${t.values.join(",")}"`,s=Bk(e);return s.push(["type","list"]),Ow`
|
|
2943
2943
|
<dataValidation ${Rw(s)}>
|
|
2944
2944
|
<formula1>${o}</formula1>
|
|
2945
2945
|
</dataValidation>
|
|
2946
|
-
`}function
|
|
2946
|
+
`}function Hk(e){const t=Rk(e.criterion.values[0]),o=Bk(e);return o.push(["type","custom"]),Ow`
|
|
2947
2947
|
<dataValidation ${Rw(o)}>
|
|
2948
2948
|
<formula1>${t}</formula1>
|
|
2949
2949
|
</dataValidation>
|
|
2950
|
-
`}function
|
|
2950
|
+
`}function Bk(e){return[["allowBlank","1"],["showInputMessage","1"],["showErrorMessage","1"],["errorStyle",e.isBlocking?"":"warning"],["sqref",e.ranges.join(" ")]]}function zk(e,t,o){const s=[["xmlns:xdr",iy.drawing],["xmlns:r",cy],["xmlns:a",ny],["xmlns:c",ry]],i=[];for(const[s,n]of Object.entries(o))switch(n?.tag){case"chart":i.push(Gk(n,t,e[s]));break;case"image":i.push(qk(n,t,e[s]))}return Tw(Ow`
|
|
2951
2951
|
<xdr:wsDr ${Rw(s)}>
|
|
2952
2952
|
${Dw(i)}
|
|
2953
2953
|
</xdr:wsDr>
|
|
2954
|
-
`)}function
|
|
2954
|
+
`)}function $k(e,t){const{x:o,y:s,height:i,width:n}=e,r=Object.values(t.cols),a=Object.values(t.rows),{index:l,offset:c}=Wk(r,o),{index:h,offset:d}=Wk(r,o+n),{index:u,offset:g}=Wk(a,s),{index:p,offset:m}=Wk(a,s+i);return{from:{col:l,colOff:c,row:u,rowOff:g},to:{col:h,colOff:d,row:p,rowOff:m}}}function Wk(e,t){let o=0;for(const[s,i]of e.entries()){if(o<=t&&t<o+i.size)return{index:s,offset:RC(t-o+ye)};s<e.length-1&&(o+=i.size)}return{index:e.length-1,offset:RC(t-o+ye)}}function Gk(e,t,o){const{from:s,to:i}=$k(e,t),n=EC(e.id),r=[["id",n],["name",`Chart ${n}`],["title","Chart"]];return Ow`
|
|
2955
2955
|
<xdr:twoCellAnchor>
|
|
2956
2956
|
<xdr:from>
|
|
2957
2957
|
<xdr:col>${s.col}</xdr:col>
|
|
@@ -2982,7 +2982,7 @@
|
|
|
2982
2982
|
</xdr:graphicFrame>
|
|
2983
2983
|
<xdr:clientData fLocksWithSheet="0"/>
|
|
2984
2984
|
</xdr:twoCellAnchor>
|
|
2985
|
-
`}function
|
|
2985
|
+
`}function qk(e,t,o){const{from:s,to:i}=$k(e,t),n=IC(e.id),r=[["id",n],["name",`Image ${n}`],["title","Image"]],a=RC(e.width),l=RC(e.height);return Ow`
|
|
2986
2986
|
<xdr:twoCellAnchor editAs="oneCell">
|
|
2987
2987
|
<xdr:from>
|
|
2988
2988
|
<xdr:col>${s.col}</xdr:col>
|
|
@@ -3019,7 +3019,7 @@
|
|
|
3019
3019
|
</xdr:pic>
|
|
3020
3020
|
<xdr:clientData fLocksWithSheet="0"/>
|
|
3021
3021
|
</xdr:twoCellAnchor>
|
|
3022
|
-
`}function
|
|
3022
|
+
`}function Zk(e){return ct(e)?Ow``:Ow`
|
|
3023
3023
|
<font>
|
|
3024
3024
|
${e.bold?Ow`<b />`:""}
|
|
3025
3025
|
${e.italic?Ow`<i />`:""}
|
|
@@ -3029,15 +3029,15 @@
|
|
|
3029
3029
|
${e.color&&e.color.rgb?Ow`<color rgb="${XS(e.color.rgb)}" />`:""}
|
|
3030
3030
|
${e.name?Ow`<name val="${e.name}" />`:""}
|
|
3031
3031
|
</font>
|
|
3032
|
-
`}function
|
|
3032
|
+
`}function jk(e){return e?Rw([["style",e.style]]):Ow``}function Yk(e){return e?Ow`
|
|
3033
3033
|
<color ${Rw([["rgb",XS(e.color.rgb)]])}/>
|
|
3034
|
-
`:Ow``}function
|
|
3034
|
+
`:Ow``}function Xk(e,t,o){const s=Ow`
|
|
3035
3035
|
<table ${Rw([["id",t],["name",`Table${t}`],["displayName",`Table${t}`],["ref",e.range],["headerRowCount",e.config.numberOfHeaders],["totalsRowCount",e.config.totalRow?1:0],["xmlns",iy.table],["xmlns:xr",iy.revision],["xmlns:xr3",iy.revision3],["xmlns:mc",iy.markupCompatibility]])}>
|
|
3036
3036
|
${e.config.hasFilters?function(e){const t=[["ref",e.range]];return Ow`
|
|
3037
3037
|
<autoFilter ${Rw(t)}>
|
|
3038
3038
|
${Dw(function(e){const t=[];for(const o of e.filters){const e=Ow`
|
|
3039
3039
|
<filterColumn ${Rw([["colId",o.colId]])}>
|
|
3040
|
-
${
|
|
3040
|
+
${Kk(o)}
|
|
3041
3041
|
</filterColumn>
|
|
3042
3042
|
`;t.push(e)}return t}(e))}
|
|
3043
3043
|
</autoFilter>
|
|
@@ -3049,17 +3049,17 @@
|
|
|
3049
3049
|
`}(e,o)}
|
|
3050
3050
|
${function(e){const t=[["name",e.config.styleId],["showFirstColumn",e.config.firstColumn?1:0],["showLastColumn",e.config.lastColumn?1:0],["showRowStripes",e.config.bandedRows?1:0],["showColumnStripes",e.config.bandedColumns?1:0]];return Ow`<tableStyleInfo ${Rw(t)}/>`}(e)}
|
|
3051
3051
|
</table>
|
|
3052
|
-
`;return Tw(s)}function
|
|
3052
|
+
`;return Tw(s)}function Kk(e){const t=e.displayedValues.map((e=>Ow`<filter ${Rw([["val",e]])}/>`));return Ow`
|
|
3053
3053
|
<filters ${Rw(e.displayBlanks?[["blank",1]]:[])}>
|
|
3054
3054
|
${Dw(t)}
|
|
3055
3055
|
</filters>
|
|
3056
|
-
`}function
|
|
3056
|
+
`}function Jk(e){if(!Object.values(e).length)return Ow``;const t=[];for(let[o,s]of Object.entries(e)){const e=[["min",parseInt(o)+1],["max",parseInt(o)+1],["width",vC(s.size||oe)],["customWidth",1],["hidden",s.isHidden?1:0]];s.outlineLevel&&e.push(["outlineLevel",s.outlineLevel]),s.collapsed&&e.push(["collapsed",1]),t.push(Ow`
|
|
3057
3057
|
<col ${Rw(e)}/>
|
|
3058
3058
|
`)}return Ow`
|
|
3059
3059
|
<cols>
|
|
3060
3060
|
${Dw(t)}
|
|
3061
3061
|
</cols>
|
|
3062
|
-
`}function
|
|
3062
|
+
`}function Qk(e,t,o){const s=[];for(let i=0;i<o.rowNumber;i++){const n=[["r",i+1]],r=o.rows[i]||{};r.size&&r.size!==se&&n.push(["ht",fC(r.size)],["customHeight",1]),r.isHidden&&n.push(["hidden",1]),r.outlineLevel&&n.push(["outlineLevel",r.outlineLevel]),r.collapsed&&n.push(["collapsed",1]);const a=new g_(Is(o.id,o.styles)),l=new g_(Is(o.id,o.borders)),c=new g_(Is(o.id,o.formats)),h=[];for(let s=0;s<o.colNumber;s++){const n=Co(s,i),r=o.cells[n],d=o.cellValues[n],u={sheetId:o.id,col:s,row:i},g=a.get(u),p=c.get(u),m=l.get(u);if(r||g||p||m||void 0!==d){const a=[["r",n]],l=SC(e,bC(t,r,g,p,m));l&&a.push(["s",l]);let c=[],u=Ow``;if(r?.startsWith("=")&&void 0!==d){const e=xk(r,d);if(!e)continue;({attrs:c,node:u}=e)}else if(r&&Qe(r)){const{label:t}=ot(r);({attrs:c,node:u}=Ik(t,e.sharedStrings))}else if(r&&""!==r){const n=eL(s,i,o),a=tL(s,i,o),l=!(!p||!Ir(t.formats[p]));({attrs:c,node:u}=Ik(r,e.sharedStrings,n||a||l))}a.push(...c),h.push(Ow`<c ${Rw(a)}>
|
|
3063
3063
|
${u}
|
|
3064
3064
|
</c>`)}}(h.length||r.size!==se||r.isHidden||r.outlineLevel||r.collapsed)&&s.push(Ow`
|
|
3065
3065
|
<row ${Rw(n)}>
|
|
@@ -3069,7 +3069,7 @@
|
|
|
3069
3069
|
<sheetData>
|
|
3070
3070
|
${Dw(s)}
|
|
3071
3071
|
</sheetData>
|
|
3072
|
-
`}function
|
|
3072
|
+
`}function eL(e,t,o){return o.tables.some((o=>{const s=Xo(o.range),i={...s,bottom:s.top};return ls(e,t,i)}))}function tL(e,t,o){return o.tables.some((o=>{if(!o.config.totalRow)return!1;const s=Xo(o.range),i={...s,top:s.bottom};return ls(e,t,i)}))}function oL(e,t,o){const s=t.sheets[o].cells,i=[];for(const n in s){const r=s[n];if(r&&Qe(r)){const{label:s,url:a}=ot(r);if(it(a)){const e=rt(a),o=t.sheets.find((t=>t.id===e)),r=[["display",s],["location",o?`${o.name}!A1`:Ri.InvalidReference],["ref",n]];i.push(Ow`
|
|
3073
3073
|
<hyperlink ${Rw(r)}/>
|
|
3074
3074
|
`)}else{const t=[["r:id",yC(e.relsFiles,`xl/worksheets/_rels/sheet${o}.xml.rels`,{target:wn(a),type:ly.hyperlink,targetMode:"External"})],["ref",n]];i.push(Ow`
|
|
3075
3075
|
<hyperlink ${Rw(t)}/>
|
|
@@ -3077,11 +3077,11 @@
|
|
|
3077
3077
|
<hyperlinks>
|
|
3078
3078
|
${Dw(i)}
|
|
3079
3079
|
</hyperlinks>
|
|
3080
|
-
`:Ow``}function
|
|
3080
|
+
`:Ow``}function sL(e){if(e.length){const t=e.map((e=>Ow`<mergeCell ref="${e}" />`));return Ow`
|
|
3081
3081
|
<mergeCells count="${e.length}">
|
|
3082
3082
|
${Dw(t)}
|
|
3083
3083
|
</mergeCells>
|
|
3084
|
-
`}return Ow``}function
|
|
3084
|
+
`}return Ow``}function iL(e){const t=e.panes;let o=Ow``;if(t&&(t.xSplit||t.ySplit)){const e=Co(t.xSplit,t.ySplit),s=t.xSplit?Ow`xSplit="${t.xSplit}"`:"",i=t.ySplit?Ow`ySplit="${t.ySplit}"`:"",n=t.xSplit?Ow`<selection pane="topRight"/>`:"",r=t.ySplit?Ow`<selection pane="bottomLeft"/>`:"",a=t.xSplit&&t.ySplit?Ow`<selection pane="bottomRight"/>`:"";o=Ow`
|
|
3085
3085
|
<pane
|
|
3086
3086
|
${s}
|
|
3087
3087
|
${i}
|
|
@@ -3097,11 +3097,11 @@
|
|
|
3097
3097
|
${o}
|
|
3098
3098
|
</sheetView>
|
|
3099
3099
|
</sheetViews>
|
|
3100
|
-
`}function
|
|
3100
|
+
`}function nL(e){return e.color?Ow`
|
|
3101
3101
|
<sheetPr>
|
|
3102
3102
|
<tabColor ${Rw([["rgb",XS(e.color)]])} />
|
|
3103
3103
|
</sheetPr>
|
|
3104
|
-
`:""}function
|
|
3104
|
+
`:""}function rL(e){const t=[],o=function(e){const t=[{},...Object.values(e.borders).map((e=>({left:Aw(e.left),right:Aw(e.right),bottom:Aw(e.bottom),top:Aw(e.top)})))];return{relsFiles:[],sharedStrings:[],styles:[{fontId:0,fillId:0,numFmtId:0,borderId:0,alignment:{}}],fonts:[{size:me,family:2,color:{rgb:"000000"},name:"Arial"}],fills:[{reservedAttribute:"none"},{reservedAttribute:"gray125"}],borders:t,numFmts:[],dxfs:[]}}(e=function(e){for(const t of e.sheets)t.tables=t.tables.filter((e=>hs(Xo(e.range)).numberOfRows>1));return e}(e=function(e){const t={},o=[];for(const s of e.sheets){let e=s.name.slice(0,31);e=Nt(e,o,{compute:(e,t)=>e.slice(0,31-String(t).length)+t}),o.push(e),e!==s.name&&(t[s.name]=e,s.name=e)}if(!Object.keys(t).length)return e;const s=Object.keys(t).sort(((e,t)=>t.length-e.length));let i=JSON.stringify(e);for(const e of s){const o=new RegExp(`'?${He(e)}'?!`,"g");i=i.replaceAll(o,(o=>{const s=t[e];return o.replace(e,s)}))}return JSON.parse(i)}(e)));return t.push(function(e,t){const o=[["xmlns",iy.workbook],["xmlns:r",cy]],s=[];for(const[o,i]of Object.entries(e.sheets)){const e=[["state",i.isVisible?"visible":"hidden"],["name",i.name],["sheetId",parseInt(o)+1],["r:id",`rId${parseInt(o)+1}`]];s.push(Ow`
|
|
3105
3105
|
<sheet ${Rw(e)} />
|
|
3106
3106
|
`),yC(t.relsFiles,"xl/_rels/workbook.xml.rels",{type:ly.sheet,target:`worksheets/sheet${o}.xml`})}return xw(Tw(Ow`
|
|
3107
3107
|
<workbook ${Rw(o)}>
|
|
@@ -3109,17 +3109,17 @@
|
|
|
3109
3109
|
${Dw(s)}
|
|
3110
3110
|
</sheets>
|
|
3111
3111
|
</workbook>
|
|
3112
|
-
`),"xl/workbook.xml","workbook")}(e,o)),t.push(...function(e,t){const o=[];let s=1;for(const[i,n]of Object.entries(e.sheets)){const r=[["xmlns",iy.worksheet],["xmlns:r",cy]],a=[["defaultRowHeight",fC(se)],["defaultColWidth",vC(oe)]],l=
|
|
3112
|
+
`),"xl/workbook.xml","workbook")}(e,o)),t.push(...function(e,t){const o=[];let s=1;for(const[i,n]of Object.entries(e.sheets)){const r=[["xmlns",iy.worksheet],["xmlns:r",cy]],a=[["defaultRowHeight",fC(se)],["defaultColWidth",vC(oe)]],l=aL(n,i,s,t,o);s+=n.tables.length;let c=Ow``;const h=[];for(const s of n.charts){const n=EC(s.id),r=yC(t.relsFiles,`xl/drawings/_rels/drawing${i}.xml.rels`,{target:`../charts/chart${n}.xml`,type:ly.chart});h.push(r),o.push(xw(pk(s,i,e),`xl/charts/chart${n}.xml`,"chart"))}for(const e of n.images){const s=e.data.mimetype;if(void 0===s)continue;const n=qy[s];if(void 0===n)continue;let r=`image${IC(e.id)}.${n}`;const a=yC(t.relsFiles,`xl/drawings/_rels/drawing${i}.xml.rels`,{target:`../media/${r}`,type:ly.image});h.push(a),o.push({path:`xl/media/${r}`,imageSrc:e.data.path})}const d=[...n.charts,...n.images];if(d.length){const e=yC(t.relsFiles,`xl/worksheets/_rels/sheet${i}.xml.rels`,{target:`../drawings/drawing${i}.xml`,type:ly.drawing});o.push(xw(zk(h,n,d),`xl/drawings/drawing${i}.xml`,"drawing")),c=Ow`<drawing r:id="${e}" />`}const u=Ow`
|
|
3113
3113
|
<worksheet ${Rw(r)}>
|
|
3114
|
+
${nL(n)}
|
|
3114
3115
|
${iL(n)}
|
|
3115
|
-
${sL(n)}
|
|
3116
3116
|
<sheetFormatPr ${Rw(a)} />
|
|
3117
|
-
${
|
|
3118
|
-
${
|
|
3119
|
-
${
|
|
3120
|
-
${Dw(
|
|
3121
|
-
${Dw(
|
|
3122
|
-
${
|
|
3117
|
+
${Jk(n.cols)}
|
|
3118
|
+
${Qk(t,e,n)}
|
|
3119
|
+
${sL(n.merges)}
|
|
3120
|
+
${Dw(Ak(t.dxfs,n.conditionalFormats))}
|
|
3121
|
+
${Dw(kk(n.dataValidationRules))}
|
|
3122
|
+
${oL(t,e,i)}
|
|
3123
3123
|
${c}
|
|
3124
3124
|
${l}
|
|
3125
3125
|
</worksheet>
|
|
@@ -3134,7 +3134,7 @@
|
|
|
3134
3134
|
`}(e.numFmts)}
|
|
3135
3135
|
${o=e.fonts,Ow`
|
|
3136
3136
|
<fonts count="${o.length}">
|
|
3137
|
-
${Dw(Object.values(o).map(
|
|
3137
|
+
${Dw(Object.values(o).map(Zk))}
|
|
3138
3138
|
</fonts>
|
|
3139
3139
|
`}
|
|
3140
3140
|
${function(e){const t=[];for(let o of Object.values(e))void 0!==o.reservedAttribute?t.push(Ow`
|
|
@@ -3155,20 +3155,20 @@
|
|
|
3155
3155
|
`}(e.fills)}
|
|
3156
3156
|
${function(e){const t=[];for(let o of Object.values(e))t.push(Ow`
|
|
3157
3157
|
<border>
|
|
3158
|
-
<left ${
|
|
3159
|
-
${
|
|
3158
|
+
<left ${jk(o.left)}>
|
|
3159
|
+
${Yk(o.left)}
|
|
3160
3160
|
</left>
|
|
3161
|
-
<right ${
|
|
3162
|
-
${
|
|
3161
|
+
<right ${jk(o.right)}>
|
|
3162
|
+
${Yk(o.right)}
|
|
3163
3163
|
</right>
|
|
3164
|
-
<top ${
|
|
3165
|
-
${
|
|
3164
|
+
<top ${jk(o.top)}>
|
|
3165
|
+
${Yk(o.top)}
|
|
3166
3166
|
</top>
|
|
3167
|
-
<bottom ${
|
|
3168
|
-
${
|
|
3167
|
+
<bottom ${jk(o.bottom)}>
|
|
3168
|
+
${Yk(o.bottom)}
|
|
3169
3169
|
</bottom>
|
|
3170
|
-
<diagonal ${
|
|
3171
|
-
${
|
|
3170
|
+
<diagonal ${jk(o.diagonal)}>
|
|
3171
|
+
${Yk(o.diagonal)}
|
|
3172
3172
|
</diagonal>
|
|
3173
3173
|
</border>
|
|
3174
3174
|
`);return Ow`
|
|
@@ -3181,7 +3181,7 @@
|
|
|
3181
3181
|
${Dw(t)}
|
|
3182
3182
|
</cellXfs>
|
|
3183
3183
|
`}(e.styles)}
|
|
3184
|
-
${function(e){const t=[];for(const o of e){let e=Ow``;o.font&&(e=
|
|
3184
|
+
${function(e){const t=[];for(const o of e){let e=Ow``;o.font&&(e=Zk(o.font));let s=Ow``;o.fill&&(s=Ow`
|
|
3185
3185
|
<fill>
|
|
3186
3186
|
<patternFill>
|
|
3187
3187
|
<bgColor rgb="${XS(o.fill.fgColor.rgb)}" />
|
|
@@ -3221,8 +3221,8 @@
|
|
|
3221
3221
|
<Relationships xmlns="${iy.Relationships}">
|
|
3222
3222
|
<Relationship ${Rw(e)} />
|
|
3223
3223
|
</Relationships>
|
|
3224
|
-
`),"_rels/.rels")}()),{name:"my_spreadsheet.xlsx",files:t}}function
|
|
3224
|
+
`),"_rels/.rels")}()),{name:"my_spreadsheet.xlsx",files:t}}function aL(e,t,o,s,i){let n=o;if(!e.tables.length)return new ey("");const r=`xl/worksheets/_rels/sheet${t}.xml.rels`,a=[];for(const t of e.tables){const o=yC(s.relsFiles,r,{target:`../tables/table${n}.xml`,type:ly.table});i.push(xw(Xk(t,n,e),`xl/tables/table${n}.xml`,"table")),a.push(Ow`<tablePart r:id="${o}" />`),n++}return Ow`
|
|
3225
3225
|
<tableParts count="${e.tables.length}">
|
|
3226
3226
|
${Dw(a)}
|
|
3227
3227
|
</tableParts>
|
|
3228
|
-
`}var aL;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(aL||(aL={}));function lL(e,t={}){const o=Be(t);return o.type=e,o}const cL={},hL={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:ee,HEADER_WIDTH:te,BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:oe,DEFAULT_CELL_HEIGHT:se,SCROLLBAR_WIDTH:ie},dL={autoCompleteProviders:Th,autofillModifiersRegistry:RS,autofillRulesRegistry:TS,cellMenuRegistry:JT,colMenuRegistry:z_,errorTypes:Ti,linkMenuRegistry:pR,functionRegistry:Gb,featurePluginRegistry:SN,iconsOnCellRegistry:yy,statefulUIPluginRegistry:yN,coreViewsPluginRegistry:CN,corePluginRegistry:bN,rowMenuRegistry:q_,sidePanelRegistry:$F,figureRegistry:bI,chartSidePanelComponentRegistry:iO,chartComponentRegistry:dI,chartRegistry:hI,chartSubtypeRegistry:gI,topbarMenuRegistry:j_,topbarComponentRegistry:WF,clickableCellRegistry:wN,otRegistry:Y_,inverseCommandRegistry:wI,urlRegistry:En,cellPopoverRegistry:PS,numberFormatMenuRegistry:$_,repeatLocalCommandTransformRegistry:pN,repeatCommandTransformRegistry:gN,clipboardHandlersRegistries:gc,pivotRegistry:mF,pivotTimeAdapterRegistry:Al,pivotSidePanelRegistry:SF,pivotNormalizationValueRegistry:ic,supportedPivotPositionalFormulaRegistry:IS,pivotToFunctionValueRegistry:nc,migrationStepRegistry:Qw},uL={arg:Oh,isEvaluationError:Li,toBoolean:Xi,toJsDate:Ki,toNumber:Ui,toString:Zi,toNormalizedPivotValue:ec,toXC:Co,toZone:Xo,toUnboundedZone:Yo,toCartesian:yo,numberToLetters:vo,lettersToNumber:bo,UuidGenerator:la,formatValue:Qn,createCurrencyFormat:gr,ColorGenerator:uo,computeTextWidth:Yr,createEmptyWorkbookData:aE,createEmptySheet:rE,createEmptyExcelSheet:lE,rgbaToHex:Zt,colorToRGBA:jt,positionToZone:vs,isDefined:at,isMatrix:wi,lazy:ut,genericRepeat:mN,createAction:i,createActions:o,transformRangeData:mc,deepEquals:mt,overlap:as,union:is,isInside:ls,deepCopy:Be,expandZoneOnInsertion:es,reduceZoneOnDeletion:ss,unquote:$e,getMaxObjectId:ql,getFunctionsFromTokens:vS,getFirstPivotFunction:ES,getNumberOfPivotFunctions:xS,parseDimension:Yl,isDateOrDatetimeField:Xl,makeFieldProposal:SS,insertTokenAfterArgSeparator:yS,insertTokenAfterLeftParenthesis:CS,mergeContiguousZones:ws,getPivotHighlights:Z_,pivotTimeAdapter:_l,UNDO_REDO_PIVOT_COMMANDS:HP,createPivotFormula:Ql,areDomainArgsFieldsValid:Jl,splitReference:Zo,sanitizeSheetName:Ge,getUniqueText:Nt,isNumber:oi,isDateTime:Us},gL={isMarkdownLink:Qe,parseMarkdownLink:ot,markdownLink:tt,openLink:An,urlRepresentation:Tn},pL={Checkbox:HI,Section:X_,RoundColorPicker:ID,ChartDataSeries:cD,ChartErrorSection:dD,ChartLabelRange:uD,ChartTitle:ED,ChartPanel:aO,ChartFigure:mI,ChartJsComponent:dh,Grid:WM,GridOverlay:EM,ScorecardChart:Rh,LineConfigPanel:JD,BarConfigPanel:pD,PieChartDesignPanel:QD,GenericChartConfigPanel:gD,ChartWithAxisDesignPanel:OD,GaugeChartConfigPanel:MD,GaugeChartDesignPanel:ZD,ScorecardChartConfigPanel:tO,ScorecardChartDesignPanel:oO,RadarChartDesignPanel:eO,WaterfallChartDesignPanel:sO,ComboChartDesignPanel:FD,ChartTypePicker:nO,FigureComponent:GF,Menu:mR,Popover:PI,SelectionInput:lD,ValidationMessages:hD,AddDimensionButton:WO,PivotDimensionGranularity:jO,PivotDimensionOrder:YO,PivotDimension:ZO,PivotLayoutConfigurator:JO,PivotDeferUpdate:$O,PivotTitleSection:QO,CogWheelMenu:qO,TextInput:GO,SidePanelCollapsible:fD,RadioSelection:AD},mL={useDragAndDropListItems:Q_,useHighlights:dO,useHighlightsOnHover:hO},fL={useStoreProvider:yc,DependencyContainer:vc,CellPopoverStore:AI,ComposerFocusStore:Oc,CellComposerStore:oM,FindAndReplaceStore:LO,HighlightStore:Jb,HoveredCellStore:TI,ModelStore:Rc,NotificationStore:Qb,RendererStore:Ac,SelectionInputStore:aD,SpreadsheetStore:_c,useStore:Cc,useLocalStore:wc,SidePanelStore:HM,PivotSidePanelStore:vF,PivotMeasureDisplayPanelStore:BO};const vL={DEFAULT_LOCALE:yi,HIGHLIGHT_COLOR:a,PIVOT_TABLE_CONFIG:ke,ChartTerms:mE},bL={...ER,...Bx};e.AbstractCellClipboardHandler=ga,e.AbstractChart=uh,e.AbstractFigureClipboardHandler=hc,e.CellErrorType=Ri,e.CorePlugin=qM,e.CoreViewPlugin=eP,e.DispatchResult=fi,e.EvaluationError=Ai,e.Model=class extends fc{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 la,n=!1){const r=performance.now();console.debug("##### Model creation #####"),super(),Do===Ao&&Oo===_o&&(Oo=()=>!0),s=iE(e,s);const a=sE(e,n);this.state=new lk,this.uuidGenerator=i,this.config=this.setupConfig(o),this.session=this.setupSession(a.revisionId),this.coreGetters={},this.range=new JM(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.coreGetters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.coreGetters.getRangeDataFromXc=this.range.getRangeDataFromXc.bind(this.range),this.coreGetters.getRangeDataFromZone=this.range.getRangeDataFromZone.bind(this.range),this.coreGetters.getRangeFromRangeData=this.range.getRangeFromRangeData.bind(this.range),this.coreGetters.getRangeFromZone=this.range.getRangeFromZone.bind(this.range),this.coreGetters.recomputeRanges=this.range.recomputeRanges.bind(this.range),this.coreGetters.isRangeValid=this.range.isRangeValid.bind(this.range),this.coreGetters.extendRange=this.range.extendRange.bind(this.range),this.coreGetters.getRangesUnion=this.range.getRangesUnion.bind(this.range),this.coreGetters.removeRangesSheetPrefix=this.range.removeRangesSheetPrefix.bind(this.range),this.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 rk(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.coreViewPluginConfig=this.setupCoreViewPluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(let e of bN.getAll())this.setupCorePlugin(e,a);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(s);for(let e of CN.getAll()){const t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(let e of yN.getAll()){const t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(let e of SN.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(let 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(let 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(let 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(let t of e){const e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new oN(sk({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:Mo("Anonymous").toString()},o=e.transportService||new YN;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(Si));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=mi(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return t.some((e=>"Success"!==e))?new fi(t.flat()):fi.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(lL(e,t));dispatch=(e,t)=>{const o=lL(e,t);let s=this.status;if(this.getters.isReadonly()&&(i=o,!gi.has(i.type)))return new fi("Readonly");var i;if(!this.session.canApplyOptimisticUpdate())return new fi("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();mi(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(mi(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(mi(o))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,o)}return fi.Success};dispatchFromCorePlugin=(e,t)=>{const o=lL(e,t),s=this.status;this.status=2;const i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,o),this.status=s,fi.Success};dispatchToHandlers(e,t){const o=mi(t);for(const s of e)!o&&s instanceof qM||s.beforeHandle(t);for(const s of e)!o&&s instanceof qM||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=aE();for(let t of this.handlers)t instanceof qM&&t.export(e);return e.revisionId=this.session.getRevisionId()||Se,e=Be(e),e}updateMode(e){this.config.mode=e,this.trigger("update")}exportXLSX(){this.dispatch("EVALUATE_CELLS");let e={...aE(),sheets:[lE(oE,"Sheet1")]};for(let t of this.handlers)t instanceof GM&&t.exportForExcel(e);return e=Be(e),nL(e)}garbageCollectExternalResources(){for(const e of this.corePlugins)e.garbageCollectExternalResources()}},e.PivotRuntimeDefinition=eF,e.Registry=n,e.Revision=eN,e.SPREADSHEET_DIMENSIONS=hL,e.Spreadsheet=jN,e.SpreadsheetPivotTable=sF,e.UIPlugin=zP,e.__info__=cL,e.addFunction=function e(t,o){return Gb.add(t,o),{addFunction:(t,o)=>e(t,o)}},e.addRenderingLayer=function(e,t){if(xi[e])throw new Error(`Layer ${e} already exists`);xi[e]=t},e.astToFormula=Nf,e.chartHelpers=bL,e.compile=uS,e.compileTokens=gS,e.components=pL,e.constants=vL,e.convertAstNodes=Of,e.coreTypes=pi,e.findCellInNewZone=fs,e.functionCache=dS,e.helpers=uL,e.hooks=mL,e.invalidateCFEvaluationCommands=di,e.invalidateDependenciesCommands=hi,e.invalidateEvaluationCommands=li,e.iterateAstNodes=Ff,e.links=gL,e.load=sE,e.parse=_f,e.parseTokens=Df,e.readonlyAllowedCommands=gi,e.registries=dL,e.setDefaultSheetViewSize=function(e){Fe=e},e.setTranslationMethod=function(e,t=(()=>!0)){Do=e,Oo=t},e.stores=fL,e.tokenColors=oS,e.tokenize=va,cL.version="18.3.0-alpha.1",cL.date="2025-02-25T06:00:14.885Z",cL.hash="be4d957"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);
|
|
3228
|
+
`}var lL;!function(e){e[e.Ready=0]="Ready",e[e.Running=1]="Running",e[e.RunningCore=2]="RunningCore",e[e.Finalizing=3]="Finalizing"}(lL||(lL={}));function cL(e,t={}){const o=Be(t);return o.type=e,o}const hL={},dL={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:ee,HEADER_WIDTH:te,BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:oe,DEFAULT_CELL_HEIGHT:se,SCROLLBAR_WIDTH:ie},uL={autoCompleteProviders:Th,autofillModifiersRegistry:RS,autofillRulesRegistry:TS,cellMenuRegistry:JT,colMenuRegistry:z_,errorTypes:Ti,linkMenuRegistry:pR,functionRegistry:Gb,featurePluginRegistry:yN,iconsOnCellRegistry:yy,statefulUIPluginRegistry:CN,coreViewsPluginRegistry:wN,corePluginRegistry:SN,rowMenuRegistry:q_,sidePanelRegistry:WF,figureRegistry:bI,chartSidePanelComponentRegistry:iO,chartComponentRegistry:dI,chartRegistry:hI,chartSubtypeRegistry:gI,topbarMenuRegistry:j_,topbarComponentRegistry:GF,clickableCellRegistry:EN,otRegistry:Y_,inverseCommandRegistry:wI,urlRegistry:En,cellPopoverRegistry:PS,numberFormatMenuRegistry:$_,repeatLocalCommandTransformRegistry:mN,repeatCommandTransformRegistry:pN,clipboardHandlersRegistries:gc,pivotRegistry:fF,pivotTimeAdapterRegistry:Al,pivotSidePanelRegistry:yF,pivotNormalizationValueRegistry:ic,supportedPivotPositionalFormulaRegistry:IS,pivotToFunctionValueRegistry:nc,migrationStepRegistry:Qw},gL={arg:Oh,isEvaluationError:Li,toBoolean:Xi,toJsDate:Ki,toNumber:Ui,toString:Zi,toNormalizedPivotValue:ec,toXC:Co,toZone:Xo,toUnboundedZone:Yo,toCartesian:yo,numberToLetters:vo,lettersToNumber:bo,UuidGenerator:la,formatValue:Qn,createCurrencyFormat:gr,ColorGenerator:uo,computeTextWidth:Yr,createEmptyWorkbookData:aE,createEmptySheet:rE,createEmptyExcelSheet:lE,rgbaToHex:Zt,colorToRGBA:jt,positionToZone:vs,isDefined:at,isMatrix:wi,lazy:ut,genericRepeat:fN,createAction:i,createActions:o,transformRangeData:mc,deepEquals:mt,overlap:as,union:is,isInside:ls,deepCopy:Be,expandZoneOnInsertion:es,reduceZoneOnDeletion:ss,unquote:$e,getMaxObjectId:ql,getFunctionsFromTokens:vS,getFirstPivotFunction:ES,getNumberOfPivotFunctions:xS,parseDimension:Yl,isDateOrDatetimeField:Xl,makeFieldProposal:SS,insertTokenAfterArgSeparator:yS,insertTokenAfterLeftParenthesis:CS,mergeContiguousZones:ws,getPivotHighlights:Z_,pivotTimeAdapter:_l,UNDO_REDO_PIVOT_COMMANDS:BP,createPivotFormula:Ql,areDomainArgsFieldsValid:Jl,splitReference:Zo,sanitizeSheetName:Ge,getUniqueText:Nt,isNumber:oi,isDateTime:Us},pL={isMarkdownLink:Qe,parseMarkdownLink:ot,markdownLink:tt,openLink:An,urlRepresentation:Tn},mL={Checkbox:HI,Section:X_,RoundColorPicker:ID,ChartDataSeries:cD,ChartErrorSection:dD,ChartLabelRange:uD,ChartTitle:ED,ChartPanel:aO,ChartFigure:mI,ChartJsComponent:dh,Grid:GM,GridOverlay:xM,ScorecardChart:Rh,LineConfigPanel:JD,BarConfigPanel:pD,PieChartDesignPanel:QD,GenericChartConfigPanel:gD,ChartWithAxisDesignPanel:OD,GaugeChartConfigPanel:MD,GaugeChartDesignPanel:ZD,ScorecardChartConfigPanel:tO,ScorecardChartDesignPanel:oO,RadarChartDesignPanel:eO,WaterfallChartDesignPanel:sO,ComboChartDesignPanel:FD,ChartTypePicker:nO,FigureComponent:qF,Menu:mR,Popover:PI,SelectionInput:lD,ValidationMessages:hD,AddDimensionButton:GO,PivotDimensionGranularity:YO,PivotDimensionOrder:XO,PivotDimension:jO,PivotLayoutConfigurator:QO,PivotDeferUpdate:$O,PivotTitleSection:eF,CogWheelMenu:ZO,TextInput:qO,SidePanelCollapsible:fD,RadioSelection:AD},fL={useDragAndDropListItems:Q_,useHighlights:dO,useHighlightsOnHover:hO},vL={useStoreProvider:yc,DependencyContainer:vc,CellPopoverStore:AI,ComposerFocusStore:Oc,CellComposerStore:sM,FindAndReplaceStore:LO,HighlightStore:Jb,HoveredCellStore:TI,ModelStore:Rc,NotificationStore:Qb,RendererStore:Ac,SelectionInputStore:aD,SpreadsheetStore:_c,useStore:Cc,useLocalStore:wc,SidePanelStore:BM,PivotSidePanelStore:bF,PivotMeasureDisplayPanelStore:BO};const bL={DEFAULT_LOCALE:yi,HIGHLIGHT_COLOR:a,PIVOT_TABLE_CONFIG:ke,ChartTerms:mE},SL={...ER,...Bx};e.AbstractCellClipboardHandler=ga,e.AbstractChart=uh,e.AbstractFigureClipboardHandler=hc,e.CellErrorType=Ri,e.CorePlugin=ZM,e.CoreViewPlugin=tP,e.DispatchResult=fi,e.EvaluationError=Ai,e.Model=class extends fc{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 la,n=!1){const r=performance.now();console.debug("##### Model creation #####"),super(),Do===Ao&&Oo===_o&&(Oo=()=>!0),s=iE(e,s);const a=sE(e,n);this.state=new ck,this.uuidGenerator=i,this.config=this.setupConfig(o),this.session=this.setupSession(a.revisionId),this.coreGetters={},this.range=new QM(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.coreGetters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.coreGetters.getRangeDataFromXc=this.range.getRangeDataFromXc.bind(this.range),this.coreGetters.getRangeDataFromZone=this.range.getRangeDataFromZone.bind(this.range),this.coreGetters.getRangeFromRangeData=this.range.getRangeFromRangeData.bind(this.range),this.coreGetters.getRangeFromZone=this.range.getRangeFromZone.bind(this.range),this.coreGetters.recomputeRanges=this.range.recomputeRanges.bind(this.range),this.coreGetters.isRangeValid=this.range.isRangeValid.bind(this.range),this.coreGetters.extendRange=this.range.extendRange.bind(this.range),this.coreGetters.getRangesUnion=this.range.getRangesUnion.bind(this.range),this.coreGetters.removeRangesSheetPrefix=this.range.removeRangesSheetPrefix.bind(this.range),this.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 ak(this.getters),this.coreHandlers.push(this.range),this.handlers.push(this.range),this.corePluginConfig=this.setupCorePluginConfig(),this.coreViewPluginConfig=this.setupCoreViewPluginConfig(),this.uiPluginConfig=this.setupUiPluginConfig();for(let e of SN.getAll())this.setupCorePlugin(e,a);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(s);for(let e of wN.getAll()){const t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(let e of CN.getAll()){const t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(let e of yN.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(let 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(let 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(let 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(let t of e){const e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new sN(ik({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:Mo("Anonymous").toString()},o=e.transportService||new XN;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(Si));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=mi(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return t.some((e=>"Success"!==e))?new fi(t.flat()):fi.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(cL(e,t));dispatch=(e,t)=>{const o=cL(e,t);let s=this.status;if(this.getters.isReadonly()&&(i=o,!gi.has(i.type)))return new fi("Readonly");var i;if(!this.session.canApplyOptimisticUpdate())return new fi("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();mi(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(mi(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(mi(o))throw new Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,o)}return fi.Success};dispatchFromCorePlugin=(e,t)=>{const o=cL(e,t),s=this.status;this.status=2;const i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,o),this.status=s,fi.Success};dispatchToHandlers(e,t){const o=mi(t);for(const s of e)!o&&s instanceof ZM||s.beforeHandle(t);for(const s of e)!o&&s instanceof ZM||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=aE();for(let t of this.handlers)t instanceof ZM&&t.export(e);return e.revisionId=this.session.getRevisionId()||Se,e=Be(e),e}updateMode(e){this.config.mode=e,this.trigger("update")}exportXLSX(){this.dispatch("EVALUATE_CELLS");let e={...aE(),sheets:[lE(oE,"Sheet1")]};for(let t of this.handlers)t instanceof qM&&t.exportForExcel(e);return e=Be(e),rL(e)}garbageCollectExternalResources(){for(const e of this.corePlugins)e.garbageCollectExternalResources()}},e.PivotRuntimeDefinition=tF,e.Registry=n,e.Revision=tN,e.SPREADSHEET_DIMENSIONS=dL,e.Spreadsheet=YN,e.SpreadsheetPivotTable=iF,e.UIPlugin=$P,e.__info__=hL,e.addFunction=function e(t,o){return Gb.add(t,o),{addFunction:(t,o)=>e(t,o)}},e.addRenderingLayer=function(e,t){if(xi[e])throw new Error(`Layer ${e} already exists`);xi[e]=t},e.astToFormula=Nf,e.chartHelpers=SL,e.compile=uS,e.compileTokens=gS,e.components=mL,e.constants=bL,e.convertAstNodes=Of,e.coreTypes=pi,e.findCellInNewZone=fs,e.functionCache=dS,e.helpers=gL,e.hooks=fL,e.invalidateCFEvaluationCommands=di,e.invalidateDependenciesCommands=hi,e.invalidateEvaluationCommands=li,e.iterateAstNodes=Ff,e.links=pL,e.load=sE,e.parse=_f,e.parseTokens=Df,e.readonlyAllowedCommands=gi,e.registries=uL,e.setDefaultSheetViewSize=function(e){Fe=e},e.setTranslationMethod=function(e,t=(()=>!0)){Do=e,Oo=t},e.stores=vL,e.tokenColors=oS,e.tokenize=va,hL.version="18.3.0-alpha.2",hL.date="2025-02-27T06:31:04.174Z",hL.hash="17e5bfa"}(this.o_spreadsheet=this.o_spreadsheet||{},owl);
|