@odoo/o-spreadsheet 19.3.12 → 19.3.13

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.
@@ -81,12 +81,12 @@ stores.inject(MyMetaStore, storeInstance);
81
81
  `+t.slice(i),{start:r+1,end:r+1}),this.processContent()}processEscapeKey(e){this.props.composerStore.cancelEdition(),e.stopPropagation(),e.preventDefault()}processF4Key(e){e.stopPropagation(),this.props.composerStore.cycleReferences(),this.processContent()}toggleEditionMode(e){e.stopPropagation(),this.props.composerStore.toggleEditionMode(),this.processContent()}processNumpadDecimal(e){e.stopPropagation(),e.preventDefault();let t=this.env.model.getters.getLocale(),n=this.contentHelper.getCurrentSelection(),r=this.props.composerStore.currentContent,i=r.slice(0,n.start)+t.decimalSeparator+r.slice(n.end);this.props.composerStore.setCurrentContent(i,{start:n.start+1,end:n.start+1}),this.processContent()}onCompositionStart(){this.compositionActive=!0}onCompositionEnd(){this.compositionActive=!1}onKeydown(e){if(this.props.composerStore.editionMode===`inactive`)return;if(e.key.startsWith(`Arrow`)){this.processArrowKeys(e);return}let t=this.keyMapping[Cm(e)]||this.keyCodeMapping[Cm(e,`code`)];t?t.call(this,e):e.stopPropagation()}onPaste(e){this.props.composerStore.editionMode===`inactive`?e.preventDefault():e.stopPropagation()}onInput(e){if(!this.shouldProcessInputEvents)return;e.stopPropagation();let t;if(t=this.props.composerStore.editionMode===`inactive`?e.data||``:this.contentHelper.getText(),this.props.focus===`inactive`)return this.props.onComposerCellFocused?.(t);let n=this.contentHelper.getCurrentSelection();this.props.composerStore.stopComposerRangeSelection(),this.props.composerStore.setCurrentContent(t,n),this.processTokenAtCursor()}onKeyup(e){if(this.contentHelper.el===document.activeElement){if(this.props.composerStore.isAutoCompleteDisplayed&&[`ArrowUp`,`ArrowDown`].includes(e.key)||this.props.composerStore.isSelectingRange&&e.key?.startsWith(`Arrow`))return;let{start:t,end:n}=this.props.composerStore.composerSelection,{start:r,end:i}=this.contentHelper.getCurrentSelection();(r!==t||i!==n)&&this.props.composerStore.changeComposerCursorSelection(r,i),this.processTokenAtCursor()}}onBlur(e){if(this.props.composerStore.editionMode===`inactive`)return;let t=e.relatedTarget;if(!t||!(t instanceof HTMLElement)){this.props.composerStore.stopEdition();return}if(!this.containerRef.el?.contains(e.relatedTarget)){if(t.attributes.getNamedItem(`composerFocusableElement`)){this.contentHelper.el.focus();return}t.classList.contains(`o-composer`)||this.props.composerStore.stopEdition()}}onMousedown(e){e.button>0||this.env.isMobile()&&!jm()||(this.debouncedHover.stopDebounce(),this.contentHelper.removeSelection())}onMouseup(){if(this.env.model.getters.isReadonly())return;let e=this.contentHelper.getCurrentSelection();e.start!==e.end&&this.props.composerStore.hoverToken(void 0)}onClick(){if(this.env.model.getters.isReadonly())return;let e=this.contentHelper.getCurrentSelection(),t=this.props.composerStore.editionMode===`inactive`;this.props.onComposerContentFocused(e),t||this.props.composerStore.changeComposerCursorSelection(e.start,e.end),this.processTokenAtCursor()}onDblClick(){if(this.env.model.getters.isReadonly())return;let e=this.props.composerStore.currentContent;if(qt(e)){let t=this.props.composerStore.currentTokens,n=this.contentHelper.getCurrentSelection();if(n.start===n.end)return;let r=e.substring(n.start,n.end),i=t.filter(e=>e.value.includes(r)&&e.start<=n.start&&e.end>=n.end)[0];if(!i)return;i.type===`REFERENCE`&&this.props.composerStore.changeComposerCursorSelection(i.start,i.end)}}onContextMenu(e){this.props.composerStore.editionMode===`inactive`&&this.props.onInputContextMenu?.(e)}closeAssistant(){this.props.composerStore.canBeToggled&&(this.assistant.forcedClosed=!0)}openAssistant(){this.props.composerStore.canBeToggled&&(this.assistant.forcedClosed=!1)}onWheel(e){this.composerRef.el&&this.composerRef.el.scrollHeight>this.composerRef.el.clientHeight&&e.stopPropagation()}processContent(){if(this.compositionActive)return;this.shouldProcessInputEvents=!1,this.props.focus!==`inactive`&&document.activeElement!==this.contentHelper.el&&this.contentHelper.el.focus();let e=this.getContentLines();if(this.contentHelper.setText(e),e.length!==0&&e.length[0]!==0&&this.props.focus!==`inactive`){let{start:e,end:t}=this.props.composerStore.composerSelection;this.contentHelper.selectRange(e,t)}this.shouldProcessInputEvents=!0}getContentLines(){let e=this.props.composerStore.currentContent,t=qt(e);return e===``?[]:t&&this.props.focus!==`inactive`?this.splitHtmlContentIntoLines(this.getHtmlContentFromTokens()):this.splitHtmlContentIntoLines([{value:e,classes:[]}])}getHtmlContentFromTokens(){let e=this.props.composerStore.currentTokens,t=[],{end:n,start:r}=this.props.composerStore.composerSelection;for(let i=0;i<e.length;i++){let a=e[i],o=a.color||`light-dark(#000000, #ffffff)`;a.isBlurred&&(o=Yr(o,.5));let s=[];a.type===`REFERENCE`&&this.props.composerStore.tokenAtCursor===a&&this.props.composerStore.editionMode===`selecting`&&s.push(`text-decoration-underline`),n===r&&a.isParenthesisLinkedToCursor&&s.push(`highlight-parenthesis-flag`),a.isInHoverContext&&s.push(`highlight-flag`),this.props.composerStore.showSelectionIndicator&&n===r&&n===a.end&&s.push(`selector-flag`),t.push({value:a.value,color:o,classes:s,onHover:e=>this.onTokenHover(i,e),onStopHover:()=>this.onTokenHover(void 0)})}return t}onTokenHover(e,t){this.lastHoveredTokenIndex!==e&&(this.lastHoveredTokenIndex=e,this.debouncedHover(e,t))}splitHtmlContentIntoLines(e){let t=[],n=[];for(let r of e)if(r.value.includes(`
82
82
  `)){let e=r.value.split(`
83
83
  `),i=e.pop();for(let i of e)n.push({color:r.color,value:i}),t.push(n),n=[];n.push({...r,value:i})}else n.push(r);n.length&&t.push(n);let r=[];for(let e of t)e.every(this.isContentEmpty)?r.push([e[0]]):r.push(e.filter(e=>!this.isContentEmpty(e)));return r}isContentEmpty(e){return!(e.value||e.classes?.length)}processTokenAtCursor(){let e=this.props.composerStore;this.functionDescriptionState.showDescription=!1;let t=this.props.composerStore.tokenAtCursor;if(qt(e.currentContent)&&t&&t.type!==`SYMBOL`){let e=t.functionContext,n=e?.parent.toUpperCase();if(e&&n&&n in qw&&t.type!==`UNKNOWN`){let r=qw[n],i=e.argPosition,a=e.args.length;this.functionDescriptionState.functionDescription=r;let o=this.props.composerStore.currentTokens.some(e=>e.type===`RIGHT_PAREN`&&e.parenthesesCode===t.parenthesesCode);this.functionDescriptionState.argsToFocus=this.getArgsToFocus(o,r,a,i),this.functionDescriptionState.showDescription=!0,this.functionDescriptionState.repeatingArgGroupIndex=this.getRepeatingArgGroupIndex(r,a,i)}}}getRepeatingArgGroupIndex(e,t,n){let{minArgRequired:r,maxArgPossible:i,nbrArgRepeating:a}=e;if(!a)return;let o=(a?Math.ceil((t-r)/a):0)*a+r;return Ci(e,Math.max(Math.min(i,o),r))[n].repeatingGroupIndex??0}getArgsToFocus(e,t,n,r){let{nbrArgRepeating:i,minArgRequired:a,nbrOptionalNonRepeatingArgs:o,maxArgPossible:s}=t;if(e){let e=Ci(t,Math.max(Math.min(s,n),a))[r]?.index;return e===void 0?[]:[e]}let c=Math.max(n,a),l=i?a+Math.ceil((c-a)/i)*i+o:s,u=[];for(let e=c;e<=l;e++){let n=Ci(t,e)[r]?.index;n!==void 0&&u.push(n)}return[...new Set(u)]}autoComplete(e){!e?.text||this.assistant.forcedClosed&&this.props.composerStore.canBeToggled||(this.props.composerStore.insertAutoCompleteValue(e),this.processTokenAtCursor())}get displaySpeechBubble(){return!!(this.props.focus!==`inactive`&&this.composerState.hoveredRect&&this.props.composerStore.hoveredContentEvaluation)}};function Yw(e){let t=0;return e.map(e=>{let n=e.value.toString().length,r=Object.assign({},e,{start:t,end:t+n,length:n});return t=r.end,r})}function Xw(e){let t=[],n=0;return e.map((r,i)=>{if(r.type===`LEFT_PAREN`){t.push(n+1),n=0;for(let n=i-1;n>=0;n--){if(e[n].type===`SPACE`){e[n].parenthesesCode=t.join(`:`);continue}e[n].type===`SYMBOL`&&(e[n].parenthesesCode=t.join(`:`));break}}return r.parenthesesCode=t.join(`:`),r.type===`RIGHT_PAREN`&&t.length&&(n=t.pop()),r})}function Zw(e){let t=[],n=``,r=0;function i(e){if(t.length===0)return;let n=t.at(-1);if(n&&n.argsTokens){let{argsTokens:t,argPosition:r}=n;t[r]||(t[r]=[]),t[r].push({value:e.value,type:e.type})}}return e.map(e=>{switch([`SPACE`,`LEFT_PAREN`].includes(e.type)||(n=``),e.type){case`SYMBOL`:i(e),n=e.value;break;case`LEFT_PAREN`:t.push({parent:n,argPosition:0,argsTokens:[],args:[]}),i(e),n=``;break;case`RIGHT_PAREN`:t.pop()?.argsTokens?.flat().forEach(i),i(e);break;case`LEFT_BRACE`:r++,i(e);break;case`RIGHT_BRACE`:r--,i(e);break;case`ARG_SEPARATOR`:t.length&&r===0&&t[t.length-1].argPosition++,i(e);break;default:i(e);break}if(t.length){let n=t[t.length-1];n.parent&&(e.functionContext=Object.assign({},n))}return e})}function Qw(e){for(let t of e)if(t.functionContext){let{argsTokens:e,args:n}=t.functionContext;if(delete t.functionContext.argsTokens,n.length||!e)continue;e[0]?.[0]?.type===`LEFT_PAREN`&&(e[0]=e[0].slice(1));for(let t of e){let e=t;e.at(0)?.type===`ARG_SEPARATOR`&&(e=e.slice(1));try{n.push(Us(e))}catch{n.push(void 0)}}}return e}function $w(e,t){return Qw(Zw(Xw(Yw(eT(As(e,t))))))}function eT(e){let t=[];for(;e.length;)t.push(tT(e)||e.shift());return t}function tT(e){if(e.length<2)return null;let t=e[0],n=e[1];return t.type===`REFERENCE`&&n.type===`OPERATOR`&&n.value===`#`&&!t.value.includes(`:`)?(e.splice(0,2),{type:t.type,value:t.value+`#`}):null}var nT=class{lastId=0;add(e){this.lastId++;let t=this.lastId;return new Promise((n,r)=>{e.then(e=>{this.lastId===t&&n(e)}).catch(e=>{this.lastId===t&&r(e)})})}};function rT(e,t,n){if(Je(e)){let r=n.decimalSeparator===`,`?`/`:`,`;return`{${uo(e).map(e=>e.map(e=>iT(e,t,n)).join(r)).join(`;`)}}`}return iT(e,t,n)}function iT(e,t,n){let r=e.value;switch(typeof r){case`number`:return H(r,{locale:n,format:e.format});case`string`:return F(r)?r:`"${r}"`;case`boolean`:return r?`TRUE`:`FALSE`}return t}function aT(e,t,n){let r=(t.startsWith(`=`)?$w(t,n):[]).filter(t=>t.start<=e.start&&t.end>=e.start||t.start>=e.start&&t.start<e.end),i=r.filter(e=>e.type===`REFERENCE`);if(i.length===0)return;let a=r.map(Zo).map(e=>e.value).join(``),o=r[0].start,s=r[r.length-1].end,c=t.slice(0,o)+a+t.slice(s),l=c.length-t.length,u={start:i[0].start,end:i[i.length-1].end+l};return i.length===1&&e.start===e.end&&(u.start=u.end),{content:c,selection:u}}let oT=new A;function sT(e,t,n){let{x:r,y:i,width:a,height:o}=n;if(a<0||o<0)return;let s=t.color||`#017E84`,{ctx:c}=e;c.save(),t.noBorder||(t.dashed&&c.setLineDash([5,3]),c.strokeStyle=s,t.thinLine?(c.lineWidth=1,c.strokeRect(r,i,a,o)):(c.lineWidth=2,c.strokeRect(r+.5,i+.5,a,o))),t.noFill||(c.fillStyle=Yr(Nr(s),t.fillAlpha??.12),c.fillRect(r,i,a,o)),c.restore()}var cT=class extends wr{mutators=[`register`,`unRegister`];providers=[];constructor(e){super(e),this.onDispose(()=>{this.providers=[]})}get renderingLayers(){return[`Highlights`]}get highlights(){let e=this.getters.getActiveSheetId();return this.providers.flatMap(e=>e.highlights).filter(t=>t.range.sheetId===e).map(e=>{let{numberOfRows:t,numberOfCols:n}=Ln(e.range.zone),r=t*n===1?this.getters.expandZone(e.range.sheetId,e.range.zone):e.range.unboundedZone;return{...e,range:this.model.getters.getRangeFromZone(e.range.sheetId,r)}})}register(e){this.providers.push(e)}unRegister(e){this.providers=this.providers.filter(t=>t!==e)}drawLayer(e,t){if(t===`Highlights`)for(let t of this.highlights)sT(e,t,e.viewports.getVisibleRect(e.sheetId,t.range.zone))}},lT=class{mutators=[`notifyUser`,`raiseError`,`askConfirmation`,`updateNotificationCallbacks`];notifyUser=e=>window.alert(e.text);askConfirmation=(e,t,n)=>{window.confirm(e)?t():n?.()};raiseError=(e,t)=>{window.alert(e),t?.()};updateNotificationCallbacks(e){this.notifyUser=e.notifyUser||this.notifyUser,this.raiseError=e.raiseError||this.raiseError,this.askConfirmation=e.askConfirmation||this.askConfirmation}},uT=class extends wr{mutators=[`useProvider`,`moveSelection`,`hide`,`selectIndex`];selectedIndex=void 0;provider;get selectedProposal(){if(!(this.selectedIndex===void 0||this.provider===void 0))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){if(this.provider){if(this.selectedIndex===void 0){this.selectedIndex=0;return}e===`previous`?(this.selectedIndex--,this.selectedIndex<0&&(this.selectedIndex=this.provider.proposals.length-1)):this.selectedIndex=(this.selectedIndex+1)%this.provider.proposals.length}}},dT=class extends wr{mutators=[`startEdition`,`setCurrentContent`,`stopEdition`,`stopComposerRangeSelection`,`cancelEdition`,`cycleReferences`,`hideHelp`,`autoCompleteOrStop`,`insertAutoCompleteValue`,`moveAutoCompleteSelection`,`selectAutoCompleteIndex`,`toggleEditionMode`,`changeComposerCursorSelection`,`replaceComposerCursorSelection`,`hoverToken`];col=0;row=0;editionMode=`inactive`;sheetId=``;_currentContent=``;currentTokens=[];selectionStart=0;selectionEnd=0;initialContent=``;colorIndexByRange={};autoComplete=new uT(this.get);hasSelectedAProposal=!1;hoveredTokens=[];hoveredContentEvaluation=``;autoCompleteKeepLast=new nT;notificationStore=this.get(lT);highlightStore=this.get(cT);constructor(e){super(e),this.highlightStore.register(this),this.onDispose(()=>{this.highlightStore.unRegister(this),this._cancelEdition()})}handleEvent(e){let t=this.getters.getActiveSheetId(),n;switch(n=e.options.unbounded?this.getters.getUnboundedZone(t,e.anchor.zone):e.anchor.zone,e.mode){case`newAnchor`:this.editionMode===`selecting`&&this.insertSelectedRange(n);break;default:this.editionMode===`selecting`?this.replaceSelectedRange(n):this.updateComposerRange(e.previousAnchor.zone,n);break}}changeComposerCursorSelection(e,t){this.isSelectionValid(this._currentContent.length,e,t)&&(this.selectionStart=e,this.selectionEnd=t,this.stopComposerRangeSelection(),this.computeFormulaCursorContext(),this.computeParenthesisRelatedToCursor(),this.updateAutoCompleteProvider())}stopComposerRangeSelection(){this.isSelectingRange&&(this.editionMode=`editing`)}startEdition(e,t){let{col:n,row:r}=this.getters.getActivePosition();this.model.dispatch(`SELECT_FIGURE`,{figureId:null}),this.model.dispatch(`SCROLL_TO_CELL`,{col:n,row:r}),this.editionMode!==`inactive`&&e?this.setContent(e,t):this._startEdition(e,t),this.updateTokenColor(),this.computeFormulaCursorContext(),this.computeParenthesisRelatedToCursor(),this.updateAutoCompleteProvider()}cancelEdition(){this.resetContent(),this.cancelEditionAndActivateSheet()}setCurrentContent(e,t){t&&!this.isSelectionValid(e.length,t.start,t.end)||(this.setContent(e,t,!0),this.updateTokenColor(),this.computeFormulaCursorContext(),this.computeParenthesisRelatedToCursor())}replaceComposerCursorSelection(e){this.replaceSelection(e)}handle(e){switch(e.type){case`SELECT_FIGURE`:e.figureId&&(this.resetContent(),this.cancelEditionAndActivateSheet());break;case`START_CHANGE_HIGHLIGHT`:let{left:t,top:n}=e.zone;this.isSelectingRange&&(this.editionMode=`editing`),this.model.selection.resetAnchor(this,{cell:{col:t,row:n},zone:e.zone});break}}get currentContent(){return this.editionMode===`inactive`?this.getComposerContent(this.getters.getActivePosition()).text:this._currentContent}get composerSelection(){return{start:this.selectionStart,end:this.selectionEnd}}get isSelectingRange(){return this.editionMode===`selecting`}get showSelectionIndicator(){return this.isSelectingRange&&this.canStartComposerRangeSelection()}get tokenAtCursor(){let e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);if(!(e===t&&t===0))return this.currentTokens.find(n=>n.start<=e&&n.end>=t)}get autoCompleteProposals(){return this.autoComplete.provider?.proposals||[]}get autoCompleteSelectedIndex(){return this.autoComplete.selectedIndex}get isAutoCompleteDisplayed(){return!!this.autoComplete.provider}get canBeToggled(){return this.autoComplete.provider?.canBeToggled??!0}cycleReferences(){let e=this.getters.getLocale(),t=aT(this.composerSelection,this._currentContent,e);t!==void 0&&this.setCurrentContent(t.content,t.selection)}toggleEditionMode(){if(this.editionMode===`inactive`)return;let e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd),n=[...this.currentTokens].reverse().find(n=>n.end>=e&&t>=n.start&&n.type===`REFERENCE`);if(this.editionMode===`editing`&&n){let e=this.getters.getActiveSheetId(),{sheetName:t,xc:r}=Yo(n.value),i=this.getters.getSheetIdByName(t);i&&i!==e&&this.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:e,sheetIdTo:i}),this.selectionStart=this.selectionEnd=n.end;let a=this.getFullySpreadRange(this.sheetId,r).zone;this.captureSelection(a),this.editionMode=`selecting`}else this.editionMode=`editing`}hoverToken(e){this.currentTokens.forEach(e=>e.isInHoverContext=void 0);let t=[...this.currentTokens];if(e===void 0||[`ARG_SEPARATOR`,`SPACE`].includes(t[e].type)){this.hoveredContentEvaluation=``,this.hoveredTokens=[];return}let n=this.getMissingSymbols(this.currentTokens);for(let e of n){let n=e===`)`?`RIGHT_PAREN`:`RIGHT_BRACE`,r=t[t.length-1].start+1;t.push({value:e,type:n,start:r,end:r+e.length,length:1})}let r=t;if(e!==0){let n=this.getRelatedTokens(t,e),i=t.filter(e=>!n.includes(e)&&e.type!==`SPACE`);r=i.length===1&&i[0]===t[0]?t:n}r.forEach(e=>e.isInHoverContext=!0);let i=r.map(e=>e.value).join(``);qt(i)||(i=`=${i}`);let a=Gy(i,this.getters.getLocale()),o=this.evaluateCanonicalFormula(a);this.hoveredTokens=r,this.hoveredContentEvaluation=rT(o,`0`,this.getters.getLocale())}evaluateCanonicalFormula(e){return this.getters.evaluateFormulaResult(this.sheetId,e)}getRelatedTokens(e,t){try{let n=Us(e),r;for(let e of Gs(n))if(t>=e.tokenStartIndex&&t<=e.tokenEndIndex)r=e;else if(t<e.tokenStartIndex)break;return r?e.slice(r.tokenStartIndex,r.tokenEndIndex+1):e}catch(t){if(t instanceof N)return e;throw t}}captureSelection(e,t,n){this.model.selection.capture(this,{cell:{col:t??e.left,row:n??e.top},zone:e},{handleEvent:this.handleEvent.bind(this),release:()=>{this._stopEdition()}})}isSelectionValid(e,t,n){return t>=0&&t<=e&&n>=0&&n<=e}startComposerRangeSelection(){if(this.sheetId===this.getters.getActiveSheetId()){let e=D({col:this.col,row:this.row});this.model.selection.resetAnchor(this,{cell:{col:this.col,row:this.row},zone:e})}this.editionMode=`selecting`}_startEdition(e,t){let n=this.getters.getActiveCell(),r=this.getters.getLocale();e&&n.format?.includes(`%`)&&Pa(e,r)&&(t||={start:e.length,end:e.length},e=`${e}%`);let{col:i,row:a,sheetId:o}=this.getters.getActivePosition();this.col=i,this.sheetId=o,this.row=a,this.editionMode=`editing`;let{text:s,adjustedSelection:c}=this.getComposerContent({sheetId:o,col:i,row:a},t);this.initialContent=s,this.hasSelectedAProposal=!1,this.setContent(e||this.initialContent,c??t),this.colorIndexByRange={};let l=D({col:this.col,row:this.row});this.captureSelection(l,i,a)}_stopEdition(){if(this.editionMode!==`inactive`){this.cancelEditionAndActivateSheet();let e=this.getCurrentCanonicalContent();if(this.initialContent===e)return;if(e&&qt(e)){let t=this.getMissingSymbols(this.currentTokens);e+=bt(t)}this.confirmEdition(e)}}getCurrentCanonicalContent(){return Gy(this._currentContent,this.getters.getLocale())}cancelEditionAndActivateSheet(){this.editionMode!==`inactive`&&(this._cancelEdition(),this.getters.getActiveSheetId()!==this.sheetId&&this.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:this.sheetId}))}_cancelEdition(){this.editionMode!==`inactive`&&(this.editionMode=`inactive`,this.model.selection.release(this),this.colorIndexByRange={},this.hoveredTokens=[],this.hoveredContentEvaluation=``,this.hideHelp())}resetContent(){this.setContent(this.initialContent||``)}setContent(e,t,n){let r=this._currentContent!==e;if(this._currentContent=e,t?(this.selectionStart=t.start,this.selectionEnd=t.end):this.selectionStart=this.selectionEnd=e.length,r||this.editionMode!==`inactive`){let t=this.getters.getLocale();this.currentTokens=qt(e)?$w(e,t):[],this.currentTokens.filter(e=>e.type!==`SPACE`).length>1e3&&n&&this.notificationStore.raiseError(j(`This formula has over 1000 parts. It can't be processed properly, consider splitting it into multiple cells`))}this.canStartComposerRangeSelection()&&this.startComposerRangeSelection(),this.updateAutoCompleteProvider()}getAutoCompleteProviders(){return oT.getAll()}insertSelectedRange(e){let t=Math.min(this.selectionStart,this.selectionEnd),n=this.getZoneReference(e);this.canStartComposerRangeSelection()?this.insertText(n,t):this.insertText(`,`+n,t)}replaceSelectedRange(e){let t=this.getZoneReference(e),n=this.tokenAtCursor,r=n?.type===`REFERENCE`?n.start:this.selectionStart;this.replaceText(t,r,this.selectionEnd)}updateComposerRange(e,t){let n=this.getters.getActiveSheetId(),r=this.tokenAtCursor,i=(r?[r,...this.currentTokens]:this.currentTokens).filter(e=>e.type===`REFERENCE`).find(t=>{let{xc:r,sheetName:i}=Yo(t.value),a=i||this.getters.getSheetName(this.sheetId);if(!xc(this.getters.getSheetName(n),a))return!1;let o=this.getFullySpreadRange(n,r);return Mn(this.getters.expandZone(n,o.zone),e)});if(!i)return;let a=this.getFullySpreadRange(n,i.value);this.selectionStart=i.start,this.selectionEnd=this.selectionStart+i.value.length;let o=this.getters.getRangeFromZone(n,t),s=this.getRangeReference(o,a.parts);this.replaceSelection(s)}getZoneReference(e){let t=this.sheetId,n=this.getters.getActiveSheetId(),r=this.getters.getRangeFromZone(n,e);return this.getters.getSelectionRangeString(r,t,{allowSpilledReferences:!0})}getRangeReference(e,t){let n=[...t],r={...e,parts:n};return this.getters.getSelectionRangeString(r,this.sheetId,{allowSpilledReferences:!0})}replaceSelection(e){let t=Math.min(this.selectionStart,this.selectionEnd),n=Math.max(this.selectionStart,this.selectionEnd);this.replaceText(e,t,n)}replaceText(e,t,n){this._currentContent=this._currentContent.slice(0,t)+this._currentContent.slice(n,this._currentContent.length),this.insertText(e,t)}insertText(e,t){let n=this._currentContent.slice(0,t)+e+this._currentContent.slice(t),r=t+e.length;this.setCurrentContent(n,{start:r,end:r})}updateTokenColor(){this.updateRangeColor();for(let e=0;e<this.currentTokens.length;e++)this.currentTokens[e].color=this.getTokenColor(this.currentTokens[e])}getTokenColor(e){if(e.type===`REFERENCE`){let{xc:t,sheetName:n}=Yo(e.value);return this.rangeXCColor(t,n)||`light-dark(#000000, #ffffff)`}if(e.type===`SYMBOL`){let t=this.getters.getNamedRange(e.value);if(t)return this.rangeColor(t.range)||`light-dark(#000000, #ffffff)`;let n=e.value.toUpperCase();if(n===`TRUE`||n===`FALSE`)return Ke.NUMBER;if(n in Fo.content)return Ke.FUNCTION}return[`LEFT_PAREN`,`RIGHT_PAREN`].includes(e.type)&&e.parenthesesCode===``?Ke.ORPHAN_RIGHT_PAREN:Ke[e.type]||`light-dark(#000000, #ffffff)`}rangeXCColor(e,t){let n=t?this.model.getters.getSheetIdByName(t):this.sheetId;if(n)return this.rangeColor(this.getFullySpreadRange(n,e))}rangeColor(e){return this.highlights.find(t=>{if(t.range.sheetId!==e.sheetId)return!1;let n=e.zone;return n=Xn(n)===1?this.model.getters.expandZone(e.sheetId,n):n,Mn(n,t.range.zone)})?.color}computeFormulaCursorContext(){for(let e=0;e<this.currentTokens.length;e++)this.currentTokens[e].isBlurred=!1;if(this.selectionStart!==this.selectionEnd)return;let e=this.getParenthesesCodeAfterCursor(),t=[...this.currentTokens].reverse().find(t=>e.startsWith(t.parenthesesCode)&&t.type===`SYMBOL`);if(t)for(let e=0;e<this.currentTokens.length;e++)(this.currentTokens[e].parenthesesCode||``).startsWith(t.parenthesesCode||``)||(this.currentTokens[e].isBlurred=!0)}getParenthesesCodeAfterCursor(){let e=this.tokenAtCursor?.parenthesesCode||``;return this.tokenAtCursor?.type===`RIGHT_PAREN`?e.slice(0,-1)||``:e}computeParenthesisRelatedToCursor(){for(let e=0;e<this.currentTokens.length;e++)this.currentTokens[e].isParenthesisLinkedToCursor=!1;let e=this.tokenAtCursor;if(!(!e||e.parenthesesCode===``||![`LEFT_PAREN`,`RIGHT_PAREN`].includes(e.type)))for(let t=0;t<this.currentTokens.length;t++){let n=this.currentTokens[t];[`LEFT_PAREN`,`RIGHT_PAREN`].includes(n.type)&&n.parenthesesCode===e.parenthesesCode&&n!==e&&(this.currentTokens[t].isParenthesisLinkedToCursor=!0,this.tokenAtCursor.isParenthesisLinkedToCursor=!0)}}updateRangeColor(){if(!qt(this._currentContent)||this.editionMode===`inactive`)return;let e=this.sheetId,t=this.getReferencedRanges().map(({range:t})=>this.getters.getRangeString(t,e)),n={};for(let e of t)this.colorIndexByRange[e]!==void 0&&(n[e]=this.colorIndexByRange[e]);let r=new Set(Object.values(n)),i=0,a=()=>{for(;r.has(i);)i++;return r.add(i),i};for(let e of t)n[e]=e in n?n[e]:a();this.colorIndexByRange=n}get highlights(){if(!qt(this.currentContent)||this.editionMode===`inactive`)return[];let e=this.sheetId,t=e=>Ar[this.colorIndexByRange[e]%Ar.length];return this.getReferencedRanges().map(({type:n,range:r})=>{let i=this.getters.getRangeString(r,e),{numberOfRows:a,numberOfCols:o}=Ln(r.zone),s=a*o===1?this.getters.expandZone(r.sheetId,r.zone):r.unboundedZone;return{range:this.model.getters.getRangeFromZone(r.sheetId,s),color:t(i),interactive:n!==`named_range`}})}getReferencedRanges(){let e=this.sheetId;return this.currentTokens.map(t=>{if(t.type===`REFERENCE`)return{type:`reference`,range:this.getFullySpreadRange(e,t.value)};if(t.type===`SYMBOL`)return{type:`named_range`,range:this.getters.getNamedRange(t.value)?.range}}).filter(e=>e?.range&&!e.range.invalidSheetName&&!e.range.invalidXc)}getFullySpreadRange(e,t){if(!t.endsWith(`#`))return this.getters.getRangeFromSheetXC(e,t);let n=t.slice(0,-1),r=this.getters.getRangeFromSheetXC(e,n),i=this.getters.getSpreadZone({sheetId:r.sheetId,col:r.zone.left,row:r.zone.top});return i?this.getters.getRangeFromZone(e,i):r}updateAutoCompleteProvider(){this.autoComplete.hide(),this.autoCompleteKeepLast.add(this.findAutocompleteProvider()).then(e=>{e&&(this.autoComplete.useProvider(e),this.model.trigger(`update`))})}async findAutocompleteProvider(){let e=this.currentContent,t=qt(e)?this.tokenAtCursor:{type:`STRING`,value:e};if(this.editionMode===`inactive`||!t||[`TRUE`,`FALSE`].includes(t.value.toUpperCase())||!(this.canStartComposerRangeSelection()||[`SYMBOL`,`STRING`,`UNKNOWN`].includes(t.type)))return;let n={composer:this,getters:this.getters},r=this.getAutoCompleteProviders().sort((e,t)=>(e.sequence??1/0)-(t.sequence??1/0)).map(r=>({...r,getProposals:r.getProposals.bind(n,t,e),selectProposal:r.selectProposal.bind(n,t)}));for(let e of r){let n=await e.getProposals(),r=n?.find(e=>e.text===t.value),i=t.value.replace(/[ ,\(\)]/g,``);if(this._currentContent===this.initialContent&&e.displayAllOnInitialContent&&n?.length)return{proposals:n,selectProposal:e.selectProposal,autoSelectFirstProposal:e.autoSelectFirstProposal??!1,canBeToggled:e.canBeToggled};if(r&&(this._currentContent!==this.initialContent||this.hasSelectedAProposal))return;if(i&&n&&![`ARG_SEPARATOR`,`LEFT_PAREN`,`OPERATOR`].includes(t.type)){let e=fd(i,n,e=>e.fuzzySearchKey||e.text);(!r||e.length)&&(n=e)}if(e.maxDisplayedProposals&&(n=n?.slice(0,e.maxDisplayedProposals)),n?.length)return{proposals:n,selectProposal:e.selectProposal,autoSelectFirstProposal:e.autoSelectFirstProposal??!1,canBeToggled:e.canBeToggled}}}hideHelp(){this.autoComplete.hide()}autoCompleteOrStop(e,t=!1){if(this.editionMode!==`inactive`){let n=this.autoComplete;if(!(t&&this.canBeToggled)&&n.provider&&n.selectedIndex!==void 0){let e=n.provider.proposals[n.selectedIndex];if(e){this.insertAutoCompleteValue(e);return}}this.stopEdition(e)}}insertAutoCompleteValue(e){this.autoComplete.provider?.selectProposal(e),this.hasSelectedAProposal=!0}selectAutoCompleteIndex(e){this.autoComplete.selectIndex(S(0,e,10))}moveAutoCompleteSelection(e){this.autoComplete.moveSelection(e)}canStartComposerRangeSelection(){if(qt(this._currentContent)){let e=this.tokenAtCursor;if(!e)return!1;let t=this.currentTokens.map(e=>e.start).indexOf(e.start),n=t,r=e;for(;![`ARG_SEPARATOR`,`ARRAY_ROW_SEPARATOR`,`LEFT_PAREN`,`LEFT_BRACE`,`OPERATOR`].includes(r.type)||as.includes(r.value);){if(r.type!==`SPACE`||n<1)return!1;n--,r=this.currentTokens[n]}for(n=t+1,r=this.currentTokens[n];r&&![`ARG_SEPARATOR`,`ARRAY_ROW_SEPARATOR`,`RIGHT_PAREN`,`RIGHT_BRACE`,`OPERATOR`].includes(r.type);){if(r.type!==`SPACE`)return!1;n++,r=this.currentTokens[n]}return!0}return!1}getMissingSymbols(e){let t=[];for(let n of e)switch(n.type){case`LEFT_PAREN`:t.push(`)`);break;case`LEFT_BRACE`:t.push(`}`);break;case`RIGHT_PAREN`:case`RIGHT_BRACE`:t.length>0&&t.at(-1)===n.value&&t.pop();break}return t.reverse(),t}},fT=class extends dT{args;constructor(e,t){super(e),this.args=t,this._currentContent=this.getComposerContent().text}getAutoCompleteProviders(){let e=super.getAutoCompleteProviders(),t=this.args().contextualAutocomplete;return t&&e.push(t),e}getZoneReference(e){let t=super.getZoneReference(e);return this.args().defaultStatic?$o(t,`colrow`):t}getComposerContent(){let e=this.args().defaultRangeSheetId;return{text:qy(As(this.args().content).map(t=>{if(t.type===`REFERENCE`){let n=this.getters.getRangeFromSheetXC(e,t.value);return this.getters.getRangeString(n,this.getters.getActiveSheetId())}return t.value}).join(``),this.getters.getLocale())}}stopEdition(){this._stopEdition()}confirmEdition(e){this.args().onConfirm(e)}getTokenColor(e){if(e.type===`SYMBOL`){let t=this.args().getContextualColoredSymbolToken?.(e);if(t)return t}return super.getTokenColor(e)}hoverToken(){}},pT=class extends t.Component{static template=`o-spreadsheet-StandaloneComposer`;static props={composerContent:{type:String,optional:!0},defaultRangeSheetId:{type:String,optional:!0},defaultStatic:{type:Boolean,optional:!0},onConfirm:Function,contextualAutocomplete:{type:Object,optional:!0},placeholder:{type:String,optional:!0},title:{type:String,optional:!0},class:{type:String,optional:!0},invalid:{type:Boolean,optional:!0},autofocus:{type:Boolean,optional:!0},getContextualColoredSymbolToken:{type:Function,optional:!0}};static components={Composer:Jw};static defaultProps={composerContent:``,defaultStatic:!1};composerFocusStore;standaloneComposerStore;composerInterface;spreadsheetRect=vy();setup(){this.composerFocusStore=O(Er);let e=hr(fT,()=>({onConfirm:this.props.onConfirm,content:this.props.composerContent,defaultStatic:this.props.defaultStatic??!1,contextualAutocomplete:this.props.contextualAutocomplete,defaultRangeSheetId:this.props.defaultRangeSheetId,getContextualColoredSymbolToken:this.props.getContextualColoredSymbolToken}));this.standaloneComposerStore=e,this.composerInterface={id:`standaloneComposer`,get editionMode(){return e.editionMode},startEdition:this.standaloneComposerStore.startEdition,setCurrentContent:this.standaloneComposerStore.setCurrentContent,stopEdition:this.standaloneComposerStore.stopEdition},(0,t.onMounted)(()=>{this.props.autofocus&&this.focus===`inactive`&&(this.composerFocusStore.focusComposer(this.composerInterface,{}),this.composerFocusStore.activeComposer.editionMode)})}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:`inactive`}get composerStyle(){return this.props.invalid?W({padding:`1px 0px 0px 0px`}):W({padding:`1px 0px`})}get containerClass(){return[this.focus===`inactive`?``:`active`,this.props.invalid?`o-invalid`:``,this.props.class||``].join(` `)}onFocus(e){this.composerFocusStore.focusComposer(this.composerInterface,{selection:e})}},mT=class extends t.Component{static template=`o-spreadsheet-CriterionInput`;static props={value:{type:String,optional:!0},criterionType:String,onValueChanged:Function,onKeyDown:{type:Function,optional:!0},focused:{type:Boolean,optional:!0},onBlur:{type:Function,optional:!0},onFocus:{type:Function,optional:!0},disableFormulas:{type:Boolean,optional:!0}};static defaultProps={value:``,onKeyDown:()=>{},focused:!1,onBlur:()=>{}};static components={StandaloneComposer:pT};inputRef=(0,t.useRef)(`input`);setup(){(0,t.useEffect)(()=>{this.props.focused&&this.inputRef.el&&this.inputRef.el.focus()},()=>[this.props.focused,this.inputRef.el])}state=(0,t.useState)({shouldDisplayError:!!this.props.value});get placeholder(){return this.allowedValues===`onlyFormulas`?j(`Formula`):this.allowedValues===`onlyLiterals`?j(`Value`):j(`Value or formula`)}get allowedValues(){let e=X.get(this.props.criterionType);if(e.allowedValues===`onlyFormulas`&&this.props.disableFormulas)throw Error(`Cannot disable formulas for criterion type ${this.props.criterionType} that accept only formulas`);return(this.props.disableFormulas?`onlyLiterals`:e.allowedValues)??`any`}onInputValueChanged(e){this.state.shouldDisplayError=!0,this.props.onValueChanged(e.target.value)}onChangeComposerValue(e){this.state.shouldDisplayError=!0,this.props.onValueChanged(e)}getDataValidationRuleInputComposerProps(){return{onConfirm:e=>this.onChangeComposerValue(e),composerContent:this.props.value,placeholder:this.placeholder,class:`o-sidePanel-composer`,defaultRangeSheetId:this.env.model.getters.getActiveSheetId(),invalid:this.state.shouldDisplayError&&!!this.errorMessage,defaultStatic:!0,autofocus:this.props.focused}}get errorMessage(){if(this.state.shouldDisplayError)return this.env.model.getters.getDataValidationInvalidCriterionValueMessage(this.props.criterionType,Ky(this.props.value,this.env.model.getters.getLocale()))}};let hT={today:j(`today`),yesterday:j(`yesterday`),tomorrow:j(`tomorrow`),lastWeek:j(`in the past week`),lastMonth:j(`in the past month`),lastYear:j(`in the past year`),exactDate:j(`exact date`)};var gT=class extends Tw{static template=`o-spreadsheet-DataValidationDateCriterion`;static components={CriterionInput:mT,Select:Ty};get currentDateValue(){return this.props.criterion.dateValue||`exactDate`}onValueChanged(e){this.updateCriterion({values:[e],dateValue:this.currentDateValue})}onDateValueChanged(e){this.updateCriterion({dateValue:e})}get dateValues(){return Object.keys(hT).map(e=>({value:e,label:hT[e]}))}},_T=class extends Tw{static template=`o-spreadsheet-DoubleInputCriterionForm`;static components={CriterionInput:mT};onFirstValueChanged(e){let t=this.props.criterion.values;this.updateCriterion({values:[e,t[1]||``]})}onSecondValueChanged(e){let t=this.props.criterion.values;this.updateCriterion({values:[t[0]||``,e]})}},vT=class extends Tw{static template=`o-spreadsheet-SingleInputCriterionForm`;static components={CriterionInput:mT};onValueChanged(e){let t=x(this.props.criterion);t.values[0]=e,this.updateCriterion(t)}},yT=class extends Tw{static template=`o-spreadsheet-Top10CriterionForm`;static components={CriterionInput:mT,Select:Ty};onValueChanged(e){let t=x(this.props.criterion);t.values[0]=e,this.updateCriterion(t)}updateIsBottom(e){let t=x(this.props.criterion);t.isBottom=e===`bottom`,this.updateCriterion(t)}updateIsPercent(e){let t=x(this.props.criterion);t.isPercent=e===`percent`,this.updateCriterion(t)}get isBottomSelectOptions(){return[{value:`top`,label:j(`Top`)},{value:`bottom`,label:j(`Bottom`)}]}get isPercentSelectOptions(){return[{value:`values`,label:j(`Values`)},{value:`percent`,label:j(`Percent`)}]}};function bT(e,t){let n=()=>{window.removeEventListener(`pointerup`,r,{capture:!0}),window.removeEventListener(`dragstart`,i),window.removeEventListener(`pointermove`,e),window.removeEventListener(`wheel`,e)},r=e=>{t(e),n()};function i(e){e.preventDefault()}return window.addEventListener(`pointerup`,r,{capture:!0}),window.addEventListener(`dragstart`,i),window.addEventListener(`pointermove`,e),window.addEventListener(`wheel`,e,{passive:!1}),n}var xT=class extends t.Component{static template=`o-spreadsheet-ColorPicker`;static props={onColorPicked:Function,currentColor:{type:String,optional:!0},maxHeight:{type:Number,optional:!0},anchorRect:Object,disableNoColor:{type:Boolean,optional:!0}};static defaultProps={currentColor:``};static components={Popover:by};COLORS=ye;state=(0,t.useState)({showGradient:!1,currentHslaColor:Pr(this.props.currentColor)?{...Gr(this.props.currentColor),a:1}:{h:0,s:100,l:100,a:1},customHexColor:Pr(this.props.currentColor)?Nr(this.props.currentColor):``});get colorPickerStyle(){return this.props.maxHeight!==void 0&&this.props.maxHeight<=0?W({display:`none`}):``}get popoverProps(){return{anchorRect:this.props.anchorRect,maxHeight:this.props.maxHeight,positioning:`bottom-left`,verticalOffset:0}}get gradientHueStyle(){return W({background:`hsl(${this.state.currentHslaColor?.h||0} 100% 50%)`})}get sliderStyle(){let e=this.state.currentHslaColor?.h||0;return W({"margin-left":`${S(Math.round(e/360*216),1,216)-18/2}px`})}get pointerStyle(){let{s:e,l:t}=this.state.currentHslaColor||{s:0,l:0},n=Math.round(216*S(e/100,0,1)),r=Math.round(186*S(1-2*t/(200-e),0,1));return W({left:`${-16/2+n}px`,top:`${-16/2+r}px`,background:Wr(this.state.currentHslaColor)})}get colorPreviewStyle(){return W({"background-color":Wr(this.state.currentHslaColor)})}get checkmarkColor(){return xf(this.props.currentColor)}get isHexColorInputValid(){return!this.state.customHexColor||Pr(this.state.customHexColor)}setCustomGradient({x:e,y:t}){let n=S(e,0,216),r=S(t,0,186),i=n/216,a=r/186,o=100*i,s=100*(1-a)*(1-.5*i);this.updateColor({s:o,l:s})}setCustomHue(e){let t=Math.round(S(360*e/216,0,359));this.updateColor({h:t})}updateColor(e){this.state.currentHslaColor={...this.state.currentHslaColor,...e},this.state.customHexColor=Wr(this.state.currentHslaColor)}onColorClick(e){e&&this.props.onColorPicked(Nr(e))}resetColor(){this.props.onColorPicked(``)}toggleColorPicker(){this.state.showGradient=!this.state.showGradient}dragGradientPointer(e){let t={x:e.offsetX,y:e.offsetY};this.setCustomGradient(t);let n={x:e.clientX,y:e.clientY};bT(e=>{let r={x:e.clientX,y:e.clientY},i=r.x-n.x,a=r.y-n.y,o={x:t.x+i,y:t.y+a};this.setCustomGradient(o)},()=>{})}dragHuePointer(e){let t=e.offsetX,n=e.clientX;this.setCustomHue(t),bT(e=>{let r=t+(e.clientX-n);this.setCustomHue(r)},()=>{})}setHexColor(e){let t=e.target.value.replace(`##`,`#`).slice(0,7);this.state.customHexColor=t,Pr(t)&&(this.state.currentHslaColor={...Gr(t),a:1})}addCustomColor(e){!Fr(this.state.currentHslaColor)||!Pr(this.state.customHexColor)||this.props.onColorPicked(Nr(this.state.customHexColor))}isSameColor(e,t){return Jr(e,t)}},Z=class extends t.Component{static template=`o_spreadsheet.Section`;static props={class:{type:String,optional:!0},title:{type:String,optional:!0},slots:Object}},ST=class extends t.Component{static template=`o-spreadsheet.RoundColorPicker`;static components={Section:Z,ColorPicker:xT};static props={currentColor:{type:String,optional:!0},title:{type:String,optional:!0},onColorPicked:Function,disableNoColor:{type:Boolean,optional:!0}};colorPickerButtonRef=(0,t.useRef)(`colorPickerButton`);state;setup(){this.state=(0,t.useState)({pickerOpened:!1}),(0,t.useExternalListener)(window,`click`,this.closePicker)}closePicker(){this.state.pickerOpened=!1}togglePicker(){this.state.pickerOpened=!this.state.pickerOpened}onColorPicked(e){this.props.onColorPicked(e),this.state.pickerOpened=!1}get colorPickerAnchorRect(){let e=this.colorPickerButtonRef.el;return gm(e)}get buttonStyle(){return W({background:this.props.currentColor})}},CT=class extends Tw{static template=`o-spreadsheet-ListCriterionForm`;static components={CriterionInput:mT,RoundColorPicker:ST,Select:Ty};state=(0,t.useState)({items:[],focusedValueIndex:this.props.autofocus?0:void 0});setup(){super.setup();let e=this.props.criterion.values||[],n=this.props.criterion.colors||{};this.state.items=Array.from({length:Math.max(e.length,2)},(t,r)=>{let i=e[r]??``;return{value:i,color:i?n[i]:void 0}});let r=e=>{e.criterion.displayStyle===void 0&&this.updateCriterion({displayStyle:`chip`})};(0,t.onWillUpdateProps)(r),(0,t.onWillStart)(()=>r(this.props))}syncCriterion(){let e=this.state.items.map(e=>e.value),t={};for(let{value:e,color:n}of this.state.items)e?.trim()!==``&&n&&(t[e]=n);this.updateCriterion({values:e,colors:t})}onValueChanged(e,t){this.state.items[e].value=t,this.syncCriterion()}onColorChanged(e,t){this.state.items[e].color=t,this.syncCriterion()}onAddAnotherValue(){this.state.items.push({value:``})}removeItem(e){this.state.items.splice(e,1),this.syncCriterion()}onChangedDisplayStyle(e){this.updateCriterion({displayStyle:e})}onKeyDown(e,t){(e.key===`Enter`||e.key===`Tab`)&&t===this.state.items.length-1?(this.onAddAnotherValue(),this.state.focusedValueIndex=t+1,e.preventDefault()):e.key===`Enter`&&(this.state.focusedValueIndex=t+1)}onBlurInput(){this.state.focusedValueIndex=void 0}get displayTypeOptions(){return[{value:`chip`,label:j(`Chip`)},{value:`arrow`,label:j(`Arrow`)},{value:`plainText`,label:j(`Plain text`)}]}};function wT(){let e,n=document.body.style.cursor,r=[],i=()=>{e=void 0,document.body.style.cursor=n,r.forEach(e=>e()),r=[]},a=(t,a)=>{let s=()=>{document.body.style.cursor=`move`,e&&(Object.assign(o.itemsStyle,e.getItemStyles()),a.onChange?.())};o.cancel=()=>{o.draggedItemId=void 0,o.itemsStyle={},document.body.style.cursor=n,a.onCancel?.(),i()};let c=(e,t)=>{o.draggedItemId=void 0,o.itemsStyle={},document.body.style.cursor=n,a.onDragEnd?.(e,t),i()};document.body.style.cursor=`move`,o.draggedItemId=a.draggedItemId;let l=t===`horizontal`?new OT(a.scrollableContainerEl):new DT(a.scrollableContainerEl);e=new TT({...a,container:l,onChange:s,onDragEnd:c,onCancel:o.cancel});let u=bT(e.onMouseMove.bind(e),e.onMouseUp.bind(e));r.push(u);let d=e.onScroll.bind(e);a.scrollableContainerEl.addEventListener(`scroll`,d),r.push(()=>a.scrollableContainerEl.removeEventListener(`scroll`,d)),r.push(e.destroy.bind(e))};(0,t.onWillUnmount)(()=>{i()});let o=(0,t.useState)({itemsStyle:{},draggedItemId:void 0,start:a,cancel:()=>{}});return o}var TT=class{draggedItemId;items;container;initialMousePosition;currentMousePosition;initialScroll;minPosition;maxPosition;edgeScrollIntervalId;onChange;onCancel;onDragEnd;deadZone;constructor(e){this.items=e.items.map(e=>({...e,positionAtStart:e.position})),this.draggedItemId=e.draggedItemId,this.container=e.container,this.onChange=e.onChange,this.onCancel=e.onCancel,this.onDragEnd=e.onDragEnd,this.initialMousePosition=e.initialMousePosition,this.currentMousePosition=e.initialMousePosition,this.initialScroll=this.container.scroll,this.minPosition=this.items[0].position,this.maxPosition=this.items[this.items.length-1].position+this.items[this.items.length-1].size}getItemStyles(){let e={};for(let t of this.items)e[t.id]=this.getItemStyle(t.id);return e}getItemStyle(e){let t=this.container.cssPositionProperty,n={};return n.position=`relative`,n[t]=(this.getItemsPositions()[e]||0)+`px`,n.transition=`${t} 0.5s`,n[`pointer-events`]=`none`,this.draggedItemId===e&&(n.transition=`${t} 0s`,n[`z-index`]=`1000`),W(n)}onScroll(){this.moveDraggedItemToPosition(this.currentMousePosition+this.scrollOffset)}onMouseMove(e){if(e.button>1){this.onCancel();return}let t=this.container.getMousePosition(e);if(this.currentMousePosition=t,t<this.container.start||t>this.container.end){this.startEdgeScroll(t<this.container.start?-1:1);return}else this.stopEdgeScroll();this.moveDraggedItemToPosition(t+this.scrollOffset)}moveDraggedItemToPosition(e){let t=this.getHoveredItemIndex(e,this.items),n=this.items.findIndex(e=>e.id===this.draggedItemId),r=this.items[n];if(this.deadZone&&this.isInZone(e,this.deadZone)){this.onChange(this.getItemsPositions());return}else this.isInZone(e,{start:r.position,end:r.position+r.size})&&(this.deadZone=void 0);if(n===t){this.onChange(this.getItemsPositions());return}let i=Math.min(n,t),a=Math.max(n,t),o=Math.sign(t-n),s=0;for(let e=i;e<=a;e++)e!==n&&(this.items[e].position-=o*r.size,s+=this.items[e].size);r.position+=o*s,this.items.sort((e,t)=>e.position-t.position),this.deadZone=o>0?{start:e,end:r.position}:{start:r.position+r.size,end:e},this.onChange(this.getItemsPositions())}onMouseUp(e){e.button!==0&&this.onCancel(),e.stopPropagation(),e.preventDefault();let t=this.items.findIndex(e=>e.id===this.draggedItemId);return this.onDragEnd(this.draggedItemId,t),this.stopEdgeScroll(),!1}startEdgeScroll(e){this.edgeScrollIntervalId||=window.setInterval(()=>{let t=e*3;this.container.scroll+=t},5)}stopEdgeScroll(){window.clearInterval(this.edgeScrollIntervalId),this.edgeScrollIntervalId=void 0}getHoveredItemIndex(e,t){return e<=this.minPosition?0:e>=this.maxPosition?t.length-1:t.findIndex(t=>t.position+t.size>=e)}getItemsPositions(){let e={};for(let t of this.items){if(t.id!==this.draggedItemId){e[t.id]=t.position-t.positionAtStart;continue}let n=this.currentMousePosition-this.initialMousePosition+this.scrollOffset;n=Math.max(this.minPosition-t.positionAtStart,n),n=Math.min(this.maxPosition-t.positionAtStart-t.size,n),e[t.id]=n}return e}isInZone(e,t){return e>=t.start&&e<=t.end}get scrollOffset(){return this.container.scroll-this.initialScroll}destroy(){this.stopEdgeScroll()}},ET=class{el;constructor(e){this.el=e}get containerRect(){return this.el.getBoundingClientRect()}},DT=class extends ET{get start(){return this.containerRect.top}get end(){return this.containerRect.bottom}get cssPositionProperty(){return`top`}get scroll(){return this.el.scrollTop}set scroll(e){this.el.scrollTop=e}getMousePosition(e){return e.clientY}},OT=class extends ET{get start(){return this.containerRect.left}get end(){return this.containerRect.right}get cssPositionProperty(){return`left`}get scroll(){return this.el.scrollLeft}set scroll(e){this.el.scrollLeft=e}getMousePosition(e){return e.clientX}},kT=class{mutators=[`focus`,`unfocus`];focusedElement=null;focus(e){this.focusedElement=e}unfocus(e){this.focusedElement&&this.focusedElement===e&&(this.focusedElement=null)}},AT=class extends wr{initialRanges;inputHasSingleRange;colors;disabledRanges;mutators=[`resetWithRanges`,`focusById`,`unfocus`,`addEmptyRange`,`removeRange`,`changeRange`,`reset`,`confirm`,`updateColors`,`updateDisabledRanges`,`toggleEditMode`];ranges=[];focusedRangeIndex=null;mode=`text-edit`;inputSheetId;focusStore=this.get(kT);highlightStore=this.get(cT);constructor(e,t=[],n=!1,r=[],i=[]){if(super(e),this.initialRanges=t,this.inputHasSingleRange=n,this.colors=r,this.disabledRanges=i,n&&t.length>1)throw Error(`Input with a single range cannot be instantiated with several range references.`);this.inputSheetId=this.getters.getActiveSheetId(),this.resetWithRanges(t),this.highlightStore.register(this),this.onDispose(()=>{this.unfocus(),this.highlightStore.unRegister(this)})}handleEvent(e){if(this.focusedRangeIndex===null)return;let t=this.inputSheetId,n=this.getters.getActiveSheetId(),r=e.options.unbounded?this.getters.getUnboundedZone(n,e.anchor.zone):e.anchor.zone,i=this.getters.getRangeFromZone(n,r);if(e.mode===`newAnchor`&&!this.inputHasSingleRange&&this.ranges[this.focusedRangeIndex].xc.trim()!==``){let e=this.getters.getSelectionRangeString(i,t);this.insertNewRange(this.ranges.length,[e]),this.focusLast()}else{let e=i.parts,n=this.ranges[this.focusedRangeIndex].xc.trim();n&&(e=this.getters.getRangeFromSheetXC(t,n).parts);let r={...i,parts:e},a=this.getters.getSelectionRangeString(r,t);this.setRange(this.focusedRangeIndex,[a])}this.mode=`select-range`}handle(e){switch(e.type){case`ACTIVATE_SHEET`:if(e.sheetIdFrom!==e.sheetIdTo){let{col:t,row:n}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:0,row:0}),r=this.getters.expandZone(e.sheetIdTo,D({col:t,row:n}));this.model.selection.resetAnchor(this,{cell:{col:t,row:n},zone:r})}break;case`START_CHANGE_HIGHLIGHT`:let t=this.getters.getActiveSheetId(),n=this.getters.expandZone(t,e.zone),r=this.ranges.findIndex(e=>{let{xc:r,sheetName:i}=Yo(e.xc),a=i||this.getters.getSheetName(this.inputSheetId);if(this.getters.getSheetName(t)!==a)return!1;let o=this.getters.getRangeFromSheetXC(t,r);return Mn(this.getters.expandZone(t,o.zone),n)});if(r!==-1){this.focus(r);let{left:e,top:t}=n;this.model.selection.resetAnchor(this,{cell:{col:e,row:t},zone:n})}break}}changeRange(e,t){if(this.inputHasSingleRange&&t.split(`,`).length>1)return;let n=this.getIndex(e);if(n!==null&&this.focusedRangeIndex!==n&&this.focus(n),n!==null){let e=t.replace(/^,+/,``).split(`,`).map(e=>e.trim());this.setRange(n,e),this.captureSelection()}}addEmptyRange(){this.inputHasSingleRange&&this.ranges.length===1||(this.insertNewRange(this.ranges.length,[``]),this.focusLast())}removeRange(e){if(this.ranges.length===1)return;let t=this.getIndex(e);t!==null&&this.removeRangeByIndex(t)}updateColors(e){this.colors=e;let t=new ui(this.ranges.length,this.colors);this.ranges=this.ranges.map(e=>({...e,color:t.next()}))}updateDisabledRanges(e){this.disabledRanges=e}confirm(){for(let e of this.selectionInputs)e.xc===``&&this.removeRange(e.id);let e=this.getters.getActiveSheetId();this.inputSheetId!==e&&this.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:e,sheetIdTo:this.inputSheetId}),this.selectionInputValues.join()!==this.initialRanges.join()&&this.resetWithRanges(this.selectionInputValues),this.initialRanges=this.selectionInputValues,this.unfocus()}reset(){this.resetWithRanges(this.initialRanges),this.confirm()}get selectionInputValues(){return this.cleanInputs(this.ranges.map(e=>e.xc?e.xc:``))}get selectionInputs(){return this.ranges.map((e,t)=>Object.assign({},e,{color:this.hasMainFocus&&this.focusedRangeIndex!==null&&this.getters.isRangeValid(e.xc)?e.color:null,isFocused:this.hasMainFocus&&this.focusedRangeIndex===t,isValidRange:e.xc===``||this.getters.isRangeValid(e.xc),disabled:this.disabledRanges?.[t]}))}get isResettable(){return this.initialRanges.join()!==this.ranges.map(e=>e.xc).join()}get isConfirmable(){return this.selectionInputs.every(e=>e.isValidRange)}get hasFocus(){return this.selectionInputs.some(e=>e.isFocused)}get hasMainFocus(){let e=this.focusStore.focusedElement;return!!e&&e===this}get highlights(){return this.hasMainFocus?this.ranges.map(e=>this.inputToHighlights(e)).flat():[]}focusById(e){let t=this.getIndex(e);if(this.focusedRangeIndex!==t||this.mode===`select-range`){this.focus(t),this.mode=`text-edit`;return}return`noStateChange`}focus(e){this.focusStore.focus(this),this.focusedRangeIndex=e,this.captureSelection()}focusLast(){this.focus(this.ranges.length-1)}unfocus(){this.focusedRangeIndex=null,this.focusStore.unfocus(this),this.model.selection.release(this)}captureSelection(){if(this.focusedRangeIndex===null)return;let e=this.ranges[this.focusedRangeIndex],t=this.getters.getActiveSheetId(),n=this.getters.getRangeFromSheetXC(t,e?.xc||`A1`).zone;this.model.selection.capture(this,{cell:{col:n.left,row:n.top},zone:n},{handleEvent:this.handleEvent.bind(this),release:this.unfocus.bind(this)})}resetWithRanges(e){e.length&&e.every(e=>this.getters.isRangeValid(e))&&(this.initialRanges=e),this.ranges=[],this.insertNewRange(0,e),this.ranges.length===0&&(this.insertNewRange(this.ranges.length,[``]),this.focusLast())}setContent(e,t){this.ranges[e]={...this.ranges[e],xc:t}}insertNewRange(e,t){let n=Math.max(0,...this.ranges.map(e=>Number(e.id))),r=new ui(this.ranges.length,this.colors);for(let t=0;t<e;t++)r.next();this.ranges.splice(e,0,...t.map((e,t)=>({xc:e,id:n+t+1,color:r.next()})))}setRange(e,t){let[,...n]=t;this.setContent(e,t[0]),this.insertNewRange(e+1,n),n.length&&this.focus(e+n.length)}removeRangeByIndex(e){this.ranges.splice(e,1),this.focusedRangeIndex!==null&&this.focusLast()}inputToHighlights({xc:e,color:t}){return this.cleanInputs([e]).filter(e=>this.getters.isRangeValid(e)).filter(e=>this.shouldBeHighlighted(this.inputSheetId,e)).map(e=>{let{sheetName:n}=Yo(e),r=n&&this.getters.getSheetIdByName(n)||this.inputSheetId;return{range:this.getters.getRangeFromSheetXC(r,e),color:t,interactive:!0}})}cleanInputs(e){return e.map(e=>e.split(`,`)).flat().map(e=>e.trim()).filter(e=>e!==``)}shouldBeHighlighted(e,t){let{sheetName:n}=Yo(t),r=this.getters.getSheetIdByName(n),i=this.getters.getActiveSheet().id;return this.getters.isRangeValid(t)&&(r===i||r===void 0&&i===e)}getIndex(e){let t=this.ranges.findIndex(t=>t.id===e);return t>=0?t:null}toggleEditMode(){this.mode=this.mode===`select-range`?`text-edit`:`select-range`}},jT=class extends t.Component{static template=`o-spreadsheet-SelectionInput`;static props={ranges:Array,hasSingleRange:{type:Boolean,optional:!0},required:{type:Boolean,optional:!0},autofocus:{type:Boolean,optional:!0},isInvalid:{type:Boolean,optional:!0},class:{type:String,optional:!0},onSelectionChanged:{type:Function,optional:!0},onSelectionConfirmed:{type:Function,optional:!0},onSelectionReordered:{type:Function,optional:!0},onSelectionRemoved:{type:Function,optional:!0},onInputFocused:{type:Function,optional:!0},colors:{type:Array,optional:!0,default:[]},disabledRanges:{type:Array,optional:!0,default:[]},disabledRangeTitle:{type:String,optional:!0}};state=(0,t.useState)({isMissing:!1});dragAndDrop=wT();focusedInput=(0,t.useRef)(`focusedInput`);selectionRef=(0,t.useRef)(`o-selection`);DOMFocusableElementStore;store;get ranges(){return this.store.selectionInputs}get canAddRange(){return!this.props.hasSingleRange}get isInvalid(){return this.props.isInvalid||this.state.isMissing}get isConfirmable(){return this.store.isConfirmable}get isResettable(){return this.store.isResettable}get hasDisabledRanges(){return this.store.disabledRanges.some(Boolean)}setup(){(0,t.useEffect)(()=>this.focusedInput.el?.focus(),()=>[this.focusedInput.el]),(0,t.useEffect)(()=>{(this.store.isResettable||this.store.hasFocus)&&this.selectionRef.el?.offsetParent===null&&this.reset()}),this.DOMFocusableElementStore=O(ly),this.store=hr(AT,this.props.ranges,this.props.hasSingleRange||!1,this.props.colors,this.props.disabledRanges),this.props.autofocus&&(this.store.focusById(this.store.selectionInputs[0]?.id),this.props.onInputFocused?.()),(0,t.onWillUpdateProps)(e=>{e.ranges.join()!==this.store.selectionInputValues.join()&&this.triggerChange(),e.ranges.join()!==this.props.ranges.join()&&e.ranges.join()!==this.store.selectionInputValues.join()&&this.store.resetWithRanges(e.ranges),e.colors?.join()!==this.props.colors?.join()&&e.colors?.join()!==this.store.colors.join()&&this.store.updateColors(e.colors||[]),!T(e.disabledRanges,this.props.disabledRanges)&&!T(e.disabledRanges,this.store.disabledRanges)&&this.store.updateDisabledRanges(e.disabledRanges||[])})}startDragAndDrop(e,t){if(t.button!==0||t.target.tagName===`SELECT`)return;let n=this.getRangeElementsRects(),r=this.ranges.map(e=>e.id),i=r.map((e,t)=>({id:e.toString(),size:n[t].height,position:n[t].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.toString(),initialMousePosition:t.clientY,items:i,scrollableContainerEl:this.selectionRef.el,onDragEnd:(t,n)=>{let i=r.findIndex(t=>t===e);if(i===n)return;let a=C(0,r.length);a.splice(i,1),a.splice(n,0,i),this.props.onSelectionReordered?.(a),this.props.onSelectionConfirmed?.(),this.store.confirm()}})}getRangeElementsRects(){return Array.from(this.selectionRef.el.children).map(e=>e.getBoundingClientRect())}getColor(e){let t={};return e.color&&(t.color=e.color),this.store.mode===`select-range`&&(t[`caret-color`]=`transparent`),W(t)}triggerChange(){let e=this.store.selectionInputValues;this.props.onSelectionChanged?.(e)}onKeydown(e){e.key===`F2`?(e.preventDefault(),e.stopPropagation(),this.store.toggleEditMode()):e.key.startsWith(`Arrow`)?(e.stopPropagation(),this.store.mode===`select-range`&&(e.preventDefault(),Pw(e,this.env.model.selection))):e.key===`Enter`?(e.target.blur(),this.isConfirmable&&this.confirm()):e.key===`Escape`&&(this.reset(),this.DOMFocusableElementStore.focus())}extractRanges(e){return this.props.hasSingleRange?e.split(`,`)[0]:e}focus(e){this.state.isMissing=!1,this.store.focusById(e),this.props.onInputFocused?.()}addEmptyInput(){this.store.addEmptyRange()}removeInput(e){let t=this.store.selectionInputs.findIndex(t=>t.id===e);this.ranges.find(t=>t.id===e)?.xc&&(this.props.onSelectionRemoved?.(t),this.props.onSelectionConfirmed?.()),this.store.removeRange(e)}onInputChanged(e,t){let n=t.target,r=this.extractRanges(n.value);this.store.changeRange(e,r),this.triggerChange()}reset(){this.store.reset(),this.triggerChange()}confirm(){this.store.confirm();let e=this.store.selectionInputs.some(e=>this.env.model.getters.isRangeValid(e.xc));this.props.required&&!e&&(this.state.isMissing=!0),this.props.onSelectionChanged?.(this.store.selectionInputValues),this.props.onSelectionConfirmed?.()}},MT=class extends Tw{static template=`o-spreadsheet-ValueInRangeCriterionForm`;static components={RoundColorPicker:ST,SelectionInput:jT,Select:Ty};setup(){super.setup();let e=e=>{e.criterion.displayStyle===void 0&&this.updateCriterion({displayStyle:`chip`})};(0,t.onWillUpdateProps)(e),(0,t.onWillStart)(()=>e(this.props))}onRangeChanged(e){this.updateCriterion({values:[e]})}onChangedDisplayStyle(e){this.updateCriterion({displayStyle:e})}onColorChanged(e,t){let n={...this.props.criterion.colors};n[t]=e||void 0,this.updateCriterion({colors:n})}get values(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getDataValidationRangeValues(e,this.props.criterion);return new Set(t)}get displayTypeOptions(){return[{value:`chip`,label:j(`Chip`)},{value:`arrow`,label:j(`Arrow`)},{value:`plainText`,label:j(`Plain text`)}]}};let NT={list:10,text:20,number:30,date:40,relative:45,misc:50},Q=new A;Q.add(`containsText`,{type:`containsText`,component:vT,category:`text`,sequence:10}),Q.add(`notContainsText`,{type:`notContainsText`,component:vT,category:`text`,sequence:20}),Q.add(`beginsWithText`,{type:`beginsWithText`,component:vT,category:`text`,sequence:25}),Q.add(`endsWithText`,{type:`endsWithText`,component:vT,category:`text`,sequence:26}),Q.add(`isEqualText`,{type:`isEqualText`,component:vT,category:`text`,sequence:30}),Q.add(`isEmail`,{type:`isEmail`,component:void 0,category:`text`,sequence:40}),Q.add(`isLink`,{type:`isLink`,component:void 0,category:`text`,sequence:50}),Q.add(`dateIs`,{type:`dateIs`,component:gT,category:`date`,sequence:20}),Q.add(`dateIsBefore`,{type:`dateIsBefore`,component:gT,category:`date`,sequence:30}),Q.add(`dateIsOnOrBefore`,{type:`dateIsOnOrBefore`,component:gT,category:`date`,sequence:40}),Q.add(`dateIsAfter`,{type:`dateIsAfter`,component:gT,category:`date`,sequence:50}),Q.add(`dateIsOnOrAfter`,{type:`dateIsOnOrAfter`,component:gT,category:`date`,sequence:60}),Q.add(`dateIsBetween`,{type:`dateIsBetween`,component:_T,category:`date`,sequence:70}),Q.add(`dateIsNotBetween`,{type:`dateIsNotBetween`,component:_T,category:`date`,sequence:80}),Q.add(`dateIsValid`,{type:`dateIsValid`,component:void 0,category:`date`,sequence:10}),Q.add(`isEqual`,{type:`isEqual`,component:vT,category:`number`,sequence:10}),Q.add(`isNotEqual`,{type:`isNotEqual`,component:vT,category:`number`,sequence:20}),Q.add(`isGreaterThan`,{type:`isGreaterThan`,component:vT,category:`number`,sequence:50}),Q.add(`isGreaterOrEqualTo`,{type:`isGreaterOrEqualTo`,component:vT,category:`number`,sequence:60}),Q.add(`isLessThan`,{type:`isLessThan`,component:vT,category:`number`,sequence:30}),Q.add(`isLessOrEqualTo`,{type:`isLessOrEqualTo`,component:vT,category:`number`,sequence:40}),Q.add(`isBetween`,{type:`isBetween`,component:_T,category:`number`,sequence:70}),Q.add(`isNotBetween`,{type:`isNotBetween`,component:_T,category:`number`,sequence:80}),Q.add(`isBoolean`,{type:`isBoolean`,component:void 0,category:`misc`,sequence:10}),Q.add(`isValueInList`,{type:`isValueInList`,component:CT,category:`list`,sequence:10}),Q.add(`isValueInRange`,{type:`isValueInRange`,component:MT,category:`list`,sequence:20}),Q.add(`customFormula`,{type:`customFormula`,component:vT,category:`misc`,sequence:20}),Q.add(`isEmpty`,{type:`isEmpty`,component:void 0,category:`misc`,sequence:5}),Q.add(`isNotEmpty`,{type:`isNotEmpty`,component:void 0,category:`misc`,sequence:6}),Q.add(`top10`,{type:`top10`,component:yT,category:`relative`,sequence:7}),Q.add(`uniqueValues`,{type:`uniqueValues`,component:void 0,category:`relative`,sequence:8}),Q.add(`duplicateValues`,{type:`duplicateValues`,component:void 0,category:`relative`,sequence:9});function PT(e){let t=Q.getAll().filter(t=>e.has(t.type)).sort((e,t)=>e.category===t.category?e.sequence-t.sequence:NT[e.category]-NT[t.category]);return t.map((e,n)=>({label:X.get(e.type).name,value:e.type,separator:e.category!==t[n+1]?.category}))}var FT=class extends t.Component{static template=`o-spreadsheet-FilterMenuCriterion`;static props={filterPosition:Object,onCriterionChanged:Function,criterionOperators:Array};static components={Select:Ty};state;setup(){(0,t.onWillUpdateProps)(e=>{T(e.filterPosition,this.props.filterPosition)||(this.state.criterion=this.getFilterCriterionValue(e.filterPosition))}),this.state=(0,t.useState)({criterion:this.getFilterCriterionValue(this.props.filterPosition)})}getFilterCriterionValue(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getFilterCriterionValue({sheetId:t,...e});return n?.filterType===`criterion`?x(n):{filterType:`criterion`,type:`none`,values:[]}}get criterionOptions(){return[{label:j(`None`),value:`none`},...PT(new Set(this.props.criterionOperators))]}get criterionComponent(){return this.state.criterion.type===`none`?void 0:Q.get(this.state.criterion.type).component}onCriterionChanged(e){this.state.criterion.values=e.values,this.state.criterion.dateValue=e.dateValue,this.props.onCriterionChanged(this.state.criterion)}onCriterionTypeChange(e){this.state.criterion.type=e,this.props.onCriterionChanged(this.state.criterion)}},IT=class extends t.Component{static template=`o-spreadsheet.Checkbox`;static props={label:{type:String,optional:!0},value:{type:Boolean,optional:!0},className:{type:String,optional:!0},name:{type:String,optional:!0},title:{type:String,optional:!0},disabled:{type:Boolean,optional:!0},onChange:Function};static defaultProps={value:!1};onChange(e){let t=e.target.checked;this.props.onChange(t)}},LT=class extends t.Component{static template=`o-spreadsheet-FilterMenuValueItem`;static components={Checkbox:IT};static props={value:String,isChecked:Boolean,isSelected:Boolean,onMouseMove:Function,onClick:Function,scrolledTo:{type:String,optional:!0}};itemRef=(0,t.useRef)(`menuValueItem`);setup(){(0,t.onWillPatch)(()=>{this.props.scrolledTo&&this.scrollListToSelectedValue()})}scrollListToSelectedValue(){this.itemRef.el&&this.itemRef.el.scrollIntoView?.({block:`nearest`})}},RT=class extends t.Component{static template=`o-spreadsheet-FilterMenuValueList`;static props={filterPosition:Object,onUpdateHiddenValues:Function};static components={FilterMenuValueItem:LT};state=(0,t.useState)({values:[],displayedValues:[],textFilter:``,selectedValue:void 0,numberOfDisplayedValues:50,hasMoreValues:!1});searchBar=(0,t.useRef)(`filterMenuSearchBar`);setup(){(0,t.onWillUpdateProps)(e=>{T(e.filterPosition,this.props.filterPosition)||(this.state.values=this.getFilterHiddenValues(e.filterPosition),this.computeDisplayedValues())}),this.state.values=this.getFilterHiddenValues(this.props.filterPosition),this.computeDisplayedValues()}getFilterHiddenValues(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getFilter({sheetId:t,...e});if(!n)return[];let r=this.env.model.getters.getFilterValue({sheetId:t,...e}),i=(n.filteredRange?Bn(n.filteredRange.zone):[]).map(e=>({position:e,cellValue:this.env.model.getters.getEvaluatedCell({sheetId:t,...e}).formattedValue}));r?.filterType!==`criterion`&&(i=i.filter(e=>!this.env.model.getters.isRowHidden(t,e.position.row)));let a=i.map(e=>e.cellValue),o=r?.filterType===`values`?r.hiddenValues:[],s=new Set(o.map(jd)),c=new Set,l=[],u=e=>{let t=jd(e);c.has(t)||(l.push({string:e||``,checked:r?.filterType===`criterion`?!1:!s.has(t),normalizedValue:t}),c.add(t))};return a.forEach(u),o.forEach(u),l.sort((e,t)=>e.normalizedValue.localeCompare(t.normalizedValue,void 0,{numeric:!0,sensitivity:`base`}))}checkValue(e){this.state.selectedValue=e.string,e.checked=!e.checked,this.searchBar.el?.focus(),this.updateHiddenValues()}onMouseMove(e){this.state.selectedValue=e.string}getSearchedValues(){return this.state.textFilter?fd(this.state.textFilter,this.state.values,e=>e.string):this.state.values}setAllChecked(e){let t=new Set(this.getSearchedValues());for(let n of this.state.values)t.has(n)&&(n.checked=e);this.updateHiddenValues()}selectAll(){this.setAllChecked(!0)}clearAll(){this.setAllChecked(!1)}updateHiddenValues(){let e=this.state.values.filter(e=>!e.checked).map(e=>e.string);this.props.onUpdateHiddenValues(e)}updateSearch(e){let t=e.target;this.state.textFilter=t.value,this.state.selectedValue=void 0,this.computeDisplayedValues()}computeDisplayedValues(){let e=this.getSearchedValues();this.state.displayedValues=e.slice(0,this.state.numberOfDisplayedValues),this.state.hasMoreValues=e.length>this.state.numberOfDisplayedValues}loadMoreValues(){this.state.numberOfDisplayedValues+=100,this.computeDisplayedValues()}onKeyDown(e){let t=this.state.displayedValues;if(t.length===0)return;let n;if(this.state.selectedValue!==void 0){let e=t.findIndex(e=>e.string===this.state.selectedValue);n=e===-1?void 0:e}switch(e.key){case`ArrowDown`:n=n===void 0?0:Math.min(n+1,t.length-1),e.preventDefault(),e.stopPropagation();break;case`ArrowUp`:n=n===void 0?t.length-1:Math.max(n-1,0),e.preventDefault(),e.stopPropagation();break;case`Enter`:n!==void 0&&this.checkValue(t[n]),e.stopPropagation(),e.preventDefault();break}this.state.selectedValue=n===void 0?void 0:t[n].string,(e.key===`ArrowUp`||e.key===`ArrowDown`)&&this.scrollListToSelectedValue(e.key)}clearScrolledToValue(){this.state.values.forEach(e=>e.scrolledTo=void 0)}scrollListToSelectedValue(e){this.clearScrolledToValue();let t=this.state.values.find(e=>e.string===this.state.selectedValue);t&&(t.scrolledTo=e===`ArrowUp`?`top`:`bottom`)}},zT=class extends t.Component{static template=`o-spreadsheet-FilterMenu`;static props={filterPosition:Object,onClosed:{type:Function,optional:!0}};static components={FilterMenuValueList:RT,SidePanelCollapsible:ww,FilterMenuCriterion:FT};criterionCategory=`text`;updatedCriterionValue;setup(){(0,t.onWillUpdateProps)(e=>{T(e.filterPosition,this.props.filterPosition)||(this.updatedCriterionValue=void 0,this.criterionCategory=this.getCriterionCategory(e.filterPosition))}),this.criterionCategory=this.getCriterionCategory(this.props.filterPosition)}get isSortable(){if(!this.table)return!1;let e=this.env.model.getters.getCoreTableMatchingTopLeft(this.table.range.sheetId,this.table.range.zone);return!this.env.model.getters.isReadonly()&&e?.type!==`dynamic`}get table(){let e=this.env.model.getters.getActiveSheetId(),t=this.props.filterPosition;return this.env.model.getters.getTable({sheetId:e,...t})}get filterValueType(){let e=this.env.model.getters.getActiveSheetId(),t=this.props.filterPosition;return this.env.model.getters.getFilterValue({sheetId:e,...t})?.filterType}getCriterionCategory(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getFilter({sheetId:t,...e});if(!n||!n.filteredRange)return`text`;let r={text:0,number:0,date:0},i=n.filteredRange.zone;for(let n=i.top;n<=i.bottom&&!(n>100);n++){let i=this.env.model.getters.getEvaluatedCell({sheetId:t,row:n,col:e.col});i.type===`text`||i.type===`boolean`?r.text++:i.type===`number`&&(i.format&&Il(i.format)?r.date++:r.number++)}let a=Math.max(r.text,r.number,r.date);return Object.keys(r).find(e=>r[e]===a)||`text`}onUpdateHiddenValues(e){this.updatedCriterionValue={filterType:`values`,hiddenValues:e}}onCriterionChanged(e){this.updatedCriterionValue=e}confirm(){if(!this.updatedCriterionValue){this.props.onClosed?.();return}let e=this.props.filterPosition;this.env.model.dispatch(`UPDATE_FILTER`,{...e,sheetId:this.env.model.getters.getActiveSheetId(),value:this.updatedCriterionValue}),this.props.onClosed?.()}get criterionOperators(){return this.criterionCategory===`date`?qh:this.criterionCategory===`number`?Kh:Gh}cancel(){this.props.onClosed?.()}sortFilterZone(e){let t=this.props.filterPosition,n=this.table?.range.zone;if(!t||!n||n.top===n.bottom)return;let r=this.env.model.getters.getActiveSheetId(),i={...n,top:n.top+1},a={col:t.col,row:i.top};Sw(this.env,r,a,i,e,{emptyCellAsZero:!0,sortHeaders:!0}),this.props.onClosed?.()}};let BT={onOpen:(e,t)=>({isOpen:!0,props:{filterPosition:e},Component:zT,cellCorner:`bottom-left`})};var VT=class extends t.Component{static template=`o-spreadsheet-LinkDisplay`;static props={cellPosition:Object,onClosed:{type:Function,optional:!0}};cellPopovers;setup(){this.cellPopovers=O(vw)}get cell(){let{col:e,row:t}=this.props.cellPosition,n=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getEvaluatedCell({sheetId:n,col:e,row:t})}get link(){if(this.cell.link)return this.cell.link;let{col:e,row:t}=this.props.cellPosition;throw Error(`LinkDisplay Component can only be used with link cells. ${E(e,t)} is not a link.`)}getUrlRepresentation(e){return Pu(e,this.env.model.getters)}openLink(e){Fu(this.link,this.env,Em(e))}edit(){let{col:e,row:t}=this.props.cellPosition;this.env.model.selection.selectCell(e,t),this.cellPopovers.open({col:e,row:t},`LinkEditor`)}unlink(){let e=this.env.model.getters.getActiveSheetId(),{col:t,row:n}=this.props.cellPosition,r=this.env.model.getters.getCellComputedStyle({sheetId:e,col:t,row:n}),i=r?.textColor===`#017E84`?void 0:r?.textColor;this.env.model.dispatch(`UPDATE_CELL`,{col:t,row:n,sheetId:e,content:this.link.label,style:{...r,textColor:i,underline:void 0}})}};let HT={onHover:(e,t)=>{let n=t.getEvaluatedCell(e);return!t.isDashboard()&&n.link&&t.isVisibleInViewport(e)?{isOpen:!0,Component:VT,props:{cellPosition:e},cellCorner:`bottom-left`}:{isOpen:!1}}};var UT=class extends t.Component{static template=`o-spreadsheet-LinkEditor`;static props={cellPosition:Object,onClosed:{type:Function,optional:!0}};static components={MenuPopover:wy};static size={maxHeight:500};urlInput=(0,t.useRef)(`urlInput`);suggestionListRef=(0,t.useRef)(`suggestionList`);urlInputContainer=(0,t.useRef)(`urlInputContainer`);state=(0,t.useState)(this.defaultState);setup(){this.computeLinks(),(0,t.onMounted)(()=>this.urlInput.el?.focus())}computeLinks(){this.state.selectedIndex=null,this.state.linksByCategory=this.linkProposalByCategory,this.state.linksList=Object.values(this.state.linksByCategory).flat()}get linkProposalByCategory(){let e={},t=-1,n=this.state.url;for(let r of Au.getKeys()){let i=Au.get(r),a=i.getLinkProposals?.(this.env)||[],o=n&&this.state.isUrlEditable?fd(n,a,e=>i.urlRepresentation(e.url,this.env.model.getters)):a;o.length!==0&&(e[i.title]=o.map(e=>{t++;let n=i.urlRepresentation(e.url,this.env.model.getters),r=t;return{text:n,icon:e.icon,index:r,onSelect:()=>{this.state.url=e.url,this.state.label=e.label,this.state.isUrlEditable=e.isUrlEditable,this.state.selectedIndex=r,this.urlInputContainer.el?.focus()}}}))}return e}get defaultState(){let{col:e,row:t}=this.props.cellPosition,n=this.env.model.getters.getActiveSheetId(),r=this.env.model.getters.getEvaluatedCell({sheetId:n,col:e,row:t});return r.link?{url:r.link.url,label:r.formattedValue,isUrlEditable:r.link.isUrlEditable,selectedIndex:null,linksByCategory:{},linksList:[]}:{label:r.formattedValue,url:``,isUrlEditable:!0,selectedIndex:null,linksByCategory:{},linksList:[]}}getUrlRepresentation(e){return Pu(e,this.env.model.getters)}removeLink(){this.state.url=``,this.state.isUrlEditable=!0,this.computeLinks()}save(){let{col:e,row:t}=this.props.cellPosition,n=this.env.model.getters.getLocale(),r=this.state.label?Gy(this.state.label,n):this.state.url;this.env.model.dispatch(`UPDATE_CELL`,{col:e,row:t,sheetId:this.env.model.getters.getActiveSheetId(),content:ut(r,this.state.url)}),this.props.onClosed?.()}cancel(){this.props.onClosed?.()}onKeyDown(e){switch(e.key){case`Enter`:this.state.url&&this.save(),e.stopPropagation(),e.preventDefault();break;case`Escape`:this.cancel(),e.stopPropagation();break}}onInputKeyDown(e){switch(e.key){case`Enter`:if(this.state.selectedIndex!==null){let t=this.state.linksList[this.state.selectedIndex];if(t){let n=this.state.url;t.onSelect(),this.state.url!==n&&(e.stopPropagation(),e.preventDefault())}}break;case`ArrowDown`:this.state.selectedIndex=this.state.selectedIndex===null||this.state.selectedIndex===this.state.linksList.length-1?0:(this.state.selectedIndex+1)%this.state.linksList.length,this.showSelectedProposal(),e.stopPropagation(),e.preventDefault();break;case`ArrowUp`:this.state.selectedIndex!==null&&(this.state.selectedIndex=this.state.selectedIndex===0?this.state.linksList.length-1:(this.state.selectedIndex-1)%this.state.linksList.length,this.showSelectedProposal(),e.stopPropagation(),e.preventDefault());break}}showSelectedProposal(){this.suggestionListRef.el?.querySelector(`.suggestion-item[data-index="${this.state.selectedIndex}"]`)?.scrollIntoView({block:`nearest`})}};_w.add(`ErrorToolTip`,bw).add(`LinkCell`,HT).add(`LinkEditor`,{onOpen:(e,t)=>({isOpen:!0,props:{cellPosition:e},Component:UT,cellCorner:`bottom-left`})}).add(`FilterMenu`,BT);let WT=[`image/avif`,`image/bmp`,`image/gif`,`image/vnd.microsoft.icon`,`image/jpeg`,`image/png`,`image/tiff`,`image/webp`];function GT(e,t){let n=new Set(t.map(e=>e.left)),r=new Set(t.map(e=>e.right)),i=new Set(t.map(e=>e.top)),a=new Set(t.map(e=>e.bottom)),o=i.size===1&&a.size===1||n.size===1&&r.size===1?Gn(t):[t[t.length-1]],s=o.map(e=>Bn(e)).flat();return{sheetId:e,zones:t,clippedZones:o,columnsIndexes:[...new Set(s.map(e=>e.col))].sort((e,t)=>e-t),rowsIndexes:[...new Set(s.map(e=>e.row))].sort((e,t)=>e-t)}}function KT(e,t,n){let r=Math.max(e.right-t+1,e.left),i=Math.max(e.bottom-n+1,e.top),a=[];for(let o=e.left;o<=r;o+=t)for(let r=e.top;r<=i;r+=n)a.push({left:o,top:r,bottom:r+n-1,right:o+t-1});return a}function qT(e,t){if(!t.length||!t[0].length)return e;let n=t[0].length,r=t.length;return e.map(e=>KT(e,n,r)).flat()}function JT(e){let t;e[`text/html`]&&(t=XT(new DOMParser().parseFromString(e[`text/html`],`text/html`)));let n=e[`text/plain`]||``,r;if(!n.trim()){for(let t of WT)if(e[t]){r=e[t];break}}return{text:n,data:t,imageBlob:r}}function YT(e){return e?.match(/<div data-osheet-clipboard-id=(['"])([^'"]+)\1/)?.[2]}function XT(e){if([...e.documentElement.attributes].some(e=>e.value.includes(`microsoft`)))return;let t=e.querySelector(`div`)?.getAttribute(`data-osheet-clipboard`);return t&&JSON.parse(t)}let ZT=(e,t,n,r)=>{e.forEach(({handlerName:e,handler:i})=>{let a=t[e];a&&i.paste(n,a,r)})};function QT(e,t,n,r,i){let a,o=[],s={sheetId:e,zones:t};for(let{handlerName:c,handler:l}of r){let r=n[c];if(!r)continue;let u=l.getPasteTarget(e,t,r,i);u.figureId&&(s.figureId=u.figureId);for(let e of u.zones){if(o.push(e),a===void 0){a=e;continue}a=kn(a,e)}}return{target:s,zone:a,selectedZones:o}}let $T=(e,t,n)=>{let r={col:t[0].left,row:t[0].top};e.getBackToDefault(),e.selectZone({cell:r,zone:kn(...n)},{scrollIntoView:!1})},eE={type:`bar`,title:{},dataSource:{type:`range`,dataSets:[],dataSetsHaveTitle:!1},dataSetStyles:{},legendPosition:`none`,stacked:!1,humanize:!0},tE={type:`line`,title:{},dataSource:{type:`range`,dataSets:[],dataSetsHaveTitle:!1},dataSetStyles:{},legendPosition:`none`,stacked:!1,cumulative:!1,labelsAsText:!1,humanize:!0};function nE(e,t){return wn(e.getUnboundedZone(e.getActiveSheetId(),t))}function rE(e){if(!e.length)return`empty`;let t={number:0,text:0,date:0,percentage:0},n=0,r=`empty`;for(let i of e){let e=null;if(i.type===`number`?e=i.format&&Il(i.format)?`date`:i.format?.includes(`%`)?`percentage`:`number`:i.type===`text`&&(e=`text`),e){let i=++t[e];i>n&&(n=i,r=e)}}return r}function iE(e,t){let n=[];for(let r of nr(e)){let e=t.getEvaluatedCellsInZone(t.getActiveSheetId(),r);n.push({zone:r,type:rE(e)})}return n}function aE(e,t){let n=e.getEvaluatedCellsInZone(e.getActiveSheetId(),t).map(e=>e.value?.toString().trim()||``).filter(e=>e);return{uniqueCount:new Set(n).size,totalCount:n.length}}function oE(e,t){let n=e.getEvaluatedCell({sheetId:e.getActiveSheetId(),col:t.zone.left,row:t.zone.top});return![`number`,`empty`].includes(n.type)}function sE(e,t){let{type:n,zone:r}=e,i=t.getActiveSheetId(),a=oE(t,e),o=nE(t,r),s=t.getEvaluatedCell({sheetId:i,col:r.left,row:r.top});if(Xn(r)===1)return uE(r,t);switch(n){case`percentage`:return{type:`pie`,title:a?{text:String(s.value)}:{},dataSource:{type:`range`,dataSets:[{dataRange:o,dataSetId:`0`}],dataSetsHaveTitle:a},dataSetStyles:{},legendPosition:`none`};case`text`:let e=t.getEvaluatedCellsInZone(i,r).reduce((e,t)=>t.value===s.value?e+1:e,0),n=s.value!==null&&e===1;return{type:`pie`,title:n?{text:String(s.value)}:{},dataSource:{type:`range`,dataSets:[{dataRange:o,dataSetId:`0`}],labelRange:o,dataSetsHaveTitle:n},dataSetStyles:{},aggregated:!0,legendPosition:`top`};case`date`:return{...tE,type:`line`,title:a?{text:String(s.value)}:{},dataSource:{type:`range`,dataSets:[{dataRange:o,dataSetId:`0`}],dataSetsHaveTitle:a},dataSetStyles:{}}}return{...eE,title:a?{text:String(s.value)}:{},dataSource:{type:`range`,dataSets:[{dataRange:o,dataSetId:`0`}],dataSetsHaveTitle:a},dataSetStyles:{}}}function cE(e,t){if(e.length!==2)throw Error(`buildTwoColumnChart expects exactly two columns`);if(e[1].type===`percentage`)return{type:`pie`,title:{},dataSource:{type:`range`,dataSets:[{dataRange:nE(t,e[1].zone),dataSetId:`0`}],labelRange:nE(t,e[0].zone),dataSetsHaveTitle:oE(t,e[1])},dataSetStyles:{},aggregated:!0,legendPosition:`none`};if(e[0].type===`number`&&e[1].type===`number`)return{type:`scatter`,title:{},dataSource:{type:`range`,dataSets:[{dataRange:nE(t,e[1].zone),dataSetId:`0`}],labelRange:nE(t,e[0].zone),dataSetsHaveTitle:oE(t,e[1])},dataSetStyles:{},labelsAsText:!1,legendPosition:`none`};if(e[0].type===`date`&&e[1].type===`number`)return{...tE,type:`line`,dataSource:{type:`range`,dataSets:[{dataRange:nE(t,e[1].zone),dataSetId:`0`}],labelRange:nE(t,e[0].zone),dataSetsHaveTitle:oE(t,e[0])},dataSetStyles:{}};if(e[0].type===`text`&&e[1].type===`number`){let n=e[0],r=e[1],{uniqueCount:i,totalCount:a}=aE(t,n.zone),o=oE(t,r);if(i!==a)return{type:`treemap`,title:{},dataSource:{type:`range`,dataSets:[{dataRange:nE(t,n.zone),dataSetId:`0`}],labelRange:nE(t,r.zone),dataSetsHaveTitle:o},dataSetStyles:{},legendPosition:`none`}}return{...eE,dataSource:{type:`range`,dataSets:[{dataRange:nE(t,e[1].zone),dataSetId:`0`}],labelRange:nE(t,e[0].zone),dataSetsHaveTitle:oE(t,e[1])},dataSetStyles:{}}}function lE(e,t){if(e.length<3)throw Error(`buildMultiColumnChart expects at least three columns`);let n=e.some(e=>e.type!==`text`&&oE(t,e)),r=e[e.length-1],i=e.slice(0,e.length-1);if((r.type===`percentage`||r.type===`number`)&&i.every(e=>e.type===`text`)){let e=i.map(({zone:e},n)=>({dataRange:nE(t,e),dataSetId:n.toString()}));return{type:i.length>=3?`sunburst`:`treemap`,title:{},dataSource:{type:`range`,dataSets:e,dataSetsHaveTitle:n,labelRange:nE(t,r.zone)},dataSetStyles:{},legendPosition:`none`}}let a=e[0],o=e.slice(1),s=o.map(({zone:e},n)=>({dataRange:nE(t,e),dataSetId:n.toString()}));return o.every(e=>e.type===`percentage`)?{type:`pie`,title:{},dataSource:{type:`range`,dataSets:s,labelRange:nE(t,a.zone),dataSetsHaveTitle:n},dataSetStyles:{},aggregated:!1,legendPosition:`top`}:a.type===`date`&&o.every(e=>e.type===`number`)?{...tE,type:`line`,dataSource:{type:`range`,dataSets:s,labelRange:nE(t,a.zone),dataSetsHaveTitle:n},dataSetStyles:{},legendPosition:`top`}:{...eE,dataSource:{type:`range`,dataSets:s,labelRange:nE(t,a.zone),dataSetsHaveTitle:n},dataSetStyles:{},legendPosition:`top`}}function uE(e,t){let n=t.getCell({sheetId:t.getActiveSheetId(),col:e.left,row:e.top});return{type:`scorecard`,title:{},keyValue:nE(t,e),background:n?.style?.fillColor,baselineMode:Ae,baselineColorUp:je,baselineColorDown:Me}}function dE(e,t){let n=iE(e,t);if(n.length===0||n.every(e=>e.type===`empty`)){let e=n.map(({zone:e},n)=>({dataRange:nE(t,e),dataSetId:n.toString()}));return{...eE,dataSource:{type:`range`,dataSets:e,dataSetsHaveTitle:!1}}}let r=n.filter(e=>e.type!==`empty`);switch(r.length){case 1:return{humanize:!0,...sE(r[0],t)};case 2:return{humanize:!0,...cE(r,t)};default:return{humanize:!0,...lE(r,t)}}}function fE(e,t,n=BS){let r=e.model.getters.getSelectedZones(),i=e.model.getters.canCreateDynamicTableOnZones(t,r);r.length===1&&!i&&Xn(r[0])===1&&(e.model.selection.selectTableAroundSelection(),r=e.model.getters.getSelectedZones(),i=e.model.getters.canCreateDynamicTableOnZones(t,r));let a=r.map(n=>e.model.getters.getRangeDataFromZone(t,n)),o=e.model.dispatch(`CREATE_TABLE`,{ranges:a,sheetId:t,config:n,tableType:i?`dynamic`:`static`});return o.isCancelledBecause(`TableOverlap`)?e.raiseError(Vy.Errors.TableOverlap):o.isCancelledBecause(`NonContinuousTargets`)&&e.raiseError(Vy.Errors.NonContinuousTargets),o}function pE(e,t){e.model.dispatch(`SET_FORMATTING_WITH_PIVOT`,{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),format:t})}function mE(e,t){e.model.dispatch(`SET_FORMATTING`,{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),style:t})}let hE=async e=>_E(e),gE=async e=>_E(e,`asValue`);async function _E(e,t){let n=await e.clipboard.read();switch(n.status){case`ok`:let r=e.model.getters.getClipboardId(),i=e.model.getters.getSelectedZones();r===YT(n.content[`text/html`])?hw(e,i,t):await gw(e,i,JT(n.content),t),e.model.getters.isCutOperation()&&t!==`asValue`&&await e.clipboard.write({"text/plain":``});break;case`notImplemented`:e.raiseError(j(`Pasting from the context menu is not supported in this browser. Use keyboard shortcuts ctrl+c / ctrl+v instead.`));break;case`permissionDenied`:e.raiseError(j(`Access to the clipboard denied by the browser. Please enable clipboard permission for this page in your browser settings.`));break}}let vE=e=>_E(e,`onlyFormat`),yE=e=>{if(e.model.getters.getSelectedZones().length>1)return j(`Clear rows`);let t,n,r=e.model.getters.getActiveRows();if(r.size!==0)t=Ht([...r]),n=Vt([...r]);else{let r=e.model.getters.getSelectedZones()[0];t=r.top,n=r.bottom}return t===n?j(`Clear row %s`,(t+1).toString()):j(`Clear rows %s - %s`,(t+1).toString(),(n+1).toString())},bE=e=>{let t=e.model.getters.getActiveSheetId(),n=[...e.model.getters.getActiveRows()].map(n=>e.model.getters.getRowsZone(t,n,n));e.model.dispatch(`DELETE_CONTENT`,{target:n,sheetId:e.model.getters.getActiveSheetId()})},xE=e=>{if(e.model.getters.getSelectedZones().length>1)return j(`Clear columns`);let t,n,r=e.model.getters.getActiveCols();if(r.size!==0)t=Ht([...r]),n=Vt([...r]);else{let r=e.model.getters.getSelectedZones()[0];t=r.left,n=r.right}return t===n?j(`Clear column %s`,Zt(t)):j(`Clear columns %s - %s`,Zt(t),Zt(n))},SE=e=>{let t=e.model.getters.getActiveSheetId(),n=[...e.model.getters.getActiveCols()].map(n=>e.model.getters.getColsZone(t,n,n));e.model.dispatch(`DELETE_CONTENT`,{target:n,sheetId:e.model.getters.getActiveSheetId()})},CE=e=>{if(e.model.getters.getSelectedZones().length>1)return j(`Delete rows`);let t,n,r=e.model.getters.getActiveRows();if(r.size!==0)t=Ht([...r]),n=Vt([...r]);else{let r=e.model.getters.getSelectedZones()[0];t=r.top,n=r.bottom}return t===n?j(`Delete row %s`,(t+1).toString()):j(`Delete rows %s - %s`,(t+1).toString(),(n+1).toString())},wE=e=>{let t=[...e.model.getters.getActiveRows()];if(!t.length){let n=e.model.getters.getSelectedZones()[0];for(let e=n.top;e<=n.bottom;e++)t.push(e)}e.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),dimension:`ROW`,elements:t})},TE=(e,t)=>{if(e===`COL`&&t.model.getters.getActiveRows().size>0||e===`ROW`&&t.model.getters.getActiveCols().size>0)return!1;let n=t.model.getters.getActiveSheetId(),r=t.model.getters.getElementsFromSelection(e),i=t.model.getters.checkElementsIncludeAllVisibleHeaders(n,e,r),a=t.model.getters.checkElementsIncludeAllNonFrozenHeaders(n,e,r);return!i&&!a},EE=e=>{if(e.model.getters.getSelectedZones().length>1)return j(`Delete columns`);let t,n,r=e.model.getters.getActiveCols();if(r.size!==0)t=Ht([...r]),n=Vt([...r]);else{let r=e.model.getters.getSelectedZones()[0];t=r.left,n=r.right}return t===n?j(`Delete column %s`,Zt(t)):j(`Delete columns %s - %s`,Zt(t),Zt(n))},DE=e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getElementsFromSelection(`ROW`);return!e.model.getters.checkElementsIncludeAllVisibleHeaders(t,`ROW`,n)},OE=e=>{let t=[...e.model.getters.getActiveCols()];if(!t.length){let n=e.model.getters.getSelectedZones()[0];for(let e=n.left;e<=n.right;e++)t.push(e)}e.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),dimension:`COL`,elements:t})},kE=e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getElementsFromSelection(`COL`);return!e.model.getters.checkElementsIncludeAllVisibleHeaders(t,`COL`,n)},AE=e=>{let t=e.model.getters.getActiveRows(),n,r;if(t.size)n=Ht([...t]),r=t.size;else{let t=e.model.getters.getSelectedZones()[0];n=t.top,r=t.bottom-t.top+1}e.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:`before`,base:n,quantity:r,dimension:`ROW`})},jE=e=>{let t=e.model.getters.getActiveRows(),n,r;if(t.size)n=Vt([...t]),r=t.size;else{let t=e.model.getters.getSelectedZones()[0];n=t.bottom,r=t.bottom-t.top+1}e.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:`after`,base:n,quantity:r,dimension:`ROW`})},ME=e=>{let t=e.model.getters.getActiveCols(),n,r;if(t.size)n=Ht([...t]),r=t.size;else{let t=e.model.getters.getSelectedZones()[0];n=t.left,r=t.right-t.left+1}e.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:`before`,dimension:`COL`,base:n,quantity:r})},NE=e=>{let t=e.model.getters.getActiveCols(),n,r;if(t.size)n=Vt([...t]),r=t.size;else{let t=e.model.getters.getSelectedZones()[0];n=t.right,r=t.right-t.left+1}e.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),sheetName:e.model.getters.getActiveSheetName(),position:`after`,dimension:`COL`,base:n,quantity:r})},PE=e=>{let t=e.model.getters.getElementsFromSelection(`COL`),n=t[0],r=t[t.length-1];return t.length===1?j(`Hide column %s`,Zt(n).toString()):r-n+1===t.length?j(`Hide columns %s - %s`,Zt(n).toString(),Zt(r).toString()):j(`Hide columns`)},FE=e=>{let t=e.model.getters.getElementsFromSelection(`ROW`),n=t[0],r=t[t.length-1];return t.length===1?j(`Hide row %s`,(n+1).toString()):r-n+1===t.length?j(`Hide rows %s - %s`,(n+1).toString(),(r+1).toString()):j(`Hide rows`)},IE=e=>{let t=e.model.getters,n=e.model.uuidGenerator.smallUuid(),r=t.getActiveSheetId(),i=t.getSelectedZones();i.length===1&&Xn(i[0])===1&&(e.model.selection.selectTableAroundSelection(),i=t.getSelectedZones());let a={width:536,height:335},{col:o,row:s,offset:c}=Mv(t,a);e.model.dispatch(`CREATE_CHART`,{sheetId:r,figureId:n,chartId:e.model.uuidGenerator.smallUuid(),col:o,row:s,offset:c,size:a,definition:dE(i,e.model.getters)}).isSuccessful&&(e.model.dispatch(`SELECT_FIGURE`,{figureId:n}),e.openSidePanel(`ChartPanel`))},LE=e=>{let t=e.model.getters,n=e.model.uuidGenerator.smallUuid(),r=t.getActiveSheetId(),i={width:536,height:335},{col:a,row:o,offset:s}=Mv(t,i);e.model.dispatch(`CREATE_CAROUSEL`,{sheetId:r,figureId:n,col:a,row:o,offset:s,size:i,definition:{items:[]}}).isSuccessful&&(e.model.dispatch(`SELECT_FIGURE`,{figureId:n}),e.openSidePanel(`CarouselPanel`,{figureId:n}))},RE=e=>{let t=e.model.uuidGenerator.smallUuid(),n=e.model.uuidGenerator.smallUuid();e.model.dispatch(`INSERT_NEW_PIVOT`,{pivotId:t,newSheetId:n}).isSuccessful&&e.openSidePanel(`PivotSidePanel`,{pivotId:t})},zE=e=>e.model.getters.getPivotIds().map((t,n)=>({id:`reinsert_dynamic_pivot_${e.model.getters.getPivotFormulaId(t)}`,name:e.model.getters.getPivotDisplayName(t),sequence:n,execute:e=>{let n=e.model.getters.getSelectedZone(),r=e.model.getters.getPivot(t).getCollapsedTableStructure().export();e.model.dispatch(`INSERT_PIVOT_WITH_TABLE`,{pivotId:t,table:r,col:n.left,row:n.top,sheetId:e.model.getters.getActiveSheetId(),pivotMode:`dynamic`}),e.model.dispatch(`REFRESH_PIVOT`,{id:t})},isVisible:e=>e.model.getters.getPivot(t).isValid()})),BE=e=>e.model.getters.getPivotIds().map((t,n)=>({id:`reinsert_static_pivot_${e.model.getters.getPivotFormulaId(t)}`,name:e.model.getters.getPivotDisplayName(t),sequence:n,execute:e=>{let n=e.model.getters.getSelectedZone(),r=e.model.getters.getPivot(t).getExpandedTableStructure();if(r.numberOfCells>5e5){e.notifyUser({type:`warning`,text:Uy(r.numberOfCells,e.model.getters.getLocale()),sticky:!0});return}e.model.dispatch(`INSERT_PIVOT_WITH_TABLE`,{pivotId:t,table:r.export(),col:n.left,row:n.top,sheetId:e.model.getters.getActiveSheetId(),pivotMode:`static`}),e.model.dispatch(`REFRESH_PIVOT`,{id:t})},isVisible:e=>e.model.getters.getPivot(t).isValid()})),VE=async e=>{if(e.imageProvider){let t=e.model.getters.getActiveSheetId(),n=e.model.uuidGenerator.smallUuid(),r=await e.imageProvider.requestImage(),i=Nv(e.model.getters,r.size),{col:a,row:o,offset:s}=Mv(e.model.getters,i);e.model.dispatch(`CREATE_IMAGE`,{sheetId:t,figureId:n,col:a,row:o,offset:s,size:i,definition:r})}},HE=e=>pE(e,`0.00%`),UE=e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getSelectedZones(),r=e.model.getters.getConditionalFormats(t),i=e.model.getters.getRulesSelection(t,n);return i.length===1?e.openSidePanel(`ConditionalFormattingEditor`,{cf:r.find(e=>e.id===i[0]),isNewCf:!1}):e.openSidePanel(`ConditionalFormatting`)},WE=e=>{let{col:t,row:n}=e.model.getters.getActivePosition();e.getStore(vw).open({col:t,row:n},`LinkEditor`)},GE=e=>{let t=e.model.getters.getActiveSheetId(),{col:n,row:r}=e.model.getters.getActivePosition(),i=e.model.getters.getEvaluatedCell({sheetId:t,col:n,row:r});return i&&i.link?j(`Edit link`):j(`Insert link`)},KE=e=>e.model.getters.getFirstTableInSelection()?.config.hasFilters||!1,qE=e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getSelectedZones(),r=e.model.getters.getTablesOverlappingZones(t,n);return r.length===1&&!r[0].isPivotTable},JE=e=>er(e.model.getters.getSelectedZones()),YE=e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getFirstTableInSelection();n?e.model.dispatch(`UPDATE_TABLE`,{sheetId:t,zone:n.range.zone,config:{hasFilters:!0}}):fE(e,t,{...BS,hasFilters:!0,bandedRows:!1,styleId:`TableStyleLight11`})},XE=e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getFirstTableInSelection();n&&e.model.dispatch(`UPDATE_TABLE`,{sheetId:t,zone:n.range.zone,config:{hasFilters:!1}})},ZE=e=>{fE(e,e.model.getters.getActiveSheetId()).isSuccessful&&e.openSidePanel(`TableSidePanel`,{})},QE=e=>{let t=e.model.getters.getFirstTableInSelection();t&&e.model.dispatch(`REMOVE_TABLE`,{sheetId:e.model.getters.getActiveSheetId(),target:[t.range.zone]})},$E=e=>e.model.getters.getSelectedZones().length===1,eD=(e,t)=>{if(!$E(e))return!1;let n=t===`COL`?e.model.getters.getActiveCols():e.model.getters.getActiveRows(),r=t===`COL`?e.model.getters.getActiveRows():e.model.getters.getActiveCols(),i=e.model.getters.getActiveSheetId(),a=Mn(e.model.getters.getSelectedZone(),e.model.getters.getSheetZone(i));return Nt(n)&&(r.size===0||a)},tD={name:e=>KE(e)?j(`Remove selected filters`):j(`Add filters`),isEnabled:e=>JE(e),execute:e=>KE(e)?XE(e):YE(e),icon:`o-spreadsheet-Icon.FILTER_ICON_ACTIVE`},nD={name:e=>{let t=ID(e);return t===1?j(`Insert row`):j(`Insert %s rows`,t.toString())},isVisible:e=>eD(e,`ROW`),icon:`o-spreadsheet-Icon.INSERT_ROW`},rD={name:e=>{let t=ID(e);return t===1?j(`Insert row above`):j(`Insert %s rows above`,t.toString())},execute:AE,isVisible:e=>eD(e,`ROW`),icon:`o-spreadsheet-Icon.INSERT_ROW_BEFORE`},iD={...rD,name:e=>{let t=ID(e);return t===1?j(`Row above`):j(`%s Rows above`,t.toString())}},aD={...rD,name:e=>{let t=ID(e);return t===1?j(`Insert row`):j(`Insert %s rows`,t.toString())},isVisible:$E,icon:`o-spreadsheet-Icon.INSERT_ROW_BEFORE`},oD={execute:jE,name:e=>{let t=ID(e);return t===1?j(`Insert row below`):j(`Insert %s rows below`,t.toString())},isVisible:e=>eD(e,`ROW`),icon:`o-spreadsheet-Icon.INSERT_ROW_AFTER`},sD={...oD,name:e=>{let t=ID(e);return t===1?j(`Row below`):j(`%s Rows below`,t.toString())}},cD={name:e=>{let t=LD(e);return t===1?j(`Insert column`):j(`Insert %s columns`,t.toString())},isVisible:e=>eD(e,`COL`),icon:`o-spreadsheet-Icon.INSERT_COL`},lD={name:e=>{let t=LD(e);return t===1?j(`Insert column left`):j(`Insert %s columns left`,t.toString())},execute:ME,isVisible:e=>eD(e,`COL`),icon:`o-spreadsheet-Icon.INSERT_COL_BEFORE`},uD={...lD,name:e=>{let t=LD(e);return t===1?j(`Column left`):j(`%s Columns left`,t.toString())}},dD={...lD,name:e=>{let t=LD(e);return t===1?j(`Insert column`):j(`Insert %s columns`,t.toString())},isVisible:$E,icon:`o-spreadsheet-Icon.INSERT_COL_BEFORE`},fD={name:e=>{let t=LD(e);return t===1?j(`Insert column right`):j(`Insert %s columns right`,t.toString())},execute:NE,isVisible:e=>eD(e,`COL`),icon:`o-spreadsheet-Icon.INSERT_COL_AFTER`},pD={...fD,name:e=>{let t=LD(e);return t===1?j(`Column right`):j(`%s Columns right`,t.toString())},execute:NE},mD={name:j(`Insert cells`),isVisible:e=>$E(e)&&e.model.getters.getActiveCols().size===0&&e.model.getters.getActiveRows().size===0,icon:`o-spreadsheet-Icon.INSERT_CELL`},hD={name:j(`Insert cells and shift down`),execute:e=>{let t=e.model.getters.getSelectedZone();mw(e,e.model.dispatch(`INSERT_CELL`,{zone:t,shiftDimension:`ROW`}))},isVisible:e=>e.model.getters.getActiveRows().size===0&&e.model.getters.getActiveCols().size===0,icon:`o-spreadsheet-Icon.INSERT_CELL_SHIFT_DOWN`},gD={name:j(`Insert cells and shift right`),execute:e=>{let t=e.model.getters.getSelectedZone();mw(e,e.model.dispatch(`INSERT_CELL`,{zone:t,shiftDimension:`COL`}))},isVisible:e=>e.model.getters.getActiveRows().size===0&&e.model.getters.getActiveCols().size===0,icon:`o-spreadsheet-Icon.INSERT_CELL_SHIFT_RIGHT`},_D={name:j(`Chart`),execute:IE,isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.INSERT_CHART`},vD={name:j(`Carousel`),execute:LE,isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.CAROUSEL`},yD={name:j(`Pivot table`),execute:RE,isEnabled:e=>!e.isSmall,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.PIVOT`},bD={name:j(`Image`),shortcut:`Ctrl+O`,execute:VE,isVisible:e=>e.imageProvider!==void 0,isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.INSERT_IMAGE`},xD={name:()=>j(`Table`),description:`Alt+T`,execute:ZE,isVisible:e=>JE(e)&&!e.model.getters.getFirstTableInSelection(),isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.PAINT_TABLE`},SD={name:j(`Function`),icon:`o-spreadsheet-Icon.FORMULA`},CD={name:j(`SUM`),execute:e=>e.startCellEdition(`=SUM(`)},wD={name:j(`AVERAGE`),execute:e=>e.startCellEdition(`=AVERAGE(`)},TD={name:j(`COUNT`),execute:e=>e.startCellEdition(`=COUNT(`)},ED={name:j(`MAX`),execute:e=>e.startCellEdition(`=MAX(`)},DD={name:j(`MIN`),execute:e=>e.startCellEdition(`=MIN(`)},OD={name:j(`All`),children:[kD]};function kD(){return FD(Fo.getKeys().filter(e=>!Fo.get(e).hidden))}let AD=()=>{let e=Fo.content;return[...new Set(Fo.getAll().filter(e=>!e.hidden).map(e=>e.category))].filter(w).sort().map((t,n)=>({name:t,children:FD(Object.keys(e).filter(n=>e[n].category===t&&!e[n].hidden)),sequence:60+n}))},jD={name:j(`Link`),description:`Ctrl+K`,execute:WE,icon:`o-spreadsheet-Icon.INSERT_LINK`},MD={name:j(`Checkbox`),execute:e=>{let t=e.model.getters.getSelectedZones(),n=e.model.getters.getActiveSheetId(),r=t.map(t=>e.model.getters.getRangeDataFromZone(n,t));e.model.dispatch(`ADD_DATA_VALIDATION_RULE`,{ranges:r,sheetId:n,rule:{id:e.model.uuidGenerator.smallUuid(),criterion:{type:`isBoolean`,values:[]}}})},icon:`o-spreadsheet-Icon.INSERT_CHECKBOX`},ND={name:j(`Dropdown list`),execute:e=>{let t=e.model.getters.getSelectedZones(),n=e.model.getters.getActiveSheetId(),r=t.map(t=>e.model.getters.getRangeDataFromZone(n,t)),i=e.model.uuidGenerator.smallUuid();e.model.dispatch(`ADD_DATA_VALIDATION_RULE`,{ranges:r,sheetId:n,rule:{id:i,criterion:{type:`isValueInList`,values:[],displayStyle:`chip`}}}),e.model.getters.getDataValidationRule(n,i)&&e.openSidePanel(`DataValidationEditor`,{ruleId:i,onCancel:()=>{e.model.dispatch(`REMOVE_DATA_VALIDATION_RULE`,{sheetId:n,id:i})}})},isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.INSERT_DROPDOWN`},PD={name:j(`Insert sheet`),description:`Shift+F11`,execute:e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getSheetIds().indexOf(t)+1,r=e.model.uuidGenerator.smallUuid();e.model.dispatch(`CREATE_SHEET`,{sheetId:r,position:n,name:e.model.getters.getNextSheetName()}),e.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:t,sheetIdTo:r})},icon:`o-spreadsheet-Icon.INSERT_SHEET`};function FD(e){return e.sort().map((e,t)=>({name:e,sequence:t*10,execute:t=>t.startCellEdition(`=${e}(`)}))}function ID(e){let t=e.model.getters.getActiveRows();if(t.size)return t.size;{let t=e.model.getters.getSelectedZones()[0];return t.bottom-t.top+1}}function LD(e){let t=e.model.getters.getActiveCols();if(t.size)return t.size;{let t=e.model.getters.getSelectedZones()[0];return t.right-t.left+1}}function RD({refName:e}){let n=(0,t.useRef)(e);(0,t.useEffect)(e=>{e?.focus()},()=>[n.el])}var zD=class extends t.Component{static props={value:[Number,String],onChange:Function,onFocused:{type:Function,optional:!0},onBlur:{type:Function,optional:!0},onInput:{type:Function,optional:!0},class:{type:String,optional:!0},id:{type:String,optional:!0},placeholder:{type:String,optional:!0},autofocus:{type:Boolean,optional:!0},alwaysShowBorder:{type:Boolean,optional:!0},selectContentOnFocus:{type:Boolean,optional:!0},resetOnBlur:{type:Boolean,optional:!0}};refName=`input`;inputRef;lastOnChangeValue=this.props.value.toString();setup(){this.inputRef=(0,t.useRef)(this.refName),(0,t.useExternalListener)(window,`click`,e=>{let t=this.inputRef.el;!t||e.target===t||t.value===this.props.value.toString()||(this.props.resetOnBlur?t.value=this.props.value.toString():this.save())},{capture:!0}),this.props.autofocus&&RD({refName:this.refName}),(0,t.onWillUpdateProps)(e=>{document.activeElement!==this.inputRef.el&&this.inputRef.el&&(this.inputRef.el.value=e.value),this.lastOnChangeValue=e.value.toString()}),(0,t.onMounted)(()=>{this.inputRef.el&&(this.inputRef.el.value=this.props.value.toString())})}onKeyDown(e){switch(e.key){case`Enter`:this.save(),e.preventDefault(),e.stopPropagation();break;case`Escape`:this.inputRef.el&&(this.inputRef.el.value=this.props.value.toString(),this.inputRef.el.blur()),e.preventDefault(),e.stopPropagation();break}}save(){let e=(this.inputRef.el?.value||``).trim();e!==this.lastOnChangeValue&&(this.lastOnChangeValue=e,this.props.onChange(e)),document.activeElement===this.inputRef.el&&this.inputRef.el?.blur()}onMouseDown(e){e.target!==document.activeElement&&this.props.selectContentOnFocus&&(e.preventDefault(),e.stopPropagation())}onMouseUp(e){let t=e.target;t!==document.activeElement&&this.props.selectContentOnFocus&&(t.focus(),this.props.selectContentOnFocus&&t.select(),e.preventDefault(),e.stopPropagation())}onFocus(){this.props.onFocused?.()}onBlur(){this.props.onBlur?.(),this.props.resetOnBlur?this.inputRef.el&&(this.inputRef.el.value=this.props.value.toString()):this.save()}onInput(e){let t=e.target;this.props.onInput?.(t.value)}},BD=class extends zD{static template=`o-spreadsheet-TextInput`;static components={};static props={...zD.props,errorMessage:{type:String,optional:!0}};get inputClass(){return[this.props.class,`w-100 os-input`,this.props.alwaysShowBorder?`o-input-border`:void 0,this.props.errorMessage?`o-invalid`:void 0].filter(w).join(` `)}},VD=class extends t.Component{static template=`o-spreadsheet-ActionButton`;static props={action:Object,hasTriangleDownIcon:{type:Boolean,optional:!0},selectedColor:{type:String,optional:!0},class:{type:String,optional:!0},onClick:{type:Function,optional:!0}};actionButton=h(this.props.action);setup(){(0,t.onWillUpdateProps)(e=>{e.action!==this.props.action&&(this.actionButton=h(e.action))})}get isVisible(){return this.actionButton.isVisible(this.env)}get isEnabled(){let e=this.actionButton.isEnabledOnLockedSheet||!this.env.model.getters.isCurrentSheetLocked();return this.actionButton.isEnabled(this.env)&&e}get isActive(){return this.actionButton.isActive?.(this.env)}get title(){let e=this.actionButton.name(this.env),t=this.actionButton.description(this.env)||this.actionButton.shortcut;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?W({"border-bottom":`4px solid ${this.props.selectedColor}`,height:`16px`,"margin-top":`2px`}):``}},HD=class extends t.Component{static template=`o-spreadsheet-ColorPickerWidget`;static props={currentColor:{type:String,optional:!0},toggleColorPicker:Function,showColorPicker:Boolean,onColorPicked:Function,icon:String,title:{type:String,optional:!0},disabled:{type:Boolean,optional:!0},dropdownMaxHeight:{type:Number,optional:!0},class:{type:String,optional:!0}};static components={ColorPicker:xT};colorPickerButtonRef=(0,t.useRef)(`colorPickerButton`);get iconStyle(){return this.props.currentColor?`border-color: ${this.props.currentColor}`:`border-bottom-style: hidden`}get colorPickerAnchorRect(){let e=this.colorPickerButtonRef.el.getBoundingClientRect();return{x:e.x,y:e.y,width:e.width,height:e.height}}},UD=class extends t.Component{static template=`o-spreadsheet-NumberEditor`;static props={currentValue:Number,onValueChange:Function,onToggle:{type:Function,optional:!0},onFocusInput:{type:Function,optional:!0},class:String,valueIcon:{type:String,optional:!0},min:Number,max:Number,title:String,valueList:Array};static defaultProps={onFocusInput:()=>{}};static components={Popover:by};dropdown=(0,t.useState)({isOpen:!1});inputRef=(0,t.useRef)(`inputNumber`);rootEditorRef=(0,t.useRef)(`NumberEditor`);valueListRef=(0,t.useRef)(`numberList`);DOMFocusableElementStore;setup(){this.DOMFocusableElementStore=O(ly),(0,t.useExternalListener)(window,`click`,this.onExternalClick,{capture:!0}),(0,t.onWillUpdateProps)(e=>{this.inputRef.el&&document.activeElement!==this.inputRef.el&&(this.inputRef.el.value=e.currentValue)}),(0,t.onMounted)(()=>{this.inputRef.el&&(this.inputRef.el.value=this.props.currentValue.toString())})}get popoverProps(){let{x:e,y:t,width:n,height:r}=this.rootEditorRef.el.getBoundingClientRect();return{anchorRect:{x:e,y:t,width:n,height:r},positioning:`bottom-left`,verticalOffset:0}}onExternalClick(e){!fm(this.valueListRef.el,e)&&!fm(this.rootEditorRef.el,e)&&this.closeList()}toggleList(){this.dropdown.isOpen?this.closeList():(this.props.onToggle?.(),this.inputRef.el.focus())}closeList(){this.dropdown.isOpen=!1}setValue(e){let t=S(Math.floor(parseFloat(e)),this.props.min,this.props.max);this.props.onValueChange(t),this.closeList()}setValueFromInput(e){this.setValue(e.target.value)}setValueFromList(e){this.setValue(e)}get currentValue(){return`${this.props.currentValue}`}onInputFocused(e){this.dropdown.isOpen=!0,e.target.select()}onInputKeydown(e){if(e.key===`Enter`||e.key===`Escape`){this.closeList();let t=e.target;e.key===`Escape`&&(t.value=`${this.props.currentValue}`),this.props.onToggle?.()}if(e.key===`Tab`){e.preventDefault(),e.stopPropagation(),this.closeList(),this.DOMFocusableElementStore.focus();return}}},WD=class extends t.Component{static template=`o-spreadsheet-FontSizeEditor`;static components={NumberEditor:UD};static props={currentFontSize:Number,onFontSizeChanged:Function,onToggle:{type:Function,optional:!0},onFocusInput:{type:Function,optional:!0},class:String};static defaultProps={onFocusInput:()=>{}};fontSizes=ze},GD=class extends t.Component{static template=`o-spreadsheet.TextStyler`;static components={ColorPickerWidget:HD,ActionButton:VD,FontSizeEditor:WD};static props={style:Object,updateStyle:{type:Function,optional:!0},defaultStyle:{type:Object,optional:!0},hasVerticalAlign:{type:Boolean,optional:!0},hasHorizontalAlign:{type:Boolean,optional:!0},hasBackgroundColor:{type:Boolean,optional:!0},class:{type:String,optional:!0}};openedEl=null;setup(){(0,t.useExternalListener)(window,`click`,this.onExternalClick)}state=(0,t.useState)({activeTool:``});updateFontSize(e){this.props.updateStyle?.({...this.props.style,fontSize:e})}toggleDropdownTool(e,t){let n=this.state.activeTool===e;this.closeMenus(),this.state.activeTool=n?``:e,this.openedEl=n?null:t.target}onExternalClick(e){this.openedEl!==e.target&&this.closeMenus()}onTextColorChange(e){this.props.updateStyle?.({...this.props.style,color:e}),this.closeMenus()}onFillColorChange(e){this.props.updateStyle?.({...this.props.style,fillColor:e}),this.closeMenus()}updateAlignment(e){this.props.updateStyle?.({...this.props.style,align:e}),this.closeMenus()}updateVerticalAlignment(e){this.props.updateStyle?.({...this.props.style,verticalAlign:e}),this.closeMenus()}toggleBold(){this.props.updateStyle?.({...this.props.style,bold:!this.bold})}toggleItalic(){this.props.updateStyle?.({...this.props.style,italic:!this.italic})}closeMenus(){this.state.activeTool=``,this.openedEl=null}get align(){return this.props.style.align??this.props.defaultStyle?.align}get verticalAlign(){return this.props.style.verticalAlign||this.props.defaultStyle?.verticalAlign}get bold(){return this.props.style.bold??this.props.defaultStyle?.bold}get italic(){return this.props.style.italic??this.props.defaultStyle?.italic}get currentFontSize(){return this.props.style.fontSize??this.props.defaultStyle?.fontSize??xe.fontSize}get boldButtonAction(){return{name:j(`Bold`),execute:()=>this.toggleBold(),isActive:()=>this.bold||!1,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.BOLD`}}get italicButtonAction(){return{name:j(`Italic`),execute:()=>this.toggleItalic(),isActive:()=>this.italic||!1,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.ITALIC`}}get horizontalAlignButtonAction(){let e=`o-spreadsheet-Icon.ALIGN_LEFT`;return this.align===`center`?e=`o-spreadsheet-Icon.ALIGN_CENTER`:this.align===`right`&&(e=`o-spreadsheet-Icon.ALIGN_RIGHT`),{name:j(`Horizontal alignment`),icon:e,isEnabledOnLockedSheet:!0}}get horizontalAlignActions(){return[{name:j(`Left`),execute:()=>this.updateAlignment(`left`),isActive:()=>this.align===`left`,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.ALIGN_LEFT`},{name:j(`Center`),execute:()=>this.updateAlignment(`center`),isActive:()=>this.align===`center`,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.ALIGN_CENTER`},{name:j(`Right`),execute:()=>this.updateAlignment(`right`),isActive:()=>this.align===`right`,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.ALIGN_RIGHT`}]}get verticalAlignButtonAction(){let e=`o-spreadsheet-Icon.ALIGN_MIDDLE`;return this.verticalAlign===`top`?e=`o-spreadsheet-Icon.ALIGN_TOP`:this.verticalAlign===`bottom`&&(e=`o-spreadsheet-Icon.ALIGN_BOTTOM`),{name:j(`Vertical alignment`),icon:e,isEnabledOnLockedSheet:!0}}get verticalAlignActions(){return[{name:j(`Top`),execute:()=>this.updateVerticalAlignment(`top`),isActive:()=>this.verticalAlign===`top`,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.ALIGN_TOP`},{name:j(`Middle`),execute:()=>this.updateVerticalAlignment(`middle`),isActive:()=>this.verticalAlign===`middle`,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.ALIGN_MIDDLE`},{name:j(`Bottom`),execute:()=>this.updateVerticalAlignment(`bottom`),isActive:()=>this.verticalAlign===`bottom`,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.ALIGN_BOTTOM`}]}},KD=class extends t.Component{static template=`o-spreadsheet-CogWheelMenu`;static components={MenuPopover:wy};static props={items:Array};buttonRef=(0,t.useRef)(`button`);menuState=(0,t.useState)({isOpen:!1,anchorRect:null,menuItems:[]});menuId=this.env.model.uuidGenerator.uuidv4();toggleMenu(e){e.closedMenuId!==this.menuId&&(this.menuState.isOpen=!this.menuState.isOpen,this.menuState.anchorRect=gm(this.buttonRef.el),this.menuState.menuItems=p(this.props.items))}},qD=class extends t.Component{static template=`o-spreadsheet-CarouselPanel`;static props={onCloseSidePanel:Function,figureId:String};static components={Section:Z,TextInput:BD,TextStyler:GD,CogWheelMenu:KD};DEFAULT_CAROUSEL_TITLE_STYLE=Ue;dragAndDrop=wT();previewListRef=(0,t.useRef)(`previewList`);setup(){let e=[...this.carouselItems];(0,t.onWillUpdateProps)(()=>{T(this.carouselItems,e)||this.dragAndDrop.cancel(),e=[...this.carouselItems]})}get carouselItems(){return this.env.model.getters.getCarousel(this.props.figureId).items}get title(){return this.env.model.getters.getCarousel(this.props.figureId).title}get carousel(){return this.env.model.getters.getCarousel(this.props.figureId)}getPreviewDivStyle(e){return this.dragAndDrop.itemsStyle[this.getItemId(e)]||``}getItemId(e){return e.type===`chart`?e.chartId:`transparent-carousel`}addNewChartToCarousel(){this.env.model.dispatch(`ADD_NEW_CHART_TO_CAROUSEL`,{figureId:this.props.figureId,sheetId:this.carouselSheetId})}get hasDataView(){return this.carouselItems.some(e=>e.type===`carouselDataView`)}isCarouselItemActive(e){return T(this.env.model.getters.getSelectedCarouselItem(this.props.figureId),e)}addDataViewToCarousel(){let e=this.env.model.getters.getCarousel(this.props.figureId);this.updateItems([...e.items,{type:`carouselDataView`}])}activateCarouselItem(e){this.env.model.dispatch(`UPDATE_CAROUSEL_ACTIVE_ITEM`,{figureId:this.props.figureId,sheetId:this.carouselSheetId,item:e})}editCarouselItem(e){e.type===`chart`&&(this.activateCarouselItem(e),this.env.model.dispatch(`SELECT_FIGURE`,{figureId:this.props.figureId}),this.env.openSidePanel(`ChartPanel`,{chartId:e.chartId}))}renameCarouselItem(e,t){let n=t.trim();if(!n||n===this.getItemTitle(e).toString())return;let r=[...this.carouselItems],i=this.carouselItems.findIndex(t=>T(t,e));i!==-1&&(r[i]={...e,title:n},this.updateItems(r))}deleteCarouselItem(e){let t=this.env.model.getters.getCarousel(this.props.figureId).items.filter(t=>!T(t,e));this.updateItems(t)}popOutCarouselItem(e){e.type===`chart`&&this.env.model.dispatch(`POPOUT_CHART_FROM_CAROUSEL`,{sheetId:this.carouselSheetId,carouselId:this.props.figureId,chartId:e.chartId})}duplicateCarouselChart(e){e.type===`chart`&&this.env.model.dispatch(`DUPLICATE_CAROUSEL_CHART`,{sheetId:this.carouselSheetId,carouselId:this.props.figureId,chartId:e.chartId,duplicatedChartId:this.env.model.uuidGenerator.smallUuid()})}onDragHandleMouseDown(e,t){if(t.button!==0)return;let n=Array.from(this.previewListRef.el.children).map(e=>gm(e)),r=this.carouselItems.map((e,t)=>({id:this.getItemId(e),size:n[t].height,position:n[t].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:this.getItemId(e),initialMousePosition:t.clientY,items:r,scrollableContainerEl:this.previewListRef.el,onDragEnd:(t,n)=>this.onDragEnd(e,n)})}onDragEnd(e,t){let n=this.carouselItems.findIndex(t=>T(t,e));if(n===-1||n===t)return;let r=[...this.env.model.getters.getCarousel(this.props.figureId).items];r.splice(n,1),r.splice(t,0,e),this.updateItems(r)}getItemTitle(e){return Gv(this.env.model.getters,e)}getItemPreview(e){return Wv(this.env.model.getters,e)}updateItems(e){this.env.model.dispatch(`UPDATE_CAROUSEL`,{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...this.carousel,items:e}})}updateTitleText(e){let t=this.env.model.getters.getCarousel(this.props.figureId);this.env.model.dispatch(`UPDATE_CAROUSEL`,{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...t,title:{...t.title,text:e}}})}updateTitleStyle(e){let t=this.env.model.getters.getCarousel(this.props.figureId);this.env.model.dispatch(`UPDATE_CAROUSEL`,{figureId:this.props.figureId,sheetId:this.carouselSheetId,definition:{...t,title:{...t.title,...e}}})}get carouselAddChartInfoMessage(){return j(`Add a chart to the carousel. You can also add a chart by dragging and dropping it over the carousel figure.`)}getCogWheelMenuItems(e){let t=[];return e.type===`chart`&&(t.push({name:j(`Edit chart`),execute:()=>this.editCarouselItem(e),icon:`o-spreadsheet-Icon.EDIT`}),t.push({name:j(`Pop out chart`),execute:()=>this.popOutCarouselItem(e),icon:`o-spreadsheet-Icon.EXTERNAL`}),t.push({name:j(`Duplicate chart`),execute:()=>this.duplicateCarouselChart(e),icon:`o-spreadsheet-Icon.COPY`})),t.push({name:j(`Delete item`),execute:()=>this.deleteCarouselItem(e),icon:`o-spreadsheet-Icon.TRASH`}),t}get carouselSheetId(){let e=this.env.model.getters.getFigureSheetId(this.props.figureId);if(!e)throw Error(`Could not find the sheetId of the carousel figure`);return e}get carouselDataViewMessage(){return j(`The data view makes the carousel transparent, revealing the data underneath.`)}};let JD=new A,YD={chartId:String,definition:Object,canUpdateChart:Function,updateChart:Function};var XD=class extends t.Component{static template=`o-spreadsheet.ChartDataSeries`;static components={SelectionInput:jT,Section:Z};static props={ranges:Array,dataSetStyles:Object,hasSingleRange:{type:Boolean,optional:!0},onSelectionChanged:Function,onSelectionReordered:{type:Function,optional:!0},onSelectionRemoved:{type:Function,optional:!0},onSelectionConfirmed:Function,title:{type:String,optional:!0},maxNumberOfUsedRanges:{type:Number,optional:!0},datasetOrientation:{type:String,optional:!0},canChangeDatasetOrientation:{type:Boolean,optional:!0},onFlipAxis:{type:Function,optional:!0}};get ranges(){return this.props.ranges.map(e=>e.dataRange)}get disabledRanges(){return this.props.ranges.map((e,t)=>this.props.maxNumberOfUsedRanges?t>=this.props.maxNumberOfUsedRanges:!1)}get colors(){return this.props.ranges.map(e=>this.props.dataSetStyles?.[e.dataSetId]?.backgroundColor)}get title(){return this.props.title?this.props.title:this.props.hasSingleRange?j(`Data range`):j(`Data series`)}},ZD=class extends t.Component{static template=`o-spreadsheet.ChartLabelRange`;static components={SelectionInput:jT,Checkbox:IT,Section:Z};static props={title:{type:String,optional:!0},range:String,isInvalid:Boolean,onSelectionChanged:Function,onSelectionConfirmed:Function,options:{type:Array,optional:!0}};static defaultProps={title:j(`Categories / Labels`),options:[]}},QD=class extends t.Component{static template=`o-spreadsheet-ChartDataSourceComponent`;static components={ChartDataSeries:XD,ChartLabelRange:ZD};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function,onErrorMessagesChanged:{type:Function,optional:!0},dataSeriesTitle:{type:String,optional:!0},labelRangeTitle:{type:String,optional:!0},getLabelRangeOptions:{type:Function,optional:!0}};get DataSourceComponent(){let e=this.props.definition.dataSource.type;return JD.get(e)}},$D=class extends t.Component{static template=`o-spreadsheet-ValidationMessages`;static props={messages:Array,msgType:String,singleBox:{type:Boolean,optional:!0}};get divClasses(){return this.props.msgType===`warning`?`o-validation-warning`:this.props.msgType===`info`?`o-validation-info`:`o-validation-error`}get alertBoxes(){return this.props.singleBox?[this.props.messages]:this.props.messages.map(e=>[e])}},eO=class extends t.Component{static template=`o-spreadsheet.ChartErrorSection`;static components={Section:Z,ValidationMessages:$D};static props={messages:{type:Array,element:String}}},tO=class extends t.Component{static template=`o-spreadsheet-GenericChartConfigPanel`;static components={ChartDataSourceComponent:QD,Section:Z,Checkbox:IT,ChartErrorSection:eO};static props=YD;chartTerms=Py;state=(0,t.useState)({errorMessages:[]});onErrorMessagesChanged(e){this.state.errorMessages=e}get errorMessages(){return this.state.errorMessages}getLabelRangeOptions(){return[this.getAggregateLabelRangeOption()]}getAggregateLabelRangeOption(){return{name:`aggregated`,label:this.chartTerms.AggregatedChart,value:(`aggregated`in this.props.definition?this.props.definition.aggregated:!1)??!1,onChange:e=>{this.props.updateChart(this.props.chartId,{aggregated:e})}}}},nO=class extends tO{static template=`o-spreadsheet-BarConfigPanel`;get stackedLabel(){return this.props.definition.horizontal?this.chartTerms.StackedBarChart:this.chartTerms.StackedColumnChart}onUpdateStacked(e){this.props.updateChart(this.props.chartId,{stacked:e})}getLabelRangeOptions(){return[this.getAggregateLabelRangeOption()]}},rO=class extends zD{static template=`o-spreadsheet-NumberInput`;static components={};static props={...zD.props,min:{type:Number,optional:!0},max:{type:Number,optional:!0}};debouncedOnChange=_t(this.props.onChange.bind(this),100,!0);save(){let e=(this.inputRef.el?.value||``).trim();e!==this.props.value.toString()&&this.debouncedOnChange(e)}get inputClass(){return[this.props.class,`o-input`].join(` `)}},iO=class extends rO{static template=`o-spreadsheet-DateInput`},aO=class extends t.Component{static template=`o-spreadsheet.BadgeSelection`;static props={choices:Array,onChange:Function,selectedValue:String}},oO=class extends t.Component{static template=`o-spreadsheet.ChartTitle`;static components={Section:Z,TextStyler:GD,TextInput:BD};static props={title:{type:String,optional:!0},placeholder:{type:String,optional:!0},updateTitle:Function,name:{type:String},style:Object,defaultStyle:{type:Object,optional:!0},updateStyle:Function};static defaultProps={title:``,placeholder:``};updateTitle(e){this.props.updateTitle(e)}},sO=class extends t.Component{static template=`o-spreadsheet-AxisDesignEditor`;static components={Section:Z,ChartTitle:oO,BadgeSelection:aO,Checkbox:IT,NumberInput:rO,DateInput:iO};static props={chartId:String,definition:Object,updateChart:Function,axesList:Array};state=(0,t.useState)({currentAxis:`x`});defaultFontSize=12;get axisTitleStyle(){return this.props.definition.axesDesign?.[this.state.currentAxis]?.title??{}}get badgeAxes(){return this.props.axesList.map(e=>({value:e.id,label:e.name}))}getAxisTitle(){return(this.props.definition.axesDesign??{})[this.state.currentAxis]?.title?.text||``}updateAxisTitle(e){let t=x(this.props.definition.axesDesign)??{};t[this.state.currentAxis]={...t[this.state.currentAxis],title:{...t?.[this.state.currentAxis]?.title,text:e}},this.props.updateChart(this.props.chartId,{axesDesign:t})}updateAxisTitleStyle(e){let t=x(this.props.definition.axesDesign)??{};t[this.state.currentAxis]={...t[this.state.currentAxis],title:e},this.props.updateChart(this.props.chartId,{axesDesign:t})}get axisMin(){let e=this.currentAxisDesign?.min;return(this.isTimeAxis?this.formatAxisBoundary(e):e)??``}get axisMax(){let e=this.currentAxisDesign?.max;return(this.isTimeAxis?this.formatAxisBoundary(e):e)??``}get isMajorGridEnabled(){let e=this.currentAxisDesign?.gridLines;return e===void 0?this.getDefaultMajorGridValue(this.state.currentAxis):e===`major`||e===`both`}get isMinorGridEnabled(){return this.currentAxisDesign?.gridLines===`minor`||this.currentAxisDesign?.gridLines===`both`}get isValueAxis(){return`horizontal`in this.props.definition&&this.props.definition.horizontal?this.state.currentAxis===`x`:this.state.currentAxis!==`x`}get majorGridLabel(){return this.state.currentAxis===`x`?j(`Major vertical gridlines`):j(`Major horizontal gridlines`)}get minorGridLabel(){return this.state.currentAxis===`x`?j(`Minor vertical gridlines`):j(`Minor horizontal gridlines`)}updateAxisMin(e){let t=e===``?void 0:Number(e);if(t===void 0||!isNaN(t)){let e=x(this.props.definition.axesDesign)??{};e[this.state.currentAxis]={...e[this.state.currentAxis],min:t},this.props.updateChart(this.props.chartId,{axesDesign:e})}}updateTimeAxisMin(e){let t=this.parseTimeAxisBoundaryValue(e);if(t===null)return;let n=x(this.props.definition.axesDesign)??{};n[this.state.currentAxis]={...n[this.state.currentAxis],min:t},this.props.updateChart(this.props.chartId,{axesDesign:n})}updateAxisMax(e){let t=e===``?void 0:Number(e);if(t===void 0||!isNaN(t)){let e=x(this.props.definition.axesDesign)??{};e[this.state.currentAxis]={...e[this.state.currentAxis],max:t},this.props.updateChart(this.props.chartId,{axesDesign:e})}}updateTimeAxisMax(e){let t=this.parseTimeAxisBoundaryValue(e);if(t===null)return;let n=x(this.props.definition.axesDesign)??{};n[this.state.currentAxis]={...n[this.state.currentAxis],max:t},this.props.updateChart(this.props.chartId,{axesDesign:n})}toggleMajorGrid(e){let t=x(this.props.definition.axesDesign)??{},n=`none`;n=this.isMinorGridEnabled?e?`both`:`minor`:e?`major`:`none`,t[this.state.currentAxis]={...t[this.state.currentAxis],gridLines:n},this.props.updateChart(this.props.chartId,{axesDesign:t})}toggleMinorGrid(e){let t=x(this.props.definition.axesDesign)??{},n=`none`;n=this.isMajorGridEnabled?e?`both`:`major`:e?`minor`:`none`,t[this.state.currentAxis]={...t[this.state.currentAxis],gridLines:n},this.props.updateChart(this.props.chartId,{axesDesign:t})}get currentAxisDesign(){return this.props.definition.axesDesign?.[this.state.currentAxis]}getDefaultMajorGridValue(e){let{useLeftAxis:t,useRightAxis:n}=Df(this.props.definition);if(e===`x`){if(`horizontal`in this.props.definition&&this.props.definition.horizontal||this.props.definition.type===`scatter`)return!0}else if(e===`y`)return!0;else if(e===`y1`)return!t&&n;return!1}get isCategoricalAxis(){if(this.isValueAxis)return!1;let e=this.getXAxisType();return e===void 0||e===`category`}get isTimeAxis(){return this.state.currentAxis===`x`&&this.getXAxisType()===`time`}get canChangeMinorGridVisibility(){if(this.isValueAxis)return!0;if(this.isCategoricalAxis)return!1;let e=this.props.definition.type;return e===`line`||e===`scatter`}parseTimeAxisBoundaryValue(e){let t=I(e,this.env.model.getters.getLocale());return Number.isNaN(t)?null:t}formatAxisBoundary(e){if(e!==void 0)return H(e,{format:`yyyy-mm-dd`,locale:this.env.model.getters.getLocale()})}getXAxisType(){return this.env.model.getters.getChartRuntime(this.props.chartId)?.chartJsConfig.options?.scales?.x?.type}},cO=class extends t.Component{static template=`o-spreadsheet.RadioSelection`;static props={choices:Array,onChange:Function,selectedValue:{optional:!1},name:String,direction:{type:String,optional:!0}};static defaultProps={direction:`horizontal`}},lO=class extends t.Component{static template=`o-spreadsheet-GeneralDesignEditor`;static components={RoundColorPicker:ST,ChartTitle:oO,Section:Z,SidePanelCollapsible:ww,RadioSelection:cO};static props={...YD,defaultChartTitleFontSize:{type:Number,optional:!0},slots:{type:Object,optional:!0}};static defaultProps={defaultChartTitleFontSize:16};state;setup(){this.state=(0,t.useState)({activeTool:``})}get title(){return this.props.definition.title}toggleDropdownTool(e,t){let n=this.state.activeTool===e;this.state.activeTool=n?``:e}updateBackgroundColor(e){this.props.updateChart(this.props.chartId,{background:e})}updateTitle(e){let t={...this.title,text:e};this.props.updateChart(this.props.chartId,{title:t})}updateChartTitleStyle(e){let t={...this.title,...e};this.props.updateChart(this.props.chartId,{title:t}),this.state.activeTool=``}},uO=class extends t.Component{static template=`o-spreadsheet-ChartHumanizeNumbers`;static components={Checkbox:IT};static props=YD;get title(){let e=this.env.model.getters.getLocale();return j(`E.g. 1234567 -> %(value)s`,{value:H(1234567,{format:Xl({value:1234567},void 0,e),locale:e})})}},dO=class extends t.Component{static template=`o-spreadsheet-ChartLegend`;static components={Section:Z,Select:Ty};static props={...YD,isDisabled:{type:Boolean,optional:!0}};static defaultProps={isDisabled:!1};updateLegendPosition(e){this.props.updateChart(this.props.chartId,{legendPosition:e})}get legendValues(){return[{value:`none`,label:j(`None`)},{value:`top`,label:j(`Top`)},{value:`bottom`,label:j(`Bottom`)},{value:`left`,label:j(`Left`)},{value:`right`,label:j(`Right`)}]}},fO=class extends t.Component{static template=`o-spreadsheet-SeriesDesignEditor`;static components={SidePanelCollapsible:ww,Section:Z,RoundColorPicker:ST,Select:Ty};static props={...YD,slots:{type:Object,optional:!0}};state=(0,t.useState)({dataSetId:this.getDataSeries()[0]?.dataSetId||``});getRuntime(){let e=this.env.model.getters.getChartRuntime(this.props.chartId);if(!e||!(`customizableSeries`in e))throw Error(`SeriesDesignEditor: chart runtime is not compatible with series customization.`);return e}getDataSeries(){return this.getRuntime().customizableSeries}updateEditedSeries(e){this.state.dataSetId=e}updateDataSeriesColor(e){let t={...this.props.definition.dataSetStyles};t[this.state.dataSetId]={...t[this.state.dataSetId],backgroundColor:e},this.props.updateChart(this.props.chartId,{dataSetStyles:t})}getDataSeriesColor(){let e=this.props.definition.dataSetStyles[this.state.dataSetId]?.backgroundColor,t=this.getDataSeries(),n=t.findIndex(e=>e.dataSetId===this.state.dataSetId);return e?Nr(e):si(n,ci(t.length))}updateDataSeriesLabel(e){let t=e.target.value,n={...this.props.definition.dataSetStyles};n[this.state.dataSetId]={...n[this.state.dataSetId],label:t},this.props.updateChart(this.props.chartId,{dataSetStyles:n})}getDataSeriesLabel(){return this.props.definition.dataSetStyles[this.state.dataSetId]?.label||this.getDataSeries().find(e=>e.dataSetId===this.state.dataSetId)?.label||``}get selectOptions(){return this.getDataSeries().map(({label:e,dataSetId:t})=>({value:t,label:e}))}},pO=class extends t.Component{static template=`o-spreadsheet-SeriesWithAxisDesignEditor`;static components={SeriesDesignEditor:fO,Checkbox:IT,RadioSelection:cO,Section:Z,RoundColorPicker:ST,NumberInput:rO,Select:Ty};static props={...YD,slots:{type:Object,optional:!0}};axisChoices=Af;updateDataSeriesAxis(e,t){let n={...this.props.definition.dataSetStyles};n[e]={...n[e],yAxisId:t===`left`?`y`:`y1`},this.props.updateChart(this.props.chartId,{dataSetStyles:n})}getDataSerieAxis(e){let t=this.props.definition.dataSetStyles;return t?.[e]&&t[e]?.yAxisId===`y1`?`right`:`left`}get canHaveTwoVerticalAxis(){return!(`horizontal`in this.props.definition&&this.props.definition.horizontal)}toggleDataTrend(e,t){let n={...this.props.definition.dataSetStyles};n[e]={...n[e],trend:{type:`polynomial`,order:1,...n[e]?.trend,display:t}},this.props.updateChart(this.props.chartId,{dataSetStyles:n})}getTrendLineConfiguration(e){return this.props.definition.dataSetStyles?.[e]?.trend}getTrendType(e){return e?e.type===`polynomial`&&e.order===1?`linear`:e.type:``}onChangeTrendType(e,t){let n;switch(t){case`linear`:case`polynomial`:n={type:`polynomial`,order:t===`linear`?1:this.getMaxPolynomialDegree(e)};break;case`exponential`:case`logarithmic`:case`trailingMovingAverage`:n={type:t};break;default:return}this.updateTrendLineValue(e,n)}get trendOptions(){return[{value:`linear`,label:j(`Linear`)},{value:`polynomial`,label:j(`Polynomial`)},{value:`exponential`,label:j(`Exponential`)},{value:`logarithmic`,label:j(`Logarithmic`)},{value:`trailingMovingAverage`,label:j(`Trailing moving average`)}]}getPolynomialDegrees(e){return C(1,this.getMaxPolynomialDegree(e)+1).map(e=>({value:e.toString(),label:e.toString()}))}onChangePolynomialDegree(e,t){this.updateTrendLineValue(e,{order:parseInt(t)})}getMaxPolynomialDegree(e){let t=this.env.model.getters.getChartRuntime(this.props.chartId),n=t.customizableSeries.findIndex(t=>t.dataSetId===e);return Math.min(10,t.chartJsConfig.data.datasets[n].data.length-1)}get defaultWindowSize(){return 2}onChangeMovingAverageWindow(e,t){let n=parseInt(t)||2;n<=1&&(n=2),this.updateTrendLineValue(e,{window:n})}getDataSeriesColor(e){let t=this.props.definition.dataSetStyles;if(!t?.[e])return``;let n=t[e]?.backgroundColor,r=this.env.model.getters.getChartRuntime(this.props.chartId),i=r.customizableSeries.findIndex(t=>t.dataSetId===e);return n?Nr(n):si(i,ci(r.customizableSeries.length))}getTrendLineColor(e){return this.getTrendLineConfiguration(e)?.color??Yr(this.getDataSeriesColor(e),.5)}updateTrendLineColor(e,t){this.updateTrendLineValue(e,{color:t})}updateTrendLineValue(e,t){let n={...this.props.definition.dataSetStyles};n[e]={...n[e],trend:{...n[e]?.trend,...t}},this.props.updateChart(this.props.chartId,{dataSetStyles:n})}},mO=class extends t.Component{static template=`o-spreadsheet-ChartShowValues`;static components={Checkbox:IT};static props={...YD,defaultValue:{type:Boolean,optional:!0}}},hO=class extends t.Component{static template=`o-spreadsheet-ChartWithAxisDesignPanel`;static components={GeneralDesignEditor:lO,SidePanelCollapsible:ww,Section:Z,AxisDesignEditor:sO,SeriesWithAxisDesignEditor:pO,ChartLegend:dO,ChartShowValues:mO,ChartHumanizeNumbers:uO};static props=YD;get axesList(){let{useLeftAxis:e,useRightAxis:t}=Df(this.props.definition),n=[{id:`x`,name:j(`Horizontal axis`)}];return e&&n.push({id:`y`,name:j(t?`Left axis`:`Vertical axis`)}),t&&n.push({id:`y1`,name:j(e?`Right axis`:`Vertical axis`)}),n}},gO=class extends hO{static template=`o-spreadsheet-GenericZoomableChartDesignPanel`;static components={...hO.components,Checkbox:IT};onToggleZoom(e){this.props.updateChart(this.props.chartId,{zoomable:e})}},_O=class extends gO{static template=`o-spreadsheet-BarChartDesignPanel`;get isZoomable(){return!this.props.definition.horizontal}},vO=class extends t.Component{static template=`o-spreadsheet-ChartRangeDataSource`;static components={ChartDataSeries:XD,ChartLabelRange:ZD};static props={chartId:String,definition:Object,dataSource:Object,updateChart:Function,canUpdateChart:Function,onErrorMessagesChanged:{type:Function,optional:!0},dataSeriesTitle:{type:String,optional:!0},labelRangeTitle:{type:String,optional:!0},getLabelRangeOptions:{type:Function,optional:!0}};state=(0,t.useState)({datasetDispatchResult:void 0,labelsDispatchResult:void 0});dataSets=[];labelRange;datasetOrientation=void 0;chartTerms=Py;setup(){this.dataSets=this.props.dataSource.dataSets??[],this.labelRange=this.props.dataSource.labelRange,this.props.dataSource.type===`range`&&(this.datasetOrientation=this.computeDatasetOrientation())}get errorMessages(){return[...this.state.datasetDispatchResult?.reasons||[],...this.state.labelsDispatchResult?.reasons||[]].filter(e=>e!==`NoChanges`).map(e=>Py.Errors[e]||Py.Errors.Unexpected)}get isDatasetInvalid(){return!!this.state.datasetDispatchResult?.isCancelledBecause(`InvalidDataSet`)}get isLabelInvalid(){return!!this.state.labelsDispatchResult?.isCancelledBecause(`InvalidLabelRange`)}get dataSetsHaveTitleLabel(){return this.datasetOrientation===`rows`?j(`Use col %(column_name)s as headers`,{column_name:Zt(this.calculateHeaderPosition()||0)}):j(`Use row %(row_position)s as headers`,{row_position:this.calculateHeaderPosition()||``})}getLabelRangeOptions(){if(this.props.getLabelRangeOptions){let e=this.props.getLabelRangeOptions();return e.push({name:`dataSetsHaveTitle`,label:this.dataSetsHaveTitleLabel,value:this.props.dataSource.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}),e}let e=this.props.definition;return[{name:`aggregated`,label:this.chartTerms.AggregatedChart,value:(`aggregated`in e?e.aggregated:!1)??!1,onChange:this.onUpdateAggregated.bind(this)},{name:`dataSetsHaveTitle`,label:this.dataSetsHaveTitleLabel,value:this.props.dataSource.dataSetsHaveTitle,onChange:this.onUpdateDataSetsHaveTitle.bind(this)}]}onUpdateDataSetsHaveTitle(e){this.props.updateChart(this.props.chartId,{dataSource:{...this.props.dataSource,dataSetsHaveTitle:e}})}get canChangeDatasetOrientation(){let e=new Set,t=[],n=this.env.model.getters.getActiveSheetName(),r=this.dataSets.map(e=>e.dataRange);this.labelRange&&r.push(this.labelRange);for(let i of r){if(!xn(i))return!1;let r=Yo(i),a=vn(r.xc);if(a.bottom===void 0||a.right===void 0||(t.push(a),e.add(r.sheetName||n),e.size>1))return!1}let i=ar(t);if(i.length!==1)return!1;let{left:a,right:o,top:s,bottom:c}=i[0];return!t.some(e=>(e.top!==s||e.bottom!==c)&&(e.left!==a||e.right!==o))}computeDatasetOrientation(){let e=!1,t=!1;for(let n of this.dataSets){if(!xn(n.dataRange))return;let r=vn(n.dataRange);if(r.bottom===void 0||r.right===void 0)return;r.top===r.bottom&&(e=!0),r.left===r.right&&(t=!0)}if(e&&!t)return`rows`;if(!e&&t)return`columns`}setDatasetOrientation(e){let t=this.props.dataSource,n=t.dataSets.map(e=>e.dataRange),r=this.transposeDataSet([t.labelRange,...n],e);if(r.length===0)return;let i=r.length>1?r.shift().dataRange:``;this.props.updateChart(this.props.chartId,{dataSource:{...t,labelRange:i,dataSets:r}}),this.dataSets=r,this.labelRange=i,this.datasetOrientation=e}onDataSeriesRangesChanged(e){this.dataSets=e.map((e,t)=>({dataSetId:this.dataSets?.[t]?.dataSetId??this.env.model.uuidGenerator.smallUuid(),dataRange:e})),this.state.datasetDispatchResult=this.props.canUpdateChart(this.props.chartId,{dataSource:{...this.props.dataSource,dataSets:this.dataSets}}),this.props.onErrorMessagesChanged?.(this.errorMessages)}onDataSeriesReordered(e){let t=Np(this.props.definition.dataSetStyles,this.dataSets);this.datasetOrientation=void 0;let n={...this.props.definition.dataSetStyles};for(let e of this.dataSets){let r=t.next();n[e.dataSetId]={backgroundColor:r,...n[e.dataSetId]}}this.dataSets=e.map(e=>this.dataSets[e]),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{dataSource:{...this.props.dataSource,dataSets:this.dataSets},dataSetStyles:n}),this.props.onErrorMessagesChanged?.(this.errorMessages)}onDataSeriesRemoved(e){let t=Np(this.props.definition.dataSetStyles,this.dataSets),n={...this.props.definition.dataSetStyles};for(let e of this.dataSets){let r=t.next();n[e.dataSetId]={backgroundColor:r,...n[e.dataSetId]}}let r=this.dataSets[e].dataSetId;delete n[r],this.dataSets=this.dataSets.filter((t,n)=>n!==e),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{dataSource:{...this.props.dataSource,dataSets:this.dataSets},dataSetStyles:n}),this.props.onErrorMessagesChanged?.(this.errorMessages)}onDataSeriesConfirmed(){let{dataSets:e,dataSetStyles:t}=this.splitRanges();if(this.dataSets=e,this.datasetOrientation=this.computeDatasetOrientation(),this.state.datasetDispatchResult=this.props.updateChart(this.props.chartId,{dataSource:{...this.props.dataSource,dataSets:this.dataSets},dataSetStyles:t}),this.state.datasetDispatchResult.isSuccessful){let e=this.env.model.getters.getChartDefinition(this.props.chartId);e.dataSource.type===`range`&&(this.dataSets=e.dataSource.dataSets)}this.props.onErrorMessagesChanged?.(this.errorMessages)}splitRanges(){let e=[],t={},n=this.env.model.getters.getChartDefinition(this.props.chartId).dataSetStyles||{};for(let r of this.dataSets){let i=r.dataRange;if(!this.env.model.getters.isRangeValid(i)){e.push(r);continue}let{sheetName:a}=Yo(i),o=a?`${a}!`:``,s=vn(i);if(s.bottom!==s.top&&s.left!==s.right){if(this.datasetOrientation!==`rows`){if(s.right!==void 0)for(let i=s.left;i<=s.right;++i){let a=r.dataSetId+`_split`+i;t[a]=i===s.left?n[r.dataSetId]:{yAxisId:n[r.dataSetId]?.yAxisId},e.push({dataSetId:a,dataRange:`${o}${wn({left:i,right:i,top:s.top,bottom:s.bottom})}`})}else if(s.bottom!==void 0)for(let i=s.top;i<=s.bottom;++i){let a=r.dataSetId+`_split`+i;t[a]=i===s.top?n[r.dataSetId]:{yAxisId:n[r.dataSetId]?.yAxisId},e.push({dataSetId:a,dataRange:`${o}${wn({left:s.left,right:s.right,top:i,bottom:i})}`})}}else if(s.bottom!==void 0)for(let i=s.top;i<=s.bottom;++i){let a=r.dataSetId+`_split`+i;t[a]=i===s.top?n[r.dataSetId]:{yAxisId:n[r.dataSetId]?.yAxisId},e.push({dataSetId:a,dataRange:`${o}${wn({left:s.left,right:s.right,top:i,bottom:i})}`})}else if(s.right!==void 0)for(let i=s.left;i<=s.right;++i){let a=r.dataSetId+`_split`+i;t[a]=i===s.left?n[r.dataSetId]:{yAxisId:n[r.dataSetId]?.yAxisId},e.push({dataSetId:a,dataRange:`${o}${wn({left:i,right:i,top:s.top,bottom:s.bottom})}`})}}else e.push(r),t[r.dataSetId]=n[r.dataSetId]}return{dataSets:e,dataSetStyles:t}}getDataSeriesRanges(){return this.dataSets}onLabelRangeChanged(e){this.labelRange=e[0],this.state.labelsDispatchResult=this.props.canUpdateChart(this.props.chartId,{dataSource:{...this.props.dataSource,labelRange:this.labelRange}})}onLabelRangeConfirmed(){this.state.labelsDispatchResult=this.props.updateChart(this.props.chartId,{dataSource:{...this.props.dataSource,labelRange:this.labelRange}})}getLabelRange(){return this.labelRange||``}onUpdateAggregated(e){this.props.updateChart(this.props.chartId,{aggregated:e})}calculateHeaderPosition(){if(this.isDatasetInvalid||this.isLabelInvalid)return;let e=this.env.model.getters,t=e.getActiveSheetId(),n=nc(e,t,this.labelRange),r=_f(e,t,this.props.dataSource);if(r.length)return this.datasetOrientation===`rows`?r[0].dataRange.zone.left:r[0].dataRange.zone.top+1;if(n)return n.zone.top+1}get maxNumberOfUsedRanges(){return sS.get(this.props.definition.type).dataSeriesLimit}transposeDataSet(e,t){let n=this.env.model.getters,r=this.env.model.uuidGenerator,i=r.smallUuid.bind(r);if(t===void 0)return e.filter(w).map(e=>({dataRange:e,dataSetId:i()}));let a={},o=[],s=n.getFigureIdFromChartId(this.props.chartId),c=n.getFigureSheetId(s),l=n.getActiveSheet().name;c&&(l=n.getSheet(c).name);for(let t of e){if(!t)continue;if(!xn(t))return e.filter(w).map(e=>({dataRange:e,dataSetId:i()}));let{sheetName:n,xc:r}=Yo(t);n??=l,a[n]||(a[n]=[]),a[n]?.push(yn(r))}for(let e in a){let n=a[e],r=ar(n);if(t===`columns`)for(let t of r)for(let n=t.left;n<=t.right;n++){let r=`${e===l?``:e+`!`}${wn({...t,left:n,right:n})}`;o.push({dataRange:r,dataSetId:i()})}else for(let t of r)for(let n=t.top;n<=t.bottom;n++){let r=`${e===l?``:e+`!`}${wn({...t,top:n,bottom:n})}`;o.push({dataRange:r,dataSetId:i()})}}return o}},yO=class e{getters;sheetId;definition;chartTypeBuilder;dataSourceBuilder;dataSource;constructor(e,t,n,r,i){this.getters=e,this.sheetId=t,this.definition=n,this.chartTypeBuilder=r,this.dataSourceBuilder=i,this.dataSource=n.dataSource}static fromStrDefinition(t,n,r){let i=oS.get(r.dataSource?.type??`none`),a=sS.get(r.type),o=i.fromExternalDefinition(r.dataSource??{type:`none`},n,t),s={...a.fromStrDefinition(r,n,t),dataSource:o};return new e(t,n,e.deleteInvalidKeys(s),a,i)}static fromDefinition(t,n,r){let i=oS.get(r.dataSource?.type??`none`);return new e(t,n,r,sS.get(r.type),i)}static validate(e,t){let n=sS.get(t.type),r=oS.get(t.dataSource?.type??`none`);return e.batchValidations(()=>n.validateDefinition(e,t),()=>r.validate(t.dataSource??{type:`none`},e))(void 0)}static transformDefinition(e,t,n){let r=sS.get(t.type);if(!t.dataSource)return r.transformDefinition(t,e,n);let i=oS.get(t.dataSource?.type??`none`).transform(t.dataSource,e,n);return{...r.transformDefinition(t,e,n),dataSource:i}}getRangeDefinition(){return{...this.definition,dataSource:this.dataSource}}getDefinition(){return{...this.chartTypeBuilder.toStrDefinition(this.definition,this.sheetId,this.getters),dataSource:this.dataSource&&this.dataSourceBuilder.getDefinition(this.dataSource,this.sheetId,this.getters)}}updateRanges(e){return{...this.chartTypeBuilder.updateRanges(this.definition,e,this.sheetId),dataSource:this.dataSource&&this.dataSourceBuilder.adaptRanges(this.dataSource,e)}}duplicateInDuplicatedSheet(t,n){let r=this.dataSource&&this.dataSourceBuilder.duplicateInDuplicatedSheet(this.dataSource,t,n,this.getters),i={...this.chartTypeBuilder.duplicateInDuplicatedSheet(this.definition,t,n,this.getters),dataSource:r};return e.fromDefinition(this.getters,n,i).getDefinition()}copyInSheetId(e){return{...this.chartTypeBuilder.copyInSheetId(this.definition,this.sheetId,e,this.getters),dataSource:this.dataSource}}getContextCreation(){let e=this.getDefinition();return{...this.dataSourceBuilder.getContextCreation(e.dataSource??{type:`none`}),...this.chartTypeBuilder.getContextCreation(e,this.dataSourceBuilder,e.dataSource)}}getDefinitionForExcel(e){let t=this.definition,n=this.dataSourceBuilder.toExcelDataSets(this.dataSource,`dataSetStyles`in t?t.dataSetStyles:{},e);if(n!==void 0)return this.chartTypeBuilder.getDefinitionForExcel(e,t,n)}getData(e,t){let n=this.dataSource;return n?this.dataSourceBuilder.extractData(n,t,e):{dataSetsValues:[],labelValues:[]}}getRuntime(e,t){let n=this.dataSource,r=n?{extractData:()=>this.dataSourceBuilder.extractData(n,t,e),extractHierarchicalData:()=>this.dataSourceBuilder.extractHierarchicalData(n,t,e)}:{extractData:()=>({dataSetsValues:[],labelValues:[]}),extractHierarchicalData:()=>({dataSetsValues:[],labelValues:[]})};return this.chartTypeBuilder.getRuntime(e,this.definition,r,this.sheetId,{onClick:(n,r,i)=>this.dataSourceBuilder.onDataSetClick?.(this.definition.type,t,n,r,i,e),onHover:(e,n,r)=>this.dataSourceBuilder.onDataSetHover?.(this.definition.type,t,e,n,r)})}static deleteInvalidKeys(e){e={...e};let t=new Set(sS.get(e.type).allowedDefinitionKeys);for(let n of Object.keys(e))t.has(n)||delete e[n];return e}};let bO=Object.freeze({value:null}),xO=Object.freeze({value:1}),SO={supportedChartTypes:zh,fromExternalDefinition(e,t,n){let r=_f(n,t,e),i=nc(n,t,e.labelRange);return{...e,dataSets:r,labelRange:i}},fromContextCreation(e){return{type:`range`,dataSets:[],dataSetsHaveTitle:!1,labelRange:e.auxiliaryRange,...e.dataSource}},fromHierarchicalContextCreation(e){if(e.dataSource?.type!==`range`||e.hierarchicalDataSource!==void 0&&e.hierarchicalDataSource.type!==`range`)return{type:`range`,dataSets:[],dataSetsHaveTitle:!1};let t={type:`range`,dataSets:[],dataSetsHaveTitle:e.dataSource?.dataSetsHaveTitle??!1,labelRange:e.dataSource?.dataSets?.[0]?.dataRange};return e.hierarchicalDataSource?.dataSets.length?t=e.hierarchicalDataSource:e.auxiliaryRange&&(t={...t,dataSets:[{dataRange:e.auxiliaryRange,dataSetId:`0`}]}),t},validate:(e,t)=>t.checkValidations(e,Cf,wf),transform(e,t,{adaptRangeString:n}){let r;if(e.labelRange){let{changeType:i,range:a}=n(t,e.labelRange);i!==`REMOVE`&&(r=a)}let i=[];for(let r of e.dataSets){let e={...r},{changeType:a,range:o}=n(t,r.dataRange);a!==`REMOVE`&&(e.dataRange=o,i.push(e))}return{...e,dataSets:i,labelRange:r}},extractData:(e,t,n)=>CO(n,e),extractHierarchicalData(e,t,n){let r=e.dataSets,i=e.labelRange,a=TO(n,r,i),o=EO(n,r),s={labelValues:a,dataSetsValues:o};return Tf(a.length,o[0]?.data.length+(o[0]?.label===void 0?0:1),e.dataSetsHaveTitle||!1)&&a.shift(),s},adaptRanges(e,{applyChange:t}){let n=e.dataSets.map(e=>{let{range:n,changeType:r}=t(e.dataRange);if(r===`REMOVE`)return;let i;if(e.labelCell){let{range:n,changeType:r}=t(e.labelCell);r!==`REMOVE`&&(i=n)}return{...e,dataRange:n,labelCell:i}}).filter(w),r=e.labelRange;if(r){let{range:e,changeType:n}=t(r);r=n===`REMOVE`?void 0:e}let i=n;return{...e,dataSets:i,labelRange:r?.invalidSheetName||r?.invalidXc?void 0:r}},getDefinition(e,t,n){return{labelRange:e.labelRange?n.getRangeString(e.labelRange,t):void 0,type:`range`,dataSets:e.dataSets.map(e=>({dataSetId:e.dataSetId,dataRange:n.getRangeString(e.dataRange,t)})),dataSetsHaveTitle:e.dataSetsHaveTitle}},duplicateInDuplicatedSheet(e,t,n,r){return{...e,labelRange:hf(t,n,e.labelRange),dataSets:e.dataSets.map(e=>({...e,dataRange:tc(t,n,e.dataRange)}))}},getContextCreation:e=>({auxiliaryRange:e.labelRange,dataSource:e}),getHierarchicalContextCreation(e){let t=e.dataSets.at(-1)?.dataRange,n=e.dataSetsHaveTitle;return{auxiliaryRange:t,hierarchicalDataSource:e,dataSource:e.labelRange?{type:`range`,dataSets:[{dataRange:e.labelRange,dataSetId:`0`}],dataSetsHaveTitle:n}:{type:`range`,dataSets:[],dataSetsHaveTitle:n}}},toExcelDataSets(e,t,n){let r=e.dataSets,i=e.labelRange,a=r.map(e=>yf(n,t,e)).filter(e=>e.range!==``&&e.range!==M.InvalidReference),o=r[0]?Xn(r[0].dataRange.zone):void 0;return{dataSets:a,labelRange:bf(n,i,Tf(i?Xn(i.zone):0,o,e.dataSetsHaveTitle))}}};function CO(e,t){let n=t.dataSets,r=t.labelRange,i=TO(e,n,r),a=wO(e,n),o={labelValues:i,dataSetsValues:a},s=a.length?a[0]?.data.length+(a[0]?.label===void 0?0:1):0;return Tf(i.length,s,t.dataSetsHaveTitle||!1)&&i.shift(),o}function wO(e,t){let n=[];for(let[r,i]of Object.entries(t)){let t=`${Py.Series} ${parseInt(r)+1}`,a=e.isColHidden(i.dataRange.sheetId,i.dataRange.zone.left);if(i.labelCell){let{sheetId:n,zone:r}=i.labelCell,a=e.getEvaluatedCell({sheetId:n,col:r.left,row:r.top});a&&(t=a.formattedValue)}let o=i.dataRange?DO(e,i):[];o.every(e=>!e.value||Gu(e))&&o.filter(Gu).length>1?o=o.map(e=>e.value&&!Ku(e)?xO:bO):o.every(e=>!U(e))&&(a=!0),n.push({data:o,label:t,hidden:a,dataSetId:i.dataSetId})}return n}function TO(e,t,n){if(n){let{left:t}=n.zone;if(!n.invalidXc&&!n.invalidSheetName&&!e.isColHidden(n.sheetId,t))return e.getVisibleRangeValues(n)}if(t[0]){let n=DO(e,t[0]).length;return Array.from({length:n},()=>({value:``}))}return[]}function EO(e,t){t=t.filter(t=>!e.isColHidden(t.dataRange.sheetId,t.dataRange.zone.left));let n=t.map(e=>({data:[],label:``,dataSetId:e.dataSetId})),r=e.getLocale(),i=t.map(t=>DO(e,t)).map(e=>e.map(({value:e,format:t})=>e===null?bO:{value:H(e,{format:t,locale:r})}));if(!i.length)return n;let a=Math.min(...i.map(e=>e.length)),o=[],s=t.length-1;for(let e=0;e<a;e++)for(let t=0;t<i.length;t++){let r=i[t][e];(r===void 0||r.value===null)&&t!==s&&(r=o[t]),r?.value!==o[t]?.value&&(o=o.slice(0,t),o[t]=r),n[t].data.push(r??bO)}return n.filter(e=>e.data.some(e=>e.value!==null))}function DO(e,t){if(t.dataRange){let n=t.labelCell?[t.labelCell.zone]:[],r=cn([t.dataRange.zone],n)[0];if(r===void 0)return[];let i=e.getRangeFromZone(t.dataRange.sheetId,r);return e.getVisibleRangeValues(i).map(e=>e.value===``?bO:e)}return[]}oS.add(`range`,SO),oS.add(`none`,{supportedChartTypes:[],fromExternalDefinition:()=>({type:`none`}),fromContextCreation:()=>({type:`none`}),fromHierarchicalContextCreation:()=>({type:`none`}),validate:()=>`Success`,transform:()=>({type:`none`}),extractData:()=>({dataSetsValues:[],labelValues:[]}),extractHierarchicalData:()=>({dataSetsValues:[],labelValues:[]}),adaptRanges:e=>e,getDefinition:e=>e,duplicateInDuplicatedSheet:e=>e,getContextCreation:()=>({}),getHierarchicalContextCreation:()=>({}),toExcelDataSets:()=>({dataSets:[],labelRange:void 0})});let OO=[`year`,`quarter_number`,`month_number`,`iso_week_number`,`day_of_month`,`day_of_week`,`hour_number`,`minute_number`,`second_number`];var kO=class extends tO{static template=`o-spreadsheet-CalendarChartConfigPanel`;static components={...tO.components,Select:Ty};groupByChoices=OO.map(e=>({value:e,label:bg[e]}));getGroupByOptions(){let e=this.env.model.getters.getFigureSheetId(this.env.model.getters.getFigureIdFromChartId(this.props.chartId)),t=yO.fromStrDefinition(this.env.model.getters,e,this.props.definition).getRangeDefinition(),n=Qg(t,CO(this.env.model.getters,t.dataSource),this.env.model.getters).labels.filter(e=>na(e,V));if(n.length===0)return[];let r=n.map(e=>z(e,this.env.model.getters.getLocale())),i=new Set,a=new Set,o=new Set,s=new Set,c=new Set,l=new Set;for(let e of r)i.add(e.getFullYear()),a.add(e.getMonth()),o.add(e.getDate()),s.add(e.getHours()),c.add(e.getMinutes()),l.add(e.getSeconds());return this.groupByChoices.filter(e=>{switch(e.value){case`year`:return i.size>1;case`quarter_number`:case`month_number`:return a.size>1;case`iso_week_number`:case`day_of_month`:case`day_of_week`:return o.size>1;case`hour_number`:return s.size>1;case`minute_number`:return c.size>1;case`second_number`:return l.size>1;default:return!1}})}getGroupByType(e){return(e===`horizontal`?this.props.definition.horizontalGroupBy:this.props.definition.verticalGroupBy)||`year`}updateGroupBy(e,t){this.props.updateChart(this.props.chartId,{[e===`horizontal`?`horizontalGroupBy`:`verticalGroupBy`]:t})}},AO=class extends t.Component{static template=`o-spreadsheet-ColorScalePicker`;static components={Section:Z,RoundColorPicker:ST,Popover:by};static props={definition:Object,onUpdateColorScale:Function};colorScales=mi.map(e=>({value:e,label:Py.ColorScales[e],className:`${e}-color-scale`}));state=(0,t.useState)({popoverProps:void 0,popoverStyle:``});popoverRef=(0,t.useRef)(`popoverRef`);setup(){(0,t.useExternalListener)(window,`click`,this.closePopover)}get currentColorScale(){return this.props.definition.colorScale||Bh(`oranges`)}get currentColorScaleStyle(){let e=this.currentColorScale,t=e.minColor||`#fff`,n=e.midColor,r=e.maxColor||`#000`;return n?`background: linear-gradient(90deg, ${t}, ${n}, ${r});`:`background: linear-gradient(90deg, ${t}, ${r});`}colorScalePreviewStyle(e){return`background: linear-gradient(90deg, ${pi[e].join(`,`)});`}get currentColorScaleLabel(){return Py.ColorScales[this.selectedColorScale]}onColorScaleChange(e){e===`custom`?this.props.onUpdateColorScale(_e):this.props.onUpdateColorScale(Bh(e)),this.closePopover()}onPointerDown(e){if(this.state.popoverProps){this.closePopover();return}let{bottom:t,right:n,width:r}=e.currentTarget.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:n,y:t,width:0,height:0},positioning:`top-right`,verticalOffset:0},this.state.popoverStyle=W({width:`${r}px`})}closePopover(){this.state.popoverProps=void 0}get selectedColorScale(){if(!this.props.definition.colorScale)return`oranges`;let{minColor:e,midColor:t,maxColor:n}=this.props.definition.colorScale||{};for(let[r,i]of Object.entries(pi))if(i[0]===e&&i[2]===n&&i[1]===t)return r;return`custom`}getCustomColorScaleColor(e){return this.props.definition.colorScale?.[e]??``}setCustomColorScaleColor(e,t){!t&&e!==`midColor`&&(t=`#fff`);let n=this.currentColorScale;n&&this.props.onUpdateColorScale({...n,[e]:t})}},jO=class extends t.Component{static template=`o-spreadsheet-CalendarChartDesignPanel`;static components={GeneralDesignEditor:lO,SidePanelCollapsible:ww,Section:Z,AxisDesignEditor:sO,ChartShowValues:mO,ColorScalePicker:AO,RoundColorPicker:ST,Select:Ty};static props=YD;get axesList(){return[{id:`x`,name:j(`Horizontal axis`)},{id:`y`,name:j(`Vertical axis`)}]}onColormapChange(e){this.props.updateChart(this.props.chartId,{colorScale:e})}updateMissingValueColor(e){this.props.updateChart(this.props.chartId,{missingValueColor:e})}get selectedMissingValueColor(){return this.props.definition.missingValueColor}updateLegendPosition(e){this.props.updateChart(this.props.chartId,{legendPosition:e})}get legendValues(){return[{value:`none`,label:j(`None`)},{value:`right`,label:j(`Right`)},{value:`left`,label:j(`Left`)}]}},MO=class extends t.Component{static template=`o-spreadsheet-ChartShowDataMarkers`;static components={Checkbox:IT};static props=YD},NO=class extends gO{static template=`o-spreadsheet-ComboChartDesignPanel`;static components={...gO.components,ChartShowDataMarkers:MO,RadioSelection:cO};seriesTypeChoices=[{value:`bar`,label:j(`Bar`)},{value:`line`,label:j(`Line`)}];updateDataSeriesType(e,t){let n={...this.props.definition.dataSetStyles};n[e]={...n[e],type:t},this.props.updateChart(this.props.chartId,{dataSetStyles:n})}getDataSeriesType(e){return this.props.definition.dataSetStyles?.[e]?.type||(this.env.model.getters.getChartRuntime(this.props.chartId).customizableSeries.findIndex(t=>t.dataSetId===e)===0?`bar`:`line`)}},PO=class extends tO{getLabelRangeOptions(){let e=this.props.definition;return[this.getAggregateLabelRangeOption(),{name:`cumulative`,label:this.chartTerms.CumulativeData,value:e.cumulative??!1,onChange:this.onUpdateCumulative.bind(this)}]}onUpdateCumulative(e){this.props.updateChart(this.props.chartId,{cumulative:e})}},FO=class extends t.Component{static template=`o-spreadsheet-FunnelChartDesignPanel`;static components={ChartShowValues:mO,GeneralDesignEditor:lO,SidePanelCollapsible:ww,RoundColorPicker:ST,Section:Z,ChartHumanizeNumbers:uO};static props={chartId:String,definition:Object,updateChart:Function,canUpdateChart:Function};getFunnelColorItems(){let e=this.env.model.getters.getChartRuntime(this.props.chartId).chartJsConfig.data.labels||[],t=Cp(e,this.props.definition.funnelColors);return e.map((e,n)=>({label:e||j(`Value %s`,n+1),color:t[n]}))}updateFunnelItemColor(e,t){let n=Lt(this.props.definition.funnelColors||[],t,e);this.props.updateChart(this.props.chartId,{funnelColors:n})}},IO=class extends t.Component{static template=`o-spreadsheet-GaugeChartConfigPanel`;static components={ChartErrorSection:eO,ChartDataSeries:XD};static props=YD;state=(0,t.useState)({dataRangeDispatchResult:void 0});dataRange=this.props.definition.dataRange;get configurationErrorMessages(){return[...this.state.dataRangeDispatchResult?.reasons||[]].filter(e=>e!==`NoChanges`).map(e=>Py.Errors[e]||Py.Errors.Unexpected)}get isDataRangeInvalid(){return!!this.state.dataRangeDispatchResult?.isCancelledBecause(`InvalidGaugeDataRange`)}onDataRangeChanged(e){this.dataRange=e[0],this.state.dataRangeDispatchResult=this.props.canUpdateChart(this.props.chartId,{dataRange:this.dataRange})}updateDataRange(){this.state.dataRangeDispatchResult=this.props.updateChart(this.props.chartId,{dataRange:this.dataRange})}getDataRange(){return{dataRange:this.dataRange||``}}},LO=class extends t.Component{static template=`o-spreadsheet-GaugeChartDesignPanel`;static components={SidePanelCollapsible:ww,Section:Z,RoundColorPicker:ST,GeneralDesignEditor:lO,ChartErrorSection:eO,StandaloneComposer:pT,ChartHumanizeNumbers:uO,Select:Ty};static props=YD;state;setup(){this.state=(0,t.useState)({sectionRuleCancelledReasons:new Set(this.checkSectionRuleFormulasAreValid(this.props.definition.sectionRule)),sectionRule:x(this.props.definition.sectionRule)})}get designErrorMessages(){return[...this.state.sectionRuleCancelledReasons||[]].filter(e=>e!==`NoChanges`).map(e=>Py.Errors[e]||Py.Errors.Unexpected)}get isRangeMinInvalid(){return!!(this.state.sectionRuleCancelledReasons?.has(`EmptyGaugeRangeMin`)||this.state.sectionRuleCancelledReasons?.has(`GaugeRangeMinNaN`))}get isRangeMaxInvalid(){return!!(this.state.sectionRuleCancelledReasons?.has(`EmptyGaugeRangeMax`)||this.state.sectionRuleCancelledReasons?.has(`GaugeRangeMaxNaN`))}get isLowerInflectionPointInvalid(){return!!this.state.sectionRuleCancelledReasons?.has(`GaugeLowerInflectionPointNaN`)}get isUpperInflectionPointInvalid(){return!!this.state.sectionRuleCancelledReasons?.has(`GaugeUpperInflectionPointNaN`)}updateSectionColor(e,t){let n=x(this.state.sectionRule);n.colors[e]=t,this.updateSectionRule(n)}updateSectionRuleOperator(e,t){this.state.sectionRule={...this.state.sectionRule,[e]:{...this.state.sectionRule[e],operator:t}},this.updateSectionRule(this.state.sectionRule)}updateSectionRulePointType(e,t){this.state.sectionRule={...this.state.sectionRule,[e]:{...this.state.sectionRule[e],type:t}},this.updateSectionRule(this.state.sectionRule)}updateSectionRule(e){this.state.sectionRuleCancelledReasons=new Set(this.checkSectionRuleFormulasAreValid(this.state.sectionRule));let t=this.props.updateChart(this.props.chartId,{sectionRule:e});if(t.isSuccessful)this.state.sectionRule=x(e);else for(let e of t.reasons)this.state.sectionRuleCancelledReasons.add(e)}onConfirmGaugeRange(e,t){this.state.sectionRule={...this.state.sectionRule,[e]:t},this.updateSectionRule(this.state.sectionRule)}getGaugeInflectionComposerProps(e){let t=e===`lowerColor`?`lowerInflectionPoint`:`upperInflectionPoint`,n=this.state.sectionRule[t];return{onConfirm:e=>{this.state.sectionRule={...this.state.sectionRule,[t]:{...n,value:e}},this.updateSectionRule(this.state.sectionRule)},composerContent:n.value,invalid:e===`lowerColor`?this.isLowerInflectionPointInvalid:this.isUpperInflectionPointInvalid,defaultRangeSheetId:this.sheetId,class:t,placeholder:j(`Value`),title:j(`Value or formula`)}}checkSectionRuleFormulasAreValid(e){let t=new Set;return this.valueIsValidNumber(e.rangeMin)||t.add(`GaugeRangeMinNaN`),this.valueIsValidNumber(e.rangeMax)||t.add(`GaugeRangeMaxNaN`),this.valueIsValidNumber(e.lowerInflectionPoint.value)||t.add(`GaugeLowerInflectionPointNaN`),this.valueIsValidNumber(e.upperInflectionPoint.value)||t.add(`GaugeUpperInflectionPointNaN`),t}valueIsValidNumber(e){let t=this.env.model.getters.getLocale();if(!e.startsWith(`=`))return Ga(e,t)!==void 0;let n=this.env.model.getters.evaluateFormula(this.sheetId,e);return Sh(n)?!1:Ga(bh(n),t)!==void 0}get sheetId(){let e=this.env.model.getters.getChart(this.props.chartId);if(!e)throw Error(`Chart not found with id `+this.props.chartId);return e.sheetId}get inflectionPointOperators(){return[{value:`<`,label:`<`},{value:`<=`,label:`<=`}]}get inflectionPointTypes(){return[{value:`number`,label:j(`Number`)},{value:`percentage`,label:j(`Percentage`)}]}},RO=class extends t.Component{static template=`o-spreadsheet-GeoChartRegionSelectSection`;static components={Section:Z,Select:Ty};static props={chartId:String,definition:Object,updateChart:Function};updateSelectedRegion(e){this.props.updateChart(this.props.chartId,{region:e})}get availableRegions(){return this.env.model.getters.getGeoChartAvailableRegions()}get selectedRegion(){return this.props.definition.region||this.availableRegions[0]?.id}get regionOptions(){return this.availableRegions.map(e=>({value:e.id,label:e.label}))}},zO=class extends tO{static template=`o-spreadsheet-GeoChartConfigPanel`;static components={...tO.components,GeoChartRegionSelectSection:RO};getLabelRangeOptions(){return[]}},BO=class extends hO{static template=`o-spreadsheet-GeoChartDesignPanel`;static components={...hO.components,RoundColorPicker:ST,ColorScalePicker:AO,Select:Ty};updateColorScale(e){this.props.updateChart(this.props.chartId,{colorScale:e})}updateMissingValueColor(e){this.props.updateChart(this.props.chartId,{missingValueColor:e})}updateLegendPosition(e){this.props.updateChart(this.props.chartId,{legendPosition:e})}get selectedMissingValueColor(){return this.props.definition.missingValueColor||`#ffffff`}get legendValues(){return[{value:`none`,label:j(`None`)},{value:`top`,label:j(`Top left`)},{value:`right`,label:j(`Top right`)},{value:`bottom`,label:j(`Bottom right`)},{value:`left`,label:j(`Bottom left`)}]}},VO=class extends tO{static template=`o-spreadsheet-HierarchicalChartConfigPanel`;static components={...tO.components}},HO=class extends tO{static template=`o-spreadsheet-LineConfigPanel`;get canTreatLabelsAsText(){let e=this.env.model.getters.getChart(this.props.chartId),t=e?.getRangeDefinition();return e?.sheetId&&t?.type===`line`?g_(e.getData(this.env.model.getters,this.props.chartId)):!1}get stackedLabel(){return this.props.definition.fillArea?this.chartTerms.StackedAreaChart:this.chartTerms.StackedLineChart}getLabelRangeOptions(){let e=[this.getAggregateLabelRangeOption()];return this.canTreatLabelsAsText&&e.push({name:`labelsAsText`,value:this.props.definition.labelsAsText,label:this.chartTerms.TreatLabelsAsText,onChange:this.onUpdateLabelsAsText.bind(this)}),e}onUpdateLabelsAsText(e){let t;`axesDesign`in this.props.definition&&(t={...this.props.definition.axesDesign,x:{...this.props.definition.axesDesign?.x,min:void 0,max:void 0}}),this.props.updateChart(this.props.chartId,{labelsAsText:e,axesDesign:t})}onUpdateStacked(e){this.props.updateChart(this.props.chartId,{stacked:e})}onUpdateCumulative(e){this.props.updateChart(this.props.chartId,{cumulative:e})}},UO=class extends gO{static template=`o-spreadsheet-LineChartDesignPanel`;static components={...gO.components,ChartShowDataMarkers:MO}},WO=class extends t.Component{static template=`o-spreadsheet.PieHoleSize`;static components={Section:Z,NumberInput:rO};static props={onValueChange:Function,value:Number};onChange(e){isNaN(Number(e))||this.props.onValueChange(S(Number(e),0,95))}},GO=class extends t.Component{static template=`o-spreadsheet-PieChartDesignPanel`;static components={GeneralDesignEditor:lO,Section:Z,ChartLegend:dO,ChartShowValues:mO,PieHoleSize:WO,Checkbox:IT,ChartHumanizeNumbers:uO,SidePanelCollapsible:ww,RoundColorPicker:ST,Select:Ty};static props=YD;state=(0,t.useState)({index:0});get runtime(){return this.env.model.getters.getChartRuntime(this.props.chartId)}get isLegendDisabled(){let e=this.runtime.chartJsConfig.data.labels;return!e||e.every(e=>e===``)}get labels(){return this.runtime.chartJsConfig.data.labels?.map((e,t)=>e===``?`Slice ${t+1}`:e)||[]}onPieHoleSizeChange(e){this.props.updateChart(this.props.chartId,{...this.props.definition,pieHolePercentage:e})}get defaultHoleSize(){return 50}updateEditedValues(e){this.state.index=parseInt(e)}updateSliceColor(e){let t=x(this.props.definition.slicesColors);t||=Array(this.labels?.length).fill(``),t[this.state.index]=e,this.props.updateChart(this.props.chartId,{...this.props.definition,slicesColors:t})}get sliceColor(){let e=this.props.definition.slicesColors;return e?.[this.state.index]?e?.[this.state.index]:this.runtime.chartJsConfig.data.datasets[0]?.backgroundColor?.[this.state.index]}get pieSliceOptions(){return this.labels.map((e,t)=>({value:t.toString(),label:e}))}},KO=class extends t.Component{static template=`o-spreadsheet-RadarChartDesignPanel`;static components={GeneralDesignEditor:lO,SeriesDesignEditor:fO,Section:Z,ChartLegend:dO,ChartShowValues:mO,ChartShowDataMarkers:MO,Checkbox:IT,ChartHumanizeNumbers:uO};static props=YD},qO=class extends tO{static template=`o-spreadsheet-ScatterConfigPanel`;get canTreatLabelsAsText(){let e=this.env.model.getters.getChart(this.props.chartId),t=e?.getRangeDefinition();return e?.sheetId&&t?.type===`scatter`?g_(e.getData(this.env.model.getters,this.props.chartId)):!1}onUpdateLabelsAsText(e){let t;`axesDesign`in this.props.definition&&(t={...this.props.definition.axesDesign,x:{...this.props.definition.axesDesign?.x,min:void 0,max:void 0}}),this.props.updateChart(this.props.chartId,{labelsAsText:e,axesDesign:t})}getLabelRangeOptions(){let e=[this.getAggregateLabelRangeOption()];return this.canTreatLabelsAsText&&e.push({name:`labelsAsText`,value:this.props.definition.labelsAsText,label:this.chartTerms.TreatLabelsAsText,onChange:this.onUpdateLabelsAsText.bind(this)}),e}},JO=class extends t.Component{static template=`o-spreadsheet-ScorecardChartConfigPanel`;static components={SelectionInput:jT,ChartErrorSection:eO,Section:Z,Select:Ty};static props=YD;state=(0,t.useState)({keyValueDispatchResult:void 0,baselineDispatchResult:void 0});keyValue=this.props.definition.keyValue;baseline=this.props.definition.baseline;get errorMessages(){return[...this.state.keyValueDispatchResult?.reasons||[],...this.state.baselineDispatchResult?.reasons||[]].filter(e=>e!==`NoChanges`).map(e=>Py.Errors[e]||Py.Errors.Unexpected)}get isKeyValueInvalid(){return!!this.state.keyValueDispatchResult?.isCancelledBecause(`InvalidScorecardKeyValue`)}get isBaselineInvalid(){return!!this.state.baselineDispatchResult?.isCancelledBecause(`InvalidScorecardBaseline`)}onKeyValueRangeChanged(e){this.keyValue=e[0],this.state.keyValueDispatchResult=this.props.canUpdateChart(this.props.chartId,{keyValue:this.keyValue})}updateKeyValueRange(){this.state.keyValueDispatchResult=this.props.updateChart(this.props.chartId,{keyValue:this.keyValue})}getKeyValueRange(){return this.keyValue||``}onBaselineRangeChanged(e){this.baseline=e[0],this.state.baselineDispatchResult=this.props.canUpdateChart(this.props.chartId,{baseline:this.baseline})}updateBaselineRange(){this.state.baselineDispatchResult=this.props.updateChart(this.props.chartId,{baseline:this.baseline})}getBaselineRange(){return this.baseline||``}updateBaselineMode(e){this.props.updateChart(this.props.chartId,{baselineMode:e})}get baselineModeOptions(){return[{value:`text`,label:j(`Absolute value`)},{value:`difference`,label:j(`Value change from key value`)},{value:`percentage`,label:j(`Percentage change from key value`)},{value:`progress`,label:j(`Progress bar`)}]}},YO=class extends t.Component{static template=`o-spreadsheet-ScorecardChartDesignPanel`;static components={GeneralDesignEditor:lO,RoundColorPicker:ST,SidePanelCollapsible:ww,Section:Z,Checkbox:IT,ChartTitle:oO,ChartHumanizeNumbers:uO};static props=YD;get colorsSectionTitle(){return this.props.definition.baselineMode===`progress`?j(`Progress bar colors`):j(`Baseline colors`)}get defaultScorecardTitleFontSize(){return 14}translate(e){return this.env.model.getters.dynamicTranslate(e)}setColor(e,t){switch(t){case`backgroundColor`:this.props.updateChart(this.props.chartId,{background:e});break;case`baselineColorDown`:this.props.updateChart(this.props.chartId,{baselineColorDown:e});break;case`baselineColorUp`:this.props.updateChart(this.props.chartId,{baselineColorUp:e});break}}get keyStyle(){return{align:`center`,fontSize:32,...this.props.definition.keyDescr}}get baselineStyle(){return{align:`center`,fontSize:16,...this.props.definition.baselineDescr}}setKeyText(e){this.props.updateChart(this.props.chartId,{keyDescr:{...this.props.definition.keyDescr,text:e}})}updateKeyStyle(e){let t={...this.keyStyle,...e};this.props.updateChart(this.props.chartId,{keyDescr:t})}setBaselineText(e){this.props.updateChart(this.props.chartId,{baselineDescr:{...this.props.definition.baselineDescr,text:e}})}updateBaselineStyle(e){let t={...this.baselineStyle,...e};this.props.updateChart(this.props.chartId,{baselineDescr:t})}},XO=class extends t.Component{static template=`o-spreadsheet-SunburstChartDesignPanel`;static components={GeneralDesignEditor:lO,Section:Z,SidePanelCollapsible:ww,ChartShowValues:mO,Checkbox:IT,TextStyler:GD,RoundColorPicker:ST,ChartLegend:dO,PieHoleSize:WO,ChartHumanizeNumbers:uO};static props=YD;defaults=G_;get showValues(){return this.props.definition.showValues??G_.showValues}get showLabels(){return this.props.definition.showLabels??G_.showLabels}get groupColors(){let e=this.props.chartId;return this.env.model.getters.getChartRuntime(e).chartJsConfig.data.datasets[0]?.groupColors||[]}onGroupColorChanged(e,t){let n=x(this.props.definition.groupColors)??[];n[e]=t,this.props.updateChart(this.props.chartId,{groupColors:n})}onPieHoleSizeChange(e){this.props.updateChart(this.props.chartId,{...this.props.definition,pieHolePercentage:e})}},ZO=class extends t.Component{static template=`o-spreadsheet-TreeMapCategoryColors`;static components={Checkbox:IT,RoundColorPicker:ST};static props={chartId:String,definition:Object,onColorChanged:Function};get coloringOptions(){let e=this.props.definition.coloringOptions??Bf.coloringOptions;if(e.type!==`categoryColor`)throw Error(`Coloring options is not solid color`);return e}getTreeGroupAndColors(){return this.env.model.getters.getChartRuntime(this.props.chartId).chartJsConfig.data.datasets[0]?.groupColors||[]}onGroupColorChanged(e,t){let n=x(this.coloringOptions);n.colors[e]=t||void 0,this.props.onColorChanged(n)}useValueBasedGradient(e){if(this.coloringOptions.type!==`categoryColor`)throw Error(`Coloring options is not solid color`);this.props.onColorChanged({...this.coloringOptions,useValueBasedGradient:e})}},QO=class extends t.Component{static template=`o-spreadsheet-TreeMapColorScale`;static components={RoundColorPicker:ST};static props={chartId:String,definition:Object,onColorChanged:Function};get coloringOptions(){let e=this.props.definition.coloringOptions??Bf.coloringOptions;if(e.type!==`colorScale`)throw Error(`Coloring options is not a color scale`);return e}setColorScaleColor(e,t){this.props.onColorChanged({...this.coloringOptions,[e]:t})}};let $O={type:`colorScale`,minColor:`#FFF5EB`,midColor:`#FD8D3C`,maxColor:`#7F2704`},ek={type:`categoryColor`,colors:[],useValueBasedGradient:!0};var tk=class extends t.Component{static template=`o-spreadsheet-TreeMapChartDesignPanel`;static components={GeneralDesignEditor:lO,Section:Z,SidePanelCollapsible:ww,ChartShowValues:mO,Checkbox:IT,TextStyler:GD,RoundColorPicker:ST,BadgeSelection:aO,TreeMapCategoryColors:ZO,TreeMapColorScale:QO,ChartHumanizeNumbers:uO};static props=YD;savedColors={categoryColors:ek,colorScale:$O};defaults=Bf;get showHeaders(){return this.props.definition.showHeaders??Bf.showHeaders}get showValues(){return this.props.definition.showValues??Bf.showValues}get showLabels(){return this.props.definition.showLabels??Bf.showLabels}get coloringOptions(){return this.props.definition.coloringOptions??Bf.coloringOptions}changeColoringOption(e){let t=e===`categoryColor`?this.savedColors.categoryColors:this.savedColors.colorScale;this.props.updateChart(this.props.chartId,{coloringOptions:t})}onCategoryColorChange(e){this.savedColors.categoryColors=e,this.props.updateChart(this.props.chartId,{coloringOptions:e})}onColorScaleChange(e){this.savedColors.colorScale=e,this.props.updateChart(this.props.chartId,{coloringOptions:e})}get coloringOptionChoices(){return[{label:j(`Category color`),value:`categoryColor`},{label:j(`Color scale`),value:`colorScale`}]}},nk=class extends t.Component{static template=`o-spreadsheet-WaterfallChartDesignPanel`;static components={GeneralDesignEditor:lO,ChartShowValues:mO,Checkbox:IT,SidePanelCollapsible:ww,Section:Z,RoundColorPicker:ST,AxisDesignEditor:sO,RadioSelection:cO,ChartLegend:dO,ChartHumanizeNumbers:uO};static props=YD;axisChoices=Af;onUpdateShowSubTotals(e){this.props.updateChart(this.props.chartId,{showSubTotals:e})}onUpdateShowConnectorLines(e){this.props.updateChart(this.props.chartId,{showConnectorLines:e})}onUpdateFirstValueAsSubtotal(e){this.props.updateChart(this.props.chartId,{firstValueAsSubtotal:e})}updateColor(e,t){this.props.updateChart(this.props.chartId,{[e]:t})}get axesList(){return[{id:`x`,name:j(`Horizontal axis`)},{id:`y`,name:j(`Vertical axis`)}]}get positiveValuesColor(){return this.props.definition.positiveValuesColor||`#4EA7F2`}get negativeValuesColor(){return this.props.definition.negativeValuesColor||`#EA6175`}get subTotalValuesColor(){return this.props.definition.subTotalValuesColor||`#AAAAAA`}updateVerticalAxisPosition(e){this.props.updateChart(this.props.chartId,{verticalAxisPosition:e})}onToggleZoom(e){this.props.updateChart(this.props.chartId,{zoomable:e})}};let rk=new A;JD.add(`range`,vO),rk.add(`line`,{configuration:HO,design:UO}).add(`scatter`,{configuration:qO,design:hO}).add(`bar`,{configuration:nO,design:_O}).add(`combo`,{configuration:tO,design:NO}).add(`pie`,{configuration:tO,design:GO}).add(`gauge`,{configuration:IO,design:LO}).add(`scorecard`,{configuration:JO,design:YO}).add(`waterfall`,{configuration:tO,design:nk}).add(`pyramid`,{configuration:tO,design:hO}).add(`radar`,{configuration:tO,design:KO}).add(`sunburst`,{configuration:VO,design:XO}).add(`geo`,{configuration:zO,design:BO}).add(`funnel`,{configuration:PO,design:FO}).add(`treemap`,{configuration:VO,design:tk}).add(`calendar`,{configuration:kO,design:jO});let ik={line:j(`Line`),column:j(`Column`),bar:j(`Bar`),area:j(`Area`),pie:j(`Pie`),hierarchical:j(`Hierarchical`),misc:j(`Miscellaneous`)};var ak=class extends t.Component{static template=`o-spreadsheet-ChartTypePicker`;static components={Section:Z,Popover:by};static props={chartId:String,chartPanelStore:Object};categories=ik;chartTypeByCategories={};popoverRef=(0,t.useRef)(`popoverRef`);selectRef=(0,t.useRef)(`selectRef`);state=(0,t.useState)({popoverProps:void 0,popoverStyle:``});setup(){(0,t.useExternalListener)(window,`pointerdown`,this.onExternalClick,{capture:!0});let e=this.env.model.getters.getChartDefinition(this.props.chartId),n=this.getSupportedChartTypes(e);for(let e of Hv.getAll())n.has(e.chartType)&&(this.chartTypeByCategories[e.category]?this.chartTypeByCategories[e.category].push(e):this.chartTypeByCategories[e.category]=[e])}getSupportedChartTypes(e){let t;if(e.dataSource){let n=oS.get(e.dataSource.type);t=new Set(n.supportedChartTypes)}else if(!e.dataSource&&(e.type===`scorecard`||e.type===`gauge`))t=new Set(zh);else throw Error(`Missing chart data source for a chart type that requires it`);return t}onExternalClick(e){fm(this.popoverRef.el?.parentElement,e)||fm(this.selectRef.el,e)||this.closePopover()}onTypeChange(e){this.props.chartPanelStore.changeChartType(this.props.chartId,e),this.closePopover()}getChartDefinition(e){return this.env.model.getters.getChartDefinition(e)}getSelectedChartSubtypeProperties(){let e=this.getChartDefinition(this.props.chartId);return Hv.getAll().find(t=>t.matcher?.(e)||!1)||Hv.get(e.type)}onPointerDown(e){if(this.state.popoverProps){this.closePopover();return}let{bottom:t,right:n,width:r}=e.currentTarget.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:n,y:t,width:0,height:0},positioning:`top-right`,verticalOffset:0},this.state.popoverStyle=W({width:`${r}px`})}closePopover(){this.state.popoverProps=void 0}},ok=class extends wr{mutators=[`activatePanel`,`changeChartType`];panel=`configuration`;creationContexts={};activatePanel(e){this.panel=e}changeChartType(e,t){let n=this.getters.getContextCreationChart(e),r=this.creationContexts[e]||{},i=r.dataSetStyles??n?.dataSetStyles,a={...r.dataSource,...n?.dataSource},o=n?.dataSource,s=r.dataSource;if((!o||o?.type===`range`)&&(!s||s?.type===`range`)){let e=o?.dataSets,t=s?.dataSets,c=o?.dataSets;if(c&&t&&this.dataSetsStartWithSameRanges(c,t,n?.dataSetStyles,r.dataSetStyles)){let a=this.mergeDataSetStyles(c,t,n?.dataSetStyles,r.dataSetStyles);e=a.dataSets,i=a.dataSetStyles}a={type:`range`,dataSetsHaveTitle:!1,...r.dataSource,...n?.dataSource,dataSets:e??[]}}this.creationContexts[e]={...r,...n,dataSource:a,dataSetStyles:i};let c=this.getters.getFigureIdFromChartId(e),l=this.getters.getFigureSheetId(c);if(!l)return;let u=this.getDefinitionFromContextCreation(e,t);this.model.dispatch(`UPDATE_CHART`,{definition:u,chartId:e,figureId:c,sheetId:l})}dataSetsStartWithSameRanges(e,t,n,r){return e.every((e,i)=>{let a=t[i];return T(e.dataRange,a.dataRange)&&T(n?.[e.dataSetId],r?.[a.dataSetId])})}mergeDataSetStyles(e,t,n,r){let i=[],a={};for(let o=0;o<t.length;o++){let s=e[o]??t[o],c=n?.[s.dataSetId]??r?.[s.dataSetId],l=o.toString();i.push({...s,dataSetId:l}),c&&(a[l]=c)}return{dataSets:i,dataSetStyles:a}}getDefinitionFromContextCreation(e,t){let n=Hv.get(t),r=this.creationContexts[e],i=sS.get(n.chartType),a=oS.get(r.dataSource?.type??`range`),o={...i.getDefinitionFromContextCreation(r,a),...n.subtypeDefinition};return yO.deleteInvalidKeys(o)}},sk=class extends t.Component{static template=`o-spreadsheet-ChartPanel`;static components={Section:Z,ChartTypePicker:ak};static props={onCloseSidePanel:Function,chartId:String};store;get chartId(){return this.props.chartId}setup(){this.store=hr(ok)}switchPanel(e){this.store.activatePanel(e)}updateChart(e,t){let n=this.env.model.getters.getFigureIdFromChartId(e);if(e!==this.chartId)return;let r={...this.getChartDefinition(this.chartId),...t};return this.env.model.dispatch(`UPDATE_CHART`,{definition:r,chartId:e,figureId:n,sheetId:this.env.model.getters.getFigureSheetId(n)})}canUpdateChart(e,t){let n=this.env.model.getters.getFigureIdFromChartId(e);if(e!==this.chartId||!this.env.model.getters.isChartDefined(e))return;let r={...this.getChartDefinition(this.chartId),...t};return this.env.model.canDispatch(`UPDATE_CHART`,{definition:r,chartId:e,figureId:n,sheetId:this.env.model.getters.getFigureSheetId(n)})}onTypeChange(e){this.chartId&&this.store.changeChartType(this.chartId,e)}get chartPanel(){if(!this.chartId)throw Error(`Chart not defined.`);let e=this.env.model.getters.getChartType(this.chartId);if(!e)throw Error(`Chart not defined.`);let t=rk.get(e);if(!t)throw Error(`Component is not defined for type ${e}`);return t}getChartDefinition(e){return this.env.model.getters.getChartDefinition(e)}};function ck(e,...n){(0,t.useEffect)(e=>(e?.addEventListener(...n),()=>e?.removeEventListener(...n)),()=>[e.el])}function lk(e){let n=(0,t.useState)({hovered:!1});ck(e,`mouseenter`,()=>n.hovered=!0),ck(e,`mouseleave`,()=>n.hovered=!1);let r=new ResizeObserver(()=>{n.hovered=!1});return(0,t.useEffect)(()=>(r.observe(e.el),()=>{r.disconnect()}),()=>[e.el]),n}function uk(e,t){let n=lk(e);dk({get highlights(){return n.hovered?t.highlights:[]}})}function dk(e){let n=mr(),r=hr(cT);(0,t.onMounted)(()=>{r.register(e)});let i=e.highlights;(0,t.useEffect)(e=>{T(e,i)||(i=e,n.trigger(`store-updated`))},()=>[e.highlights])}function fk(e,t,n){let r={},i=Pt(e=>{let n=e.split(`,`);return t.filter(e=>n.includes(e.type))});for(let t of e){let e,a=i(t.types.sort().join(`,`));a.length&&(e=xt(()=>t.compute(a,n))),r[t.name]={value:e,format:t.format}}return r}let pk=[{name:j(`Total rows`),types:Object.values(Gc),compute:(e,t)=>e.length,format:`0`},{name:j(`Unique values`),types:[`number`,`text`,`boolean`,`error`],compute:(e,t)=>{let n=new Set;for(let t of e)n.add(t.value);return n.size},format:`0`},{name:j(`Sum`),types:[`number`],compute:(e,t)=>Xh([[e]],t)},{name:j(`Average`),types:[`number`],compute:(e,t)=>wh([[e]],t)},{name:j(`Median`),types:[`number`],compute:(e,t)=>Th([[e]],t)??``},{name:j(`Minimum value`),types:[`number`],compute:(e,t)=>kh([[e]],t).value},{name:j(`Maximum value`),types:[`number`],compute:(e,t)=>Oh([[e]],t).value}];function mk(e){let t={};for(let n of e)t[n.name]=void 0;return t}var hk=class extends wr{mutators=[`updateIgnoredRows`,`selectNextColumn`,`selectPreviousColumn`];statisticFnResults=mk(pk);selectedColumn;numericValues=[];values=[];dataFormat;countChartData;histogramData;isDirty=!1;ignoredRows=0;constructor(e){super(e),this.model.selection.observe(this,{handleEvent:this.refreshStatistics.bind(this)}),this.onDispose(()=>{this.model.selection.unobserve(this)}),this.refreshStatistics()}handle(e){switch((hu.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e))&&(this.isDirty=!0),e.type){case`HIDE_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`GROUP_HEADERS`:case`UNGROUP_HEADERS`:case`ACTIVATE_SHEET`:case`ACTIVATE_NEXT_SHEET`:case`ACTIVATE_PREVIOUS_SHEET`:case`EVALUATE_CELLS`:case`UNDO`:case`REDO`:this.isDirty=!0}}finalize(){this.isDirty&&(this.isDirty=!1,this.refreshStatistics())}get hasSingleColumn(){return this.selectedColumn!==void 0}computeCountChartData(){if(this.selectedColumn===void 0)return;let e=this.numericValues.length?this.numericValues:this.values;if(!e.length)return;let t=new Map;for(let n of e){if(n.value===null||n.value===void 0)continue;let e=typeof n.value==`number`?H(n.value,this.localeFormat):n.value.toString();t.has(e)||t.set(e,{positions:[],count:0,value:n.value}),t.get(e).positions.push({row:n.row,col:n.col}),t.get(e).count+=1}let n=[],r=[],i=[];return Array.from(t.entries()).sort((e,t)=>t[1].count-e[1].count).forEach(([e,t])=>{i.push(e),n.push(t.count),r.push(t.positions)}),{data:n,labels:i,positions:r}}computeHistogramData(){let e=this.numericValues.map(e=>e.value);if(!e.length)return;let t=1+Math.floor(Math.log2(e.length)),n=Math.min(...e),r=Math.max(...e)-n,i=r/t,a=Array(t).fill(0);if(r===0)a[0]=e.length;else for(let i of e){let e=(i-n)/r,o=Math.floor(e*t),s=Math.min(t-1,o);a[s]+=1}let o=this.localeFormat,s=[],c=[];for(let e=0;e<=t;e++)if(s.push(H(n+e*i,o)),e!==0){let t=n+(e-1)*i;c.push(`${H(t,o)}-${H(t+i,o)}`)}return{data:a,tooltipLabels:c,tickLabels:s}}get valueFrequencies(){let e=this.countChartData;return e?e.labels.map((t,n)=>({value:t,count:e.data[n],positions:e.positions[n]})):[]}updateIgnoredRows(e){this.ignoredRows=e,this.refreshStatistics()}refreshStatistics(){let e=this.getters;if(!e.isSingleColSelected()){this.selectedColumn=void 0,this.numericValues=[],this.values=[],this.statisticFnResults=mk(pk),this.dataFormat=void 0,this.countChartData=void 0,this.histogramData=void 0;return}let{sheetId:t,col:n}=e.getActivePosition();this.selectedColumn=n;let r=e.getEvaluatedCellsInZone(t,{top:0,left:n,bottom:e.getNumberRows(t)-1,right:n}).map(e=>e.format);this.dataFormat=r.find(w)??`0.00`;let i=e.getNumberRows(t),a=[],o=[],s=[],c=0;for(let r=0;r<i;r++){if(e.isRowHidden(t,r)||e.isColHidden(t,n))continue;if(c<this.ignoredRows){c++;continue}let i=e.getEvaluatedCell({sheetId:t,col:n,row:r});a.push(i),i.type!==`empty`&&i.type!==`error`&&(s.push({row:r,col:n,value:i.value}),i.type===`number`&&o.push({row:r,col:n,value:i.value}))}let l=e.getLocale();this.statisticFnResults=fk(pk,a,l),this.numericValues=o,this.values=s,this.countChartData=this.computeCountChartData(),this.histogramData=this.computeHistogramData()}selectPreviousColumn(){this.selectedColumn!==void 0&&this.model.selection.moveAnchorCell(`left`,1)}selectNextColumn(){this.selectedColumn!==void 0&&this.model.selection.moveAnchorCell(`right`,1)}get localeFormat(){return{locale:this.getters.getLocale(),format:this.dataFormat}}get statItems(){let e=this.localeFormat;return Object.entries(this.statisticFnResults).map(([t,n])=>n?.value===void 0?{name:t,value:`—`}:{name:t,value:H(n.value(),{locale:e.locale,format:n.format??e.format})})}},gk=class extends t.Component{static template=`o-spreadsheet-ColumnStatsPanel`;static props={onCloseSidePanel:Function};static components={NumberInput:rO,SidePanelCollapsible:ww,BadgeSelection:aO,Section:Z};state=(0,t.useState)({currentChart:`count`,currentFrequencyOrder:`descending`,highlightPositions:[]});store;chartCanvas=(0,t.useRef)(`columnStatsChart`);chart;setup(){this.store=O(hk),dk(this),(0,t.onWillUnmount)(()=>this.destroyChart()),(0,t.useEffect)(()=>{this.updateChart()},()=>[this.store.countChartData,this.store.histogramData,this.state.currentChart])}get columnLabel(){if(this.store.selectedColumn===void 0)return``;let e=this.env.model.getters.getEvaluatedCell({sheetId:this.env.model.getters.getActiveSheetId(),col:this.store.selectedColumn,row:0});return e?.type===`text`&&e.value.trim()!==``?e.value:j(`Column %s`,Zt(this.store.selectedColumn))}get charts(){return[{value:`count`,label:j(`Count`),icon:`o-spreadsheet-Icon.COUNT_CHART`},{value:`histogram`,label:j(`Distribution`),icon:`o-spreadsheet-Icon.COUNT_CHART`}]}get frequencyOrders(){return[{value:`descending`,label:j(`Descending`),icon:`o-spreadsheet-Icon.DESCENDING_SORT`},{value:`ascending`,label:j(`Ascending`),icon:`o-spreadsheet-Icon.ASCENDING_SORT`}]}get shouldShowChart(){return this.state.currentChart===`histogram`?this.store.numericValues.length>0:this.state.currentChart===`count`?this.store.values.length>0:!1}get chartErrorMessage(){return this.state.currentChart===`histogram`&&this.store.numericValues.length===0?j(`No numeric values to display.`):this.state.currentChart===`count`&&this.store.values.length===0?j(`No values to display.`):null}getChartConfiguration(){switch(this.state.currentChart){case`histogram`:return this.getHistogramChartConfiguration();case`count`:return this.getCountChartConfiguration()}return null}createChart(){if(!globalThis.Chart)throw Error(`Chart.js library is not loaded`);let e=this.chartCanvas.el;if(!e)return;let t=e.getContext(`2d`);if(!t)return;let n=this.getChartConfiguration();n&&(this.chart=new globalThis.Chart(t,n))}getCountChartConfiguration(){let e=this.store.countChartData;return e?{type:`bar`,data:{labels:e.labels.map(this.clipTextWithEllipsis.bind(this)),datasets:[{type:`bar`,data:e.data,backgroundColor:$r,borderSkipped:!1,borderWidth:1,barPercentage:1,categoryPercentage:1}]},options:{animation:!1,responsive:!0,maintainAspectRatio:!1,plugins:{legend:{display:!1},tooltip:{enabled:!0}},scales:{x:{display:!0,ticks:{maxRotation:90,minRotation:90}},y:{display:!0,beginAtZero:!0}}}}:null}getHistogramChartConfiguration(){let e=this.store.histogramData;return e?{type:`line`,data:{labels:e.tooltipLabels,datasets:[{type:`bar`,data:e.data,backgroundColor:$r,borderSkipped:!1,borderWidth:1,barPercentage:1,categoryPercentage:1}]},options:{animation:!1,responsive:!0,maintainAspectRatio:!1,plugins:{legend:{display:!1},tooltip:{enabled:!0}},scales:{x:{display:!1,stacked:!0,position:`top`},y:{display:!0},x2:{type:`linear`,position:`bottom`,display:!0,min:0,max:e.tooltipLabels.length,ticks:{callback:t=>Math.floor(t)===t?this.clipTextWithEllipsis(e.tickLabels?.[t]):``,maxRotation:90,minRotation:90}}}}}:null}clipTextWithEllipsis(e){if(!e)return``;let t=this.chartCanvas.el;if(!t)return e;let n=t.getContext(`2d`);return n?Pd(n,e,75):e}updateChart(){let e=this.getChartConfiguration();if(!e){this.destroyChart();return}if(!this.chart){this.createChart();return}this.chart.config.options=e.options,this.chart.data=e.data,this.chart.update()}destroyChart(){this.chart?.destroy(),this.chart=void 0}switchChart(e){this.state.currentChart=e}switchFrequencyOrder(e){this.state.currentFrequencyOrder=e}updateIgnoredRows(e){let t=parseInt(e,10);this.store.updateIgnoredRows(isNaN(t)?0:Math.max(0,t))}get valueFrequencies(){let e=this.state.currentFrequencyOrder===`ascending`?(e,t)=>e.count-t.count:(e,t)=>t.count-e.count;return this.store.valueFrequencies.sort(e).slice(0,5)}get highlights(){let e=this.store.selectedColumn;return e===void 0?[]:[{range:this.env.model.getters.getRangeFromZone(this.env.model.getters.getActiveSheetId(),{top:this.store.ignoredRows,left:e,bottom:void 0,right:e}),color:`#a3e9a39a`,interactive:!1},...this.state.highlightPositions.map(e=>({range:this.env.model.getters.getRangeFromZone(this.env.model.getters.getActiveSheetId(),D(e)),color:`#ffeb3b9a`,interactive:!1}))]}highlightFrequencyPositions(e){this.state.highlightPositions=e}clearHighlights(){this.state.highlightPositions=[]}},_k=class extends t.Component{static template=`o-spreadsheet-CellIsRuleEditor`;static components={ColorPickerWidget:HD,Select:Ty};static props={store:Object};getTextDecoration=Kv;get rule(){return this.props.store.state.rules.cellIs}},vk=class extends wr{mutators=[`updateConditionalFormat`,`closeMenus`];icons=kb;iconSets=Ab;state;cfId;constructor(e,n,r){switch(super(e),this.cfId=n.id,this.state=(0,t.useState)({errors:[],currentCFType:n.rule.type,ranges:n.ranges,rules:this.getDefaultRules(),hasEditedCf:r}),n.rule.type){case`CellIsRule`:this.state.rules.cellIs=n.rule;break;case`ColorScaleRule`:this.state.rules.colorScale=n.rule;break;case`IconSetRule`:this.state.rules.iconSet=n.rule;break;case`DataBarRule`:this.state.rules.dataBar=n.rule;break}}updateConditionalFormat(e){let t=e.ranges||this.state.ranges;if(this.state.ranges.some(e=>!e.match(Uo))){e.suppressErrors||(this.state.errors=[`InvalidRange`]);return}let n=this.model.getters.getActiveSheetId(),r=this.model.getters.getLocale(),i=e.rule||this.getEditedRule(this.state.currentCFType),a=this.model.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{id:this.cfId,rule:nb(i,r)},ranges:t.map(e=>this.model.getters.getRangeDataFromXc(n,e)),sheetId:n});a.isSuccessful&&(this.state.hasEditedCf=!0);let o=a.reasons.filter(e=>e!==`NoChanges`);e.suppressErrors||(this.state.errors=o)}get isRangeValid(){return this.state.errors.includes(`EmptyRange`)}get errorMessages(){return this.state.errors.map(e=>Ny.Errors[e]||Ny.Errors.Unexpected)}onRangeUpdate(e){this.state.ranges=e}onRangeConfirmed(){this.updateConditionalFormat({ranges:this.state.ranges})}changeRuleType(e){this.state.currentCFType!==e&&(this.state.errors=[],this.state.currentCFType=e,this.updateConditionalFormat({rule:this.getEditedRule(e),suppressErrors:!0}))}getEditedRule(e){switch(e){case`CellIsRule`:return this.state.rules.cellIs;case`ColorScaleRule`:return this.state.rules.colorScale;case`IconSetRule`:return this.state.rules.iconSet;case`DataBarRule`:return this.state.rules.dataBar}}get cfCriterions(){return PT(Vh)}get criterionComponent(){return Q.get(this.state.rules.cellIs.operator).component}get genericCriterion(){return{...this.state.rules.cellIs,type:this.state.rules.cellIs.operator}}onRuleValuesChanged(e){let t={...e,operator:e.type,type:`CellIsRule`,style:this.state.rules.cellIs.style};this.state.rules.cellIs=t,this.updateConditionalFormat({rule:t})}toggleStyle(e){let t=this.state.rules.cellIs.style;t[e]=!t[e],this.updateConditionalFormat({rule:this.state.rules.cellIs}),this.closeMenus()}setColor(e,t){this.state.rules.cellIs.style[e]=t,this.updateConditionalFormat({rule:this.state.rules.cellIs}),this.closeMenus()}editOperator(e){this.state.rules.cellIs.operator=e,e.includes(`date`)&&!this.state.rules.cellIs.dateValue&&(this.state.rules.cellIs.dateValue=`exactDate`),this.updateConditionalFormat({rule:this.state.rules.cellIs,suppressErrors:!0}),this.closeMenus()}get previewGradient(){let e=this.state.rules.colorScale,t=jr(e.minimum.color),n=jr(e.midpoint?.color||11982760),r=jr(e.maximum.color),i=`linear-gradient(to right, `;return W({"background-image":e.midpoint===void 0?i+t+`, `+r+`)`:i+t+`, `+n+`, `+r+`)`,color:`#000`})}onMidpointChange(e){let t=this.state.rules.colorScale;e===`none`?t.midpoint=void 0:t.midpoint={color:se,value:``,...t.midpoint,type:e},this.updateConditionalFormat({rule:t,suppressErrors:!0})}updateThresholdType(e,t){this.state.rules.colorScale[e].type=t,this.updateConditionalFormat({rule:this.state.rules.colorScale,suppressErrors:!0})}updateThresholdValue(e,t){this.state.rules.colorScale[e].value=t,this.updateConditionalFormat({rule:this.state.rules.colorScale})}setColorScaleColor(e,t){if(!Pr(t))return;let n=this.state.rules.colorScale[e];n&&(n.color=Mr(t)),this.updateConditionalFormat({rule:this.state.rules.colorScale}),this.closeMenus()}reverseIcons(){let e=this.state.rules.iconSet.icons,t=e.upper;e.upper=e.lower,e.lower=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setIconSet(e){let t=this.state.rules.iconSet.icons;t.upper=this.iconSets[e].good,t.middle=this.iconSets[e].neutral,t.lower=this.iconSets[e].bad,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setIcon(e,t){this.state.rules.iconSet.icons[e]=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setInflectionOperator(e,t){this.state.rules.iconSet[e].operator=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setInflectionValue(e,t){this.state.rules.iconSet[e].value=t,this.updateConditionalFormat({rule:this.state.rules.iconSet})}setInflectionType(e,t){this.state.rules.iconSet[e].type=t,this.updateConditionalFormat({rule:this.state.rules.iconSet,suppressErrors:!0})}get rangeValues(){return[this.state.rules.dataBar.rangeValues||``]}updateDataBarColor(e){Pr(e)&&(this.state.rules.dataBar.color=Number.parseInt(e.slice(1),16),this.updateConditionalFormat({rule:this.state.rules.dataBar}))}onDataBarRangeUpdate(e){this.state.rules.dataBar.rangeValues=e[0]}onDataBarRangeChange(){this.updateConditionalFormat({rule:this.state.rules.dataBar})}toggleMenu(e){let t=this.state.openedMenu===e;this.closeMenus(),t||(this.state.openedMenu=e)}closeMenus(){this.state.openedMenu=void 0}getDefaultRules(){return{cellIs:{type:`CellIsRule`,operator:`isNotEmpty`,values:[],style:{fillColor:`#b6d7a8`}},colorScale:{type:`ColorScaleRule`,minimum:{type:`value`,color:mx(`EFF7FF`)},midpoint:void 0,maximum:{type:`value`,color:6989903}},iconSet:{type:`IconSetRule`,icons:{upper:`arrowGood`,middle:`arrowNeutral`,lower:`arrowBad`},upperInflectionPoint:{type:`percentage`,value:`66`,operator:`gt`},lowerInflectionPoint:{type:`percentage`,value:`33`,operator:`gt`}},dataBar:{type:`DataBarRule`,color:14281427}}}},yk=class extends t.Component{static template=`o-spreadsheet-ColorScaleRuleEditorThreshold`;static components={RoundColorPicker:ST,StandaloneComposer:pT,Select:Ty};static props={store:Object,thresholdType:String};get rule(){return this.props.store.state.rules.colorScale}get threshold(){return this.rule[this.props.thresholdType]}getThresholdColor(e){return jr(e?e.color:se)}isValueInvalid(){let e=this.props.store.state.errors;switch(this.props.thresholdType){case`minimum`:return e.includes(`MinInvalidFormula`)||e.includes(`MinBiggerThanMid`)||e.includes(`MinBiggerThanMax`)||e.includes(`MinNaN`);case`midpoint`:return e.includes(`MidInvalidFormula`)||e.includes(`MidNaN`)||e.includes(`MidBiggerThanMax`);case`maximum`:return e.includes(`MaxInvalidFormula`)||e.includes(`MaxNaN`);default:return!1}}getColorScaleComposerProps(){let e=this.rule[this.props.thresholdType];if(!e)throw Error(`Threshold not found`);let t=this.isValueInvalid();return{onConfirm:t=>{e.value=t,this.props.store.updateConditionalFormat({rule:this.rule})},composerContent:e.value||``,placeholder:j(`Formula`),defaultStatic:!0,invalid:t,class:`o-sidePanel-composer`,defaultRangeSheetId:this.env.model.getters.getActiveSheetId()}}getThresholdTypeSelectOptions(){let e=[{value:`number`,label:j(`Number`)},{value:`percentage`,label:j(`Percentage`)},{value:`percentile`,label:j(`Percentile`)},{value:`formula`,label:j(`Formula`)}];return this.props.thresholdType===`midpoint`?[{value:`none`,label:j(`None`)},...e]:[{value:`value`,label:j(`Cell values`)},...e]}},bk=class extends t.Component{static template=`o-spreadsheet-ColorScaleRuleEditor`;static components={ColorScaleRuleEditorThreshold:yk};static props={store:Object}},xk=class extends t.Component{static template=`o-spreadsheet-DataBarRuleEditor`;static components={SelectionInput:jT,RoundColorPicker:ST};static props={store:Object};get rule(){return this.props.store.state.rules.dataBar}colorNumberToHex=jr},Sk=class extends t.Component{static template=`o-spreadsheet-IconPicker`;static props={onIconPicked:Function};icons=kb;iconSets=Ab;onIconClick(e){e&&this.props.onIconPicked(e)}},Ck=class extends t.Component{static template=`o-spreadsheet-IconSetRuleEditor`;static components={IconPicker:Sk,StandaloneComposer:pT,Select:Ty};static props={store:Object};get rule(){return this.props.store.state.rules.iconSet}getIconName(e,t){return this.props.store.iconSets[e][t]}getIconTemplate(e){return`o-spreadsheet-Icon.${this.props.store.icons[e].template}`}isInflectionPointInvalid(e){let t=this.props.store.state.errors;switch(e){case`lowerInflectionPoint`:return t.includes(`ValueLowerInflectionNaN`)||t.includes(`ValueLowerInvalidFormula`)||t.includes(`LowerBiggerThanUpper`);case`upperInflectionPoint`:return t.includes(`ValueUpperInflectionNaN`)||t.includes(`ValueUpperInvalidFormula`)||t.includes(`LowerBiggerThanUpper`);default:return!0}}getColorIconSetComposerProps(e){let t=this.props.store.state.rules.iconSet[e],n=this.isInflectionPointInvalid(e);return{onConfirm:e=>{t.value=e,this.props.store.updateConditionalFormat({rule:this.props.store.state.rules.iconSet})},composerContent:t.value||``,placeholder:j(`Formula`),defaultStatic:!0,invalid:n,class:`o-sidePanel-composer`,defaultRangeSheetId:this.env.model.getters.getActiveSheetId()}}getThresholdTypeSelectOptions(){return[{value:`number`,label:j(`Number`)},{value:`percentage`,label:j(`Percentage`)},{value:`percentile`,label:j(`Percentile`)},{value:`formula`,label:j(`Formula`)}]}getIconSetOperatorSelectOptions(){return[{value:`gt`,label:`>`},{value:`ge`,label:`>=`}]}},wk=class extends t.Component{static template=`o-spreadsheet-ConditionalFormattingEditor`;static components={SelectionInput:jT,Section:Z,BadgeSelection:aO,ValidationMessages:$D,CellIsRuleEditor:_k,ColorScaleRuleEditor:bk,IconSetRuleEditor:Ck,DataBarRuleEditor:xk};static props={cf:Object,isNewCf:Boolean,onCloseSidePanel:Function};activeSheetId;store;setup(){this.activeSheetId=this.env.model.getters.getActiveSheetId(),this.store=hr(vk,x(this.props.cf),this.props.isNewCf),(0,t.useEffect)((e,t)=>{(this.activeSheetId!==e||t)&&this.env.replaceSidePanel(`ConditionalFormatting`,`ConditionalFormattingEditor_${this.props.cf.id}`)},()=>[this.env.model.getters.getActiveSheetId(),this.isEditedCfRemoved]),(0,t.useExternalListener)(window,`click`,()=>this.store.closeMenus())}get isEditedCfRemoved(){return!this.env.model.getters.getConditionalFormats(this.activeSheetId).find(e=>e.id===this.props.cf.id)}get cfTypesValues(){return[{value:`CellIsRule`,label:j(`Single color`)},{value:`ColorScaleRule`,label:j(`Color scale`)},{value:`IconSetRule`,label:j(`Icon set`)},{value:`DataBarRule`,label:j(`Data bar`)}]}onSave(){this.store.updateConditionalFormat({}),this.store.state.errors.length===0&&this.env.replaceSidePanel(`ConditionalFormatting`,`ConditionalFormattingEditor_${this.props.cf.id}`)}onCancel(){this.store.state.hasEditedCf&&(this.props.isNewCf?this.env.model.dispatch(`REMOVE_CONDITIONAL_FORMAT`,{sheetId:this.activeSheetId,id:this.props.cf.id}):this.env.model.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:this.props.cf,ranges:this.props.cf.ranges.map(e=>this.env.model.getters.getRangeDataFromXc(this.activeSheetId,e)),sheetId:this.activeSheetId})),this.env.replaceSidePanel(`ConditionalFormatting`,`ConditionalFormattingEditor_${this.props.cf.id}`)}},Tk=class extends t.Component{static template=`o-spreadsheet-ConditionalFormatPreview`;static props={conditionalFormat:Object,onMouseDown:Function,class:String};icons=kb;ref=(0,t.useRef)(`cfPreview`);setup(){uk(this.ref,this)}get previewImageStyle(){let e=this.props.conditionalFormat.rule;if(e.type===`CellIsRule`)return W(qv(e.style));if(e.type===`ColorScaleRule`){let t=jr(e.minimum.color),n=e.midpoint?jr(e.midpoint.color):null,r=jr(e.maximum.color),i=`background-image: linear-gradient(to right, `;return n?i+t+`, `+n+`, `+r+`)`:i+t+`, `+r+`)`}else if(e.type===`DataBarRule`)return`${`background-image: linear-gradient(to right, ${jr(e.color)} 50%, white 50%)`}; color: ${he};`;return``}get description(){let e=this.props.conditionalFormat;switch(e.rule.type){case`CellIsRule`:return X.get(e.rule.operator).getPreview({...e.rule,type:e.rule.operator},this.env.model.getters);case`ColorScaleRule`:return Ny.ColorScale;case`IconSetRule`:return Ny.IconSet;case`DataBarRule`:return Ny.DataBar}}get highlights(){let e=this.env.model.getters.getActiveSheetId();return this.props.conditionalFormat.ranges.map(t=>({range:this.env.model.getters.getRangeFromSheetXC(e,t),color:ee,fillAlpha:.06}))}editConditionalFormat(){this.env.replaceSidePanel(`ConditionalFormattingEditor`,`ConditionalFormatting`,{cf:this.props.conditionalFormat,isNewCf:!1})}deleteConditionalFormat(){this.env.model.dispatch(`REMOVE_CONDITIONAL_FORMAT`,{id:this.props.conditionalFormat.id,sheetId:this.env.model.getters.getActiveSheetId()})}},Ek=class extends t.Component{static template=`o-spreadsheet-ConditionalFormatPreviewList`;static props={onCloseSidePanel:Function};static components={ConditionalFormatPreview:Tk};dragAndDrop=wT();cfListRef=(0,t.useRef)(`cfList`);get conditionalFormats(){return this.env.model.getters.getConditionalFormats(this.env.model.getters.getActiveSheetId()).map(e=>({...e,rule:rb(e.rule,this.env.model.getters.getLocale())}))}getPreviewDivStyle(e){return this.dragAndDrop.itemsStyle[e.id]||``}onPreviewMouseDown(e,t){if(t.button!==0)return;let n=Array.from(this.cfListRef.el.children).map(e=>gm(e)),r=this.conditionalFormats.map((e,t)=>({id:e.id,size:n[t].height,position:n[t].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.id,initialMousePosition:t.clientY,items:r,scrollableContainerEl:this.cfListRef.el,onDragEnd:(e,t)=>this.onDragEnd(e,t)})}onAddConditionalFormat(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones(),n={id:this.env.model.uuidGenerator.smallUuid(),rule:{type:`CellIsRule`,operator:`isNotEmpty`,style:{fillColor:`#b6d7a8`},values:[]}};return this.env.model.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:n,ranges:t.map(t=>this.env.model.getters.getRangeDataFromZone(e,t)),sheetId:e}),this.env.replaceSidePanel(`ConditionalFormattingEditor`,`ConditionalFormatting`,{cf:{...n,ranges:t.map(t=>wn(this.env.model.getters.getUnboundedZone(e,t)))},isNewCf:!0})}onDragEnd(e,t){let n=this.conditionalFormats.findIndex(t=>t.id===e)-t;n!==0&&this.env.model.dispatch(`CHANGE_CONDITIONAL_FORMAT_PRIORITY`,{cfId:e,delta:n,sheetId:this.env.model.getters.getActiveSheetId()})}},Dk=class extends t.Component{static template=`o-spreadsheet-DataValidationPreview`;static props={rule:Object};ref=(0,t.useRef)(`dvPreview`);setup(){uk(this.ref,this)}onPreviewClick(){this.env.replaceSidePanel(`DataValidationEditor`,`DataValidation`,{ruleId:this.props.rule.id})}deleteDataValidation(){let e=this.env.model.getters.getActiveSheetId();this.env.model.dispatch(`REMOVE_DATA_VALIDATION_RULE`,{sheetId:e,id:this.props.rule.id})}get highlights(){return this.props.rule.ranges.map(e=>({range:e,color:ee,fillAlpha:.06}))}get rangesString(){let e=this.env.model.getters.getActiveSheetId();return this.props.rule.ranges.map(t=>this.env.model.getters.getRangeString(t,e)).join(`, `)}get descriptionString(){return X.get(this.props.rule.criterion.type).getPreview(this.props.rule.criterion,this.env.model.getters)}},Ok=class extends t.Component{static template=`o-spreadsheet-DataValidationPanel`;static props={onCloseSidePanel:Function};static components={DataValidationPreview:Dk};addDataValidationRule(){this.env.replaceSidePanel(`DataValidationEditor`,`DataValidation`,{ruleId:this.env.model.uuidGenerator.smallUuid()})}localizeDVRule(e){return e&&ib(e,this.env.model.getters.getLocale())}get validationRules(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getDataValidationRules(e)}},kk=class extends t.Component{static template=`o-spreadsheet-DataValidationEditor`;static components={SelectionInput:jT,Select:Ty,Section:Z,ValidationMessages:$D};static props={ruleId:String,onCancel:{type:Function,optional:!0},onCloseSidePanel:Function};state=(0,t.useState)({rule:this.defaultDataValidationRule,errors:[],isTypeUpdated:!1});editingSheetId;setup(){this.editingSheetId=this.env.model.getters.getActiveSheetId();let e=this.env.model.getters.getDataValidationRule(this.editingSheetId,this.props.ruleId);if(e){let t=this.env.model.getters.getLocale();this.state.rule={...ib(e,t),ranges:e.ranges.map(e=>this.env.model.getters.getRangeString(e,this.editingSheetId))}}}onCriterionTypeChanged(e){this.state.rule.criterion.type=e,this.state.isTypeUpdated=!0}onRangesChanged(e){this.state.rule.ranges=e}onCriterionChanged(e){this.state.rule.criterion=e}changeRuleIsBlocking(e){this.state.rule.isBlocking=e===`true`}onCancel(){this.props.onCancel?.(),this.env.replaceSidePanel(`DataValidation`,`DataValidationEditor_${this.props.ruleId}`)}onSave(){let e=this.env.model.dispatch(`ADD_DATA_VALIDATION_RULE`,this.dispatchPayload);if(!e.isSuccessful){this.state.errors=e.reasons;return}this.env.replaceSidePanel(`DataValidation`,`DataValidationEditor_${this.props.ruleId}`)}get dispatchPayload(){let e={...this.state.rule,ranges:void 0},t=this.env.model.getters.getLocale(),n=e.criterion,r=X.get(n.type),i=n.values.slice(0,r.numberOfValues(n)).filter(e=>e&&e.trim()!==``).map(e=>Ky(e,t));return e.criterion={...n,values:i},{sheetId:this.editingSheetId,ranges:this.state.rule.ranges.map(e=>this.env.model.getters.getRangeDataFromXc(this.editingSheetId,e)),rule:e}}get dvCriterionOptions(){return PT(Hh)}get defaultDataValidationRule(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZones().map(t=>wn(this.env.model.getters.getUnboundedZone(e,t)));return{id:this.props.ruleId,criterion:{type:`containsText`,values:[``]},ranges:t}}get criterionComponent(){return Q.get(this.state.rule.criterion.type).component}get errorMessages(){return this.state.errors.map(e=>By.Errors[e]||By.Errors.Unexpected)}get isRuleBlockingSelectOptions(){return[{value:`false`,label:j(`Show a warning`)},{value:`true`,label:j(`Reject the input`)}]}};let Ak=`#8B008B`;var jk=class extends wr{mutators=[`updateSearchOptions`,`updateSearchContent`,`searchFormulas`,`selectPreviousMatch`,`selectNextMatch`,`replace`];allSheetsMatches=[];activeSheetMatches=[];specificRangeMatches=[];selectedMatchPosition=null;currentSearchRegex=null;initialShowFormulaState;irreplaceableMatchCount=0;isSearchDirty=!1;shouldFinalizeUpdateSelection=!1;notificationStore=this.get(lT);selectedMatchIndex=null;toSearch=``;toReplace=``;searchOptions={matchCase:!1,exactMatch:!1,searchFormulas:!1,searchScope:`activeSheet`,specificRange:void 0};constructor(e){super(e),this.initialShowFormulaState=this.model.getters.shouldShowFormulas(),this.searchOptions.searchFormulas=this.initialShowFormulaState;let t=e(cT);t.register(this),this.onDispose(()=>{this.model.dispatch(`SET_FORMULA_VISIBILITY`,{show:this.initialShowFormulaState}),t.unRegister(this)})}get searchMatches(){switch(this.searchOptions.searchScope){case`allSheets`:return this.allSheetsMatches;case`activeSheet`:return this.activeSheetMatches;case`specificRange`:return this.specificRangeMatches}}updateSearchContent(e){this._updateSearch(e,this.searchOptions)}updateSearchOptions(e){this._updateSearch(this.toSearch,{...this.searchOptions,...e})}searchFormulas(e){this.model.dispatch(`SET_FORMULA_VISIBILITY`,{show:e}),this.updateSearchOptions({searchFormulas:e})}selectPreviousMatch(){this.selectNextCell(-1,{jumpToMatchSheet:!0,updateSelection:!0})}selectNextMatch(){this.selectNextCell(1,{jumpToMatchSheet:!0,updateSelection:!0})}handle(e){switch(e.type){case`SET_FORMULA_VISIBILITY`:this.updateSearchOptions({searchFormulas:e.show});break;case`UNDO`:case`REDO`:case`REMOVE_TABLE`:case`UPDATE_FILTER`:case`REMOVE_COLUMNS_ROWS`:case`HIDE_COLUMNS_ROWS`:case`UNHIDE_COLUMNS_ROWS`:case`ADD_COLUMNS_ROWS`:case`EVALUATE_CELLS`:case`UPDATE_CELL`:this.isSearchDirty=!0;break;case`ACTIVATE_SHEET`:this.isSearchDirty=!0,this.shouldFinalizeUpdateSelection=!0,this.searchOptions.specificRange&&(this.searchOptions.specificRange={...this.searchOptions.specificRange,sheetId:this.getters.getActiveSheetId()});break;case`DELETE_SHEET`:this.searchOptions.searchScope===`specificRange`&&this.searchOptions.specificRange?.sheetId===e.sheetId&&(this.searchOptions={...this.searchOptions,specificRange:void 0}),this.isSearchDirty=!0;break;case`REPLACE_SEARCH`:for(let t of e.matches)this.replaceMatch(t,e.searchString,e.replaceWith,e.searchOptions);this.irreplaceableMatchCount>0&&this.showReplaceWarningMessage(e.matches.length,this.irreplaceableMatchCount),this.irreplaceableMatchCount=0;break}}finalize(){this.isSearchDirty&&=(this.refreshSearch({jumpToMatchSheet:!1,updateSelection:this.shouldFinalizeUpdateSelection}),this.shouldFinalizeUpdateSelection=!1,!1)}get allSheetMatchesCount(){return this.allSheetsMatches.length}get activeSheetMatchesCount(){return this.activeSheetMatches.length}get specificRangeMatchesCount(){return this.specificRangeMatches.length}_updateSearch(e,t){this.searchOptions=t,e!==this.toSearch&&(this.selectedMatchIndex=null,this.selectedMatchPosition=null),this.toSearch=e,this.currentSearchRegex=Bt(this.toSearch,this.searchOptions),this.refreshSearch({jumpToMatchSheet:!0,updateSelection:!0})}refreshSearch(e){if(this.findMatches(),this.selectedMatchPosition)if(this.selectedMatchPosition.sheetId!==this.getters.getActiveSheetId())this.selectedMatchIndex=null,this.selectedMatchPosition=null;else{let e=this.searchMatches.findIndex(e=>e.sheetId===this.selectedMatchPosition?.sheetId&&e.col===this.selectedMatchPosition?.col&&e.row===this.selectedMatchPosition?.row);e!==-1&&(this.selectedMatchIndex=e)}this.selectNextCell(0,e)}getSheetsInSearchOrder(){switch(this.searchOptions.searchScope){case`allSheets`:let e=this.getters.getSheetIds(),t=e.findIndex(e=>e===this.getters.getActiveSheetId());return[e[t],...e.slice(t+1),...e.slice(0,t)];case`activeSheet`:return[this.getters.getActiveSheetId()];case`specificRange`:let n=this.searchOptions.specificRange;return n&&n?[n.sheetId]:[]}}findMatches(){let e=[];if(this.toSearch)for(let t of this.getters.getSheetIds())e.push(...this.findMatchesInSheet(t));if(this.allSheetsMatches=e,this.activeSheetMatches=e.filter(e=>e.sheetId===this.getters.getActiveSheetId()),this.searchOptions.specificRange){let{sheetId:t,zone:n}=this.searchOptions.specificRange;this.specificRangeMatches=e.filter(e=>e.sheetId===t&&Fn(e.col,e.row,n))}else this.specificRangeMatches=[]}findMatchesInSheet(e){let t=[],{left:n,right:r,top:i,bottom:a}=this.getters.getSheetZone(e);for(let o=i;o<=a;o++)for(let i=n;i<=r;i++){let n=this.getters.isColHidden(e,i),r=this.getters.isRowHidden(e,o);if(n||r)continue;let a={sheetId:e,col:i,row:o};if(this.currentSearchRegex?.test(this.getSearchableString(a))){let n={sheetId:e,col:i,row:o};t.push(n)}}return t}selectNextCell(e,t){let n=this.searchMatches;if(!n.length){this.selectedMatchIndex=null,this.selectedMatchPosition=null;return}let r;if(this.selectedMatchIndex===null){let e=-1;for(let t of this.getSheetsInSearchOrder())if(e=n.findIndex(e=>e.sheetId===t),e!==-1)break;r=e}else r=this.selectedMatchIndex+e;r=(r+n.length)%n.length,this.selectedMatchIndex=r,this.selectedMatchPosition=n[this.selectedMatchIndex];let i=n[r];t.jumpToMatchSheet&&this.getters.getActiveSheetId()!==i.sheetId&&(this.model.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:this.getters.getActiveSheetId(),sheetIdTo:i.sheetId}),this.isSearchDirty=!1),this.model.selection.getBackToDefault(),t.updateSelection&&this.model.selection.selectCell(i.col,i.row)}replace(){this.selectedMatchIndex!==null&&(this.shouldFinalizeUpdateSelection=!0,this.model.dispatch(`REPLACE_SEARCH`,{searchString:this.toSearch,replaceWith:this.toReplace,matches:[this.searchMatches[this.selectedMatchIndex]],searchOptions:this.searchOptions}))}replaceAll(){this.model.dispatch(`REPLACE_SEARCH`,{searchString:this.toSearch,replaceWith:this.toReplace,matches:this.searchMatches,searchOptions:this.searchOptions})}showReplaceWarningMessage(e,t){let n=e-t;n===0?this.notificationStore.notifyUser({type:`warning`,sticky:!1,text:j(`Match(es) cannot be replaced as they are part of a formula or inside a locked sheet`)}):this.notificationStore.notifyUser({type:`warning`,sticky:!1,text:j(`%(replaceable_count)s match(es) replaced. %(irreplaceable_count)s match(es) cannot be replaced as they are part of a formula or inside a locked sheet`,{replaceable_count:n,irreplaceable_count:t})})}replaceMatch(e,t,n,r){if(this.getters.isSheetLocked(e.sheetId)){this.irreplaceableMatchCount++;return}let i=this.getters.getCell(e);if(!i?.isFormula&&!i?.content)return;if(i?.isFormula&&!r.searchFormulas){this.irreplaceableMatchCount++;return}let a=Bt(t,r),o=new RegExp(a.source,a.flags+`g`),s=Gy(this.getters.getCellText(e,{showFormula:r.searchFormulas}).replace(o,n),this.getters.getLocale());this.model.dispatch(`UPDATE_CELL`,{...e,content:s})}getSearchableString(e){return this.getters.getCellText(e,{showFormula:this.searchOptions.searchFormulas})}get highlights(){let e=[],t=this.getters.getActiveSheetId();for(let[n,r]of this.searchMatches.entries()){if(r.sheetId!==t)continue;let i=D(r),a=this.getters.expandZone(t,i),{width:o,height:s}=this.getters.getVisibleRect(a);o>0&&s>0&&e.push({range:this.model.getters.getRangeFromZone(t,a),color:Ak,noBorder:n!==this.selectedMatchIndex,thinLine:!0,fillAlpha:.2})}if(this.searchOptions.searchScope===`specificRange`){let n=this.searchOptions.specificRange;n&&n.sheetId===t&&e.push({range:n,color:Ak,noFill:!0,thinLine:!0})}return e}},Mk=class extends t.Component{static template=`o-spreadsheet-FindAndReplacePanel`;static components={SelectionInput:jT,Section:Z,Checkbox:IT,ValidationMessages:$D,Select:Ty};static props={onCloseSidePanel:Function};searchInput=(0,t.useRef)(`searchInput`);store;state;updateSearchContent;get hasSearchResult(){return this.store.selectedMatchIndex!==null}get searchOptions(){return this.store.searchOptions}get allSheetsMatchesCount(){return j(`%s matches in all sheets`,this.store.allSheetMatchesCount)}get currentSheetMatchesCount(){return j(`%(matches)s matches in %(sheetName)s`,{matches:this.store.activeSheetMatchesCount,sheetName:this.env.model.getters.getSheetName(this.env.model.getters.getActiveSheetId())})}get specificRangeMatchesCount(){let e=this.searchOptions.specificRange;if(!e)return``;let{sheetId:t,zone:n}=e;return j(`%(matches)s matches in range %(range)s of %(sheetName)s`,{matches:this.store.specificRangeMatchesCount,range:wn(n),sheetName:this.env.model.getters.getSheetName(t)})}get searchInfo(){return this.store.toSearch?[this.specificRangeMatchesCount,this.currentSheetMatchesCount,this.allSheetsMatchesCount]:[]}setup(){this.store=hr(jk),this.state=(0,t.useState)({dataRange:``}),(0,t.onMounted)(()=>this.searchInput.el?.focus()),(0,t.onWillUnmount)(()=>this.updateSearchContent.stopDebounce()),this.updateSearchContent=_t(this.store.updateSearchContent,200),(0,t.useExternalListener)(window,`keydown`,e=>{let t=Cm(e);(t===`Ctrl+F`||t===`Ctrl+H`)&&(this.searchInput.el?.focus(),e.preventDefault(),e.stopPropagation())},{capture:!0})}onFocusSearch(){this.updateDataRange()}onSearchInput(e){this.updateSearchContent(e.target.value)}onKeydownPanel(e){e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.props.onCloseSidePanel())}onKeydownSearch(e){e.key===`Enter`&&(e.preventDefault(),e.stopPropagation(),e.shiftKey?this.store.selectPreviousMatch():this.store.selectNextMatch())}onKeydownReplace(e){e.key===`Enter`&&(e.preventDefault(),e.stopPropagation(),this.store.replace())}searchFormulas(e){this.store.searchFormulas(e)}searchExactMatch(e){this.store.updateSearchOptions({exactMatch:e})}searchMatchCase(e){this.store.updateSearchOptions({matchCase:e})}changeSearchScope(e){this.store.updateSearchOptions({searchScope:e})}onSearchRangeChanged(e){this.state.dataRange=e[0]}updateDataRange(){if(!this.state.dataRange||this.searchOptions.searchScope!==`specificRange`)return;let e=this.env.model.getters.getRangeFromSheetXC(this.env.model.getters.getActiveSheetId(),this.state.dataRange);this.store.updateSearchOptions({specificRange:e})}get specificRange(){let e=this.store.searchOptions.specificRange;return e?this.env.model.getters.getRangeString(e,`forceSheetReference`):``}get pendingSearch(){return this.updateSearchContent.isDebouncePending()}get selectionInputKey(){return this.env.model.getters.getActiveSheetId()}get searchScopeOptions(){return[{value:`allSheets`,label:j(`All sheets`)},{value:`activeSheet`,label:j(`Current sheet`)},{value:`specificRange`,label:j(`Specific range`)}]}};let Nk=new A;function Pk({name:e,format:t,descriptionValue:n}){let r=typeof t==`function`?t:()=>t;return{name:e,description:e=>H(n,{format:r(e),locale:e.model.getters.getLocale()}),execute:e=>pE(e,r(e)),isActive:e=>jA(e,r(e)),format:t}}let Fk={name:j(`Automatic`),execute:e=>pE(e,``),isActive:e=>AA(e)},Ik={name:j(`Plain text`),execute:e=>pE(e,`@`),isActive:e=>jA(e,`@`)},Lk=Pk({name:j(`Number`),descriptionValue:1000.12,format:`#,##0.00`}),Rk={name:j(`Format as percent`),execute:HE,icon:`o-spreadsheet-Icon.PERCENT`},zk=Pk({name:j(`Percent`),descriptionValue:.1012,format:`0.00%`}),Bk=Pk({name:j(`Scientific`),descriptionValue:.1012,format:`0.00e`}),Vk=Pk({name:j(`Currency`),descriptionValue:1000.12,format:e=>Ul(e.model.config.defaultCurrency||He)}),Hk={...Pk({name:j(`Currency rounded`),descriptionValue:1e3,format:e=>ql(Ul(e.model.config.defaultCurrency||He))}),isVisible:e=>{let t=Ul(e.model.config.defaultCurrency||He);return t!==ql(t)}},Uk=Pk({name:j(`Accounting`),descriptionValue:-1000.12,format:e=>Wl(e.model.config.defaultCurrency||He)}),Wk=Hu(`2023/09/26 10:43:00 PM`,V),Gk={name:j(`Custom currency`),isVisible:e=>e.loadCurrencies!==void 0&&!e.isSmall,execute:e=>e.openSidePanel(`MoreFormats`,{category:`currency`})},Kk=Pk({name:j(`Date`),descriptionValue:Wk,format:e=>e.model.getters.getLocale().dateFormat}),qk=Pk({name:j(`Time`),descriptionValue:Wk,format:e=>e.model.getters.getLocale().timeFormat}),Jk=Pk({name:j(`Date time`),descriptionValue:Wk,format:e=>sb(e.model.getters.getLocale())}),Yk=Pk({name:j(`Duration`),descriptionValue:`27:51:38`,format:`hhhh:mm:ss`}),Xk={name:j(`Custom date and time`),isVisible:e=>!e.isSmall,execute:e=>e.openSidePanel(`MoreFormats`,{category:`date`})},Zk={name:j(`Custom number format`),isVisible:e=>!e.isSmall,execute:e=>e.openSidePanel(`MoreFormats`,{category:`number`})};Pk({name:j(`Full date time`),format:`dddd d mmmm yyyy hh:mm:ss a`,descriptionValue:Wk});let Qk={name:j(`Increase decimal places`),icon:`o-spreadsheet-Icon.INCREASE_DECIMAL`,execute:e=>e.model.dispatch(`SET_DECIMAL`,{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),step:1})},$k={name:j(`Decrease decimal places`),icon:`o-spreadsheet-Icon.DECRASE_DECIMAL`,execute:e=>e.model.dispatch(`SET_DECIMAL`,{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones(),step:-1})},eA={name:j(`Bold`),shortcut:`Ctrl+B`,execute:e=>mE(e,{bold:!e.model.getters.getCurrentStyle().bold}),icon:`o-spreadsheet-Icon.BOLD`,isActive:e=>!!e.model.getters.getCurrentStyle().bold},tA={name:j(`Italic`),shortcut:`Ctrl+I`,execute:e=>mE(e,{italic:!e.model.getters.getCurrentStyle().italic}),icon:`o-spreadsheet-Icon.ITALIC`,isActive:e=>!!e.model.getters.getCurrentStyle().italic},nA={name:j(`Underline`),shortcut:`Ctrl+U`,execute:e=>mE(e,{underline:!e.model.getters.getCurrentStyle().underline}),icon:`o-spreadsheet-Icon.UNDERLINE`,isActive:e=>!!e.model.getters.getCurrentStyle().underline},rA={name:j(`Rotation`),icon:e=>zA(e)};function iA(e,t){t=Math.trunc(t/Se)*Se,mE(e,{rotation:t})}function aA(e,t){let n=e.model.getters.getCurrentStyle().rotation;return n===void 0?t===0:Math.abs(n-t)<Se}let oA={name:j(`No rotation`),execute:e=>mE(e,{rotation:0}),icon:`o-spreadsheet-Icon.ROTATION-0`,isActive:e=>aA(e,0)},sA={name:j(`45° rotation`),execute:e=>iA(e,Math.PI/4),icon:`o-spreadsheet-Icon.ROTATION-45`,isActive:e=>aA(e,Math.PI/4)},cA={name:j(`90° rotation`),execute:e=>iA(e,Math.PI/2),icon:`o-spreadsheet-Icon.ROTATION-90`,isActive:e=>aA(e,Math.PI/2)},lA={name:j(`-90° rotation`),execute:e=>iA(e,-Math.PI/2),icon:`o-spreadsheet-Icon.ROTATION-270`,isActive:e=>aA(e,-Math.PI/2)},uA={name:j(`-45° rotation`),execute:e=>iA(e,-Math.PI/4),icon:`o-spreadsheet-Icon.ROTATION-315`,isActive:e=>aA(e,-Math.PI/4)},dA={name:j(`Strikethrough`),execute:e=>mE(e,{strikethrough:!e.model.getters.getCurrentStyle().strikethrough}),icon:`o-spreadsheet-Icon.STRIKE`,isActive:e=>!!e.model.getters.getCurrentStyle().strikethrough},fA={name:j(`Font size`),children:kA(),icon:`o-spreadsheet-Icon.FONT_SIZE`},pA={name:j(`Alignment`),icon:`o-spreadsheet-Icon.ALIGN_LEFT`},mA={name:j(`Horizontal align`),icon:e=>IA(e)},hA={name:j(`Left`),shortcut:`Ctrl+Shift+L`,execute:e=>mE(e,{align:`left`}),isActive:e=>NA(e)===`left`,icon:`o-spreadsheet-Icon.ALIGN_LEFT`},gA={name:j(`Center`),shortcut:`Ctrl+Shift+E`,execute:e=>mE(e,{align:`center`}),isActive:e=>NA(e)===`center`,icon:`o-spreadsheet-Icon.ALIGN_CENTER`},_A={name:j(`Right`),shortcut:`Ctrl+Shift+R`,execute:e=>mE(e,{align:`right`}),isActive:e=>NA(e)===`right`,icon:`o-spreadsheet-Icon.ALIGN_RIGHT`},vA={name:j(`Vertical align`),icon:e=>LA(e)},yA={name:j(`Top`),execute:e=>mE(e,{verticalAlign:`top`}),isActive:e=>PA(e)===`top`,icon:`o-spreadsheet-Icon.ALIGN_TOP`},bA={name:j(`Middle`),execute:e=>mE(e,{verticalAlign:`middle`}),isActive:e=>PA(e)===`middle`,icon:`o-spreadsheet-Icon.ALIGN_MIDDLE`},xA={name:j(`Bottom`),execute:e=>mE(e,{verticalAlign:`bottom`}),isActive:e=>PA(e)===`bottom`,icon:`o-spreadsheet-Icon.ALIGN_BOTTOM`},SA={name:j(`Wrapping`),icon:`o-spreadsheet-Icon.WRAPPING_OVERFLOW`},CA={name:j(`Wrapping`),icon:e=>RA(e)},wA={name:j(`Overflow`),execute:e=>mE(e,{wrapping:`overflow`}),isActive:e=>FA(e)===`overflow`,icon:`o-spreadsheet-Icon.WRAPPING_OVERFLOW`},TA={name:j(`Wrap`),execute:e=>mE(e,{wrapping:`wrap`}),isActive:e=>FA(e)===`wrap`,icon:`o-spreadsheet-Icon.WRAPPING_WRAP`},EA={name:j(`Clip`),execute:e=>mE(e,{wrapping:`clip`}),isActive:e=>FA(e)===`clip`,icon:`o-spreadsheet-Icon.WRAPPING_CLIP`};j(`Text Color`),j(`Fill Color`);let DA={name:j(`Conditional formatting`),execute:UE,isEnabled:e=>!e.isSmall,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.CONDITIONAL_FORMAT`},OA={name:j(`Clear formatting`),shortcut:`Ctrl+<`,execute:e=>e.model.dispatch(`CLEAR_FORMATTING`,{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()}),icon:`o-spreadsheet-Icon.CLEAR_FORMAT`};function kA(){return ze.map(e=>({name:e.toString(),sequence:e,id:`font_size_${e}`,execute:t=>mE(t,{fontSize:e}),isActive:t=>MA(t,e)}))}function AA(e){let t=e.model.getters.getActivePosition();return e.model.getters.getPivotCellFromPosition(t).type===`VALUE`?!e.model.getters.getEvaluatedCell(t).format:!e.model.getters.getCell(t)?.format}function jA(e,t){let n=e.model.getters.getActivePosition();return e.model.getters.getPivotCellFromPosition(n).type===`VALUE`?e.model.getters.getEvaluatedCell(n).format===t:e.model.getters.getCell(n)?.format===t}function MA(e,t){return(e.model.getters.getCurrentStyle().fontSize||Ee)===t}function NA(e){let t=e.model.getters.getCurrentStyle();return t.align?t.align:e.model.getters.getActiveCell().defaultAlign}function PA(e){let t=e.model.getters.getCurrentStyle();return t.verticalAlign?t.verticalAlign:we}function FA(e){let t=e.model.getters.getCurrentStyle();return t.wrapping?t.wrapping:Te}function IA(e){switch(NA(e)){case`right`:return`o-spreadsheet-Icon.ALIGN_RIGHT`;case`center`:return`o-spreadsheet-Icon.ALIGN_CENTER`;default:return`o-spreadsheet-Icon.ALIGN_LEFT`}}function LA(e){switch(PA(e)){case`top`:return`o-spreadsheet-Icon.ALIGN_TOP`;case`middle`:return`o-spreadsheet-Icon.ALIGN_MIDDLE`;default:return`o-spreadsheet-Icon.ALIGN_BOTTOM`}}function RA(e){switch(FA(e)){case`wrap`:return`o-spreadsheet-Icon.WRAPPING_WRAP`;case`clip`:return`o-spreadsheet-Icon.WRAPPING_CLIP`;default:return`o-spreadsheet-Icon.WRAPPING_OVERFLOW`}}function zA(e){return aA(e,Math.PI/2)?`o-spreadsheet-Icon.ROTATION-90`:aA(e,-Math.PI/2)?`o-spreadsheet-Icon.ROTATION-270`:aA(e,Math.PI/4)?`o-spreadsheet-Icon.ROTATION-45`:aA(e,-Math.PI/4)?`o-spreadsheet-Icon.ROTATION-315`:`o-spreadsheet-Icon.ROTATION-0`}let BA={name:Fy.Custom,code:``,symbol:``,decimalPlaces:2,position:`after`};var VA=class extends wr{mutators=[`updateFormat`,`changeCategory`,`selectCurrency`,`changeCurrencyCode`,`changeCurrencySymbol`,`updateAvailableCurrencies`];invalidFormat=!1;isApplyingFormatFromPanel=!1;currentFormat=this.formatInSelection;category=this.detectFormatCategory(this.formatInSelection);selectedCurrencyIndex=0;currencyCode=``;currencySymbol=``;isAccountingFormat=!1;availableCurrencies=[BA,...Nk.getAll()];lastFormatInSelection=this.currentFormat;usedFormatForCategory={};constructor(e,t){super(e),t&&(this.category=t),this.model.selection.observe(this,{handleEvent:this.handleSelectionEvent.bind(this)}),this.onDispose(()=>{this.model.selection.unobserve(this)})}handle(){this.isApplyingFormatFromPanel||this.syncActiveFormat()}handleSelectionEvent(){this.getters.isGridSelectionActive()&&this.syncActiveFormat()}syncActiveFormat(){let e=this.formatInSelection;e!==this.lastFormatInSelection&&(this.setActiveFormat(e),this.lastFormatInSelection=e)}setActiveFormat(e){this.currentFormat=e,this.invalidFormat=!ou(e||``),this.category=this.detectFormatCategory(e)}get categories(){return[{label:j(`Number`),value:`number`},{label:j(`Date`),value:`date`},{label:j(`Currency`),value:`currency`}]}get formatInSelection(){let e=this.getters.getActivePosition();return this.getters.getPivotCellFromPosition(e).type===`VALUE`?this.getters.getEvaluatedCell(e).format:this.getters.getCell(e)?.format}detectFormatCategory(e){return e?Il(e)?`date`:e.includes(`$`)||e.includes(`"`)?`currency`:`number`:`number`}get formatProposals(){return this.category===`date`?this.dateFormatProposals:this.category===`currency`?this.currencyFormatProposals:this.category===`number`?this.numberFormatProposals:[]}get numberFormatProposals(){let e=[`0.00`,`0`,`#,##0`,`#,##0.00`,`0%`,`0.00%`,`0.00e`,`0.00;(0.00);-`].map(e=>({label:H(-1234.56,{format:e,locale:this.getters.getLocale()}),format:e}));return[{label:j(`Automatic`),format:void 0},{label:j(`Plain text`),format:`@`},...e]}get dateFormatProposals(){let e=this.getters.getLocale();return[e.dateFormat,e.timeFormat,e.dateFormat+` `+e.timeFormat,`dddd d mmmm yyyy hh:mm:ss a`,`yyyy-mm-dd`,`yyyy-mm-dd hh:mm:ss`,`dddd d mmmm yyyy`,`d mmmm yyyy`,`ddd d mmm yyyy`,`d mmm yyyy`,`mmmm yyyy`,`mmm yyyy`,`hhhh:mm:ss`,`qq yyyy`,`qqqq yyyy`].map(t=>({label:H(Wk,{format:t,locale:e}),format:t}))}get currencyFormatProposals(){let e=this.availableCurrencies[this.selectedCurrencyIndex],t=e.position,n=e.position===`before`?`after`:`before`,r=this.currencySymbol.trim()?this.currencySymbol:``,i=this.currencyCode.trim()?this.currencyCode:``,a=e.decimalPlaces;if(!r&&!i)return[];let o=[{symbol:r,position:t,decimalPlaces:0},{symbol:r,position:t,decimalPlaces:a},{symbol:r,position:t,decimalPlaces:0,code:i},{symbol:r,position:t,decimalPlaces:a,code:i},{symbol:r,position:n,decimalPlaces:0},{symbol:r,position:n,decimalPlaces:a},{symbol:r,position:n,decimalPlaces:0,code:i},{symbol:r,position:n,decimalPlaces:a,code:i}],s=new Set,c=this.getters.getLocale();return o.map(e=>{let t=this.isAccountingFormat?Wl(e):Ul(e);if(!(!e.symbol&&!e.code||s.has(t)))return s.add(t),{format:t,label:H(1e3,{format:t,locale:c})}}).filter(w)}get formatExamples(){let e=this.currentFormat,t=this.getters.getLocale();if(!e||!ou(e))return[];if(this.category===`date`)return[{label:j(`Sample:`),value:H(Wk,{format:e,locale:t})}];{let n=su(e),r=[{label:j(`Positive:`),value:H(1234.56,{format:e,locale:t})},{label:j(`Negative:`),value:H(-1234.56,{format:e,locale:t})},{label:j(`Zero:`),value:H(0,{format:e,locale:t})}];return n===4&&r.push({label:j(`Text:`),value:H(`Text`,{format:e,locale:t})}),r}}updateAvailableCurrencies(){this.availableCurrencies=[BA,...Nk.getAll()]}updateFormat(e){this.currentFormat=e,this.invalidFormat=!ou(e),this.invalidFormat||(this.lastFormatInSelection=e,this.isApplyingFormatFromPanel=!0,this.model.dispatch(`SET_FORMATTING_WITH_PIVOT`,{sheetId:this.getters.getActiveSheetId(),target:this.getters.getSelectedZones(),format:e||``}),this.isApplyingFormatFromPanel=!1)}changeCategory(e){if(e===this.category)return`noStateChange`;this.usedFormatForCategory[this.category]=this.currentFormat,this.category=e;let t=this.usedFormatForCategory[e]||this.formatProposals[0]?.format||``;this.updateFormat(t)}selectCurrency(e){let t=this.formatProposals.findIndex(e=>e.format===this.currentFormat);this.selectedCurrencyIndex=e;let n=this.availableCurrencies[e];this.currencyCode=n.code,this.currencySymbol=n.symbol,this.updateFormat(this.formatProposals[t]?.format||this.formatProposals[0]?.format||``)}changeCurrencyCode(e){let t=this.formatProposals.findIndex(e=>e.format===this.currentFormat);this.currencyCode=e,this.selectedCurrencyIndex=0,this.updateFormat(this.formatProposals[t]?.format||this.formatProposals[0]?.format||``)}changeCurrencySymbol(e){let t=this.formatProposals.findIndex(e=>e.format===this.currentFormat);this.currencySymbol=e,this.selectedCurrencyIndex=0,this.updateFormat(this.formatProposals[t]?.format||this.formatProposals[0]?.format||``)}toggleAccountingFormat(){let e=this.formatProposals.findIndex(e=>e.format===this.currentFormat);this.isAccountingFormat=!this.isAccountingFormat,this.updateFormat(this.formatProposals[e]?.format||this.formatProposals[0]?.format||``)}get invalidFormatMessage(){return this.invalidFormat?j(`The format entered is not valid.`):void 0}},HA=class extends t.Component{static template=`o-spreadsheet-MoreFormatsPanel`;static props={onCloseSidePanel:Function,category:{type:String,optional:!0}};static components={BadgeSelection:aO,Section:Z,TextInput:BD,Checkbox:IT,Select:Ty};store;setup(){this.store=hr(VA,this.props.category),(0,t.onWillStart)(()=>this.loadCurrencies()),(0,t.onWillUpdateProps)(e=>{e.category&&e.category!==this.props.category&&this.store.changeCategory(e.category)})}async loadCurrencies(){Nk.getAll().length===0&&((await(this.env.loadCurrencies?.()??Promise.resolve([]))).forEach((e,t)=>{Nk.replace(t.toString(),e)}),this.store.updateAvailableCurrencies())}currencyDisplayName(e){return e.name+(e.code?` (${e.code})`:``)}updateSelectCurrency(e){let t=parseInt(e,10);this.store.selectCurrency(t)}isFormatSelected(e){return e===this.store.currentFormat}get availableCurrenciesOptions(){return this.store.availableCurrencies.map((e,t)=>({value:t.toString(),label:this.currencyDisplayName(e)}))}};function UA(e,t){GA(e,e.model.dispatch(`CREATE_NAMED_RANGE`,t))}function WA(e,t){GA(e,e.model.dispatch(`UPDATE_NAMED_RANGE`,t))}function GA(e,t){t.isSuccessful||(t.isCancelledBecause(`NamedRangeNameAlreadyExists`)?e.raiseError(j(`A named range with this name already exists.`)):t.isCancelledBecause(`NamedRangeInvalidName`)?e.raiseError(j(`The named range name is invalid. Valid names can contain letters, digits, underscores, and periods. The name cannot be only a number, TRUE, or FALSE.`)):t.isCancelledBecause(`NamedRangeNameLooksLikeCellReference`)?e.raiseError(j(`A named range name cannot resemble a cell reference.`)):t.isCancelledBecause(`NamedRangeNotFound`)&&e.raiseError(j(`The named range to update was not found.`)))}var KA=class extends t.Component{static template=`o-spreadsheet-NamedRangePreview`;static props={namedRange:Object};static components={SelectionInput:jT,TextInput:BD};state=(0,t.useState)({});ref=(0,t.useRef)(`namedRangePreview`);setup(){uk(this.ref,this)}get highlights(){return this.state.isSelectionInputFocused?[]:[{range:this.props.namedRange.range,color:ee,noFill:!0}]}deleteNamedRange(){this.env.model.dispatch(`DELETE_NAMED_RANGE`,{name:this.props.namedRange.name})}updateNamedRangeName(e){e=e.replace(/ /g,`_`),WA(this.env,{oldRangeName:this.props.namedRange.name,newRangeName:e,ranges:[this.env.model.getters.getRangeData(this.props.namedRange.range)]})}onSelectionInputChanged(e){this.state.currentRange=e[0]}onSelectionInputConfirmed(){if(this.state.isSelectionInputFocused=!1,this.state.currentRange){let e=this.env.model.getters.getRangeFromSheetXC(this.env.model.getters.getActiveSheetId(),this.state.currentRange);if(e.invalidSheetName||e.invalidXc)return;WA(this.env,{oldRangeName:this.props.namedRange.name,newRangeName:this.props.namedRange.name,ranges:[this.env.model.getters.getRangeData(e)]})}}onSelectionInputFocused(){this.state.isSelectionInputFocused=!0}get rangeString(){return this.env.model.getters.getRangeString(this.props.namedRange.range,this.env.model.getters.getActiveSheetId())}},qA=class extends t.Component{static template=`o-spreadsheet-NamedRangesPanel`;static props={onCloseSidePanel:Function};static components={NamedRangePreview:KA,SelectionInput:jT,TextInput:BD};get namedRanges(){return this.env.model.getters.getNamedRanges()}addNewNamedRange(){let e=this.namedRanges.map(e=>e.name),t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getSelectedZone();this.env.model.dispatch(`CREATE_NAMED_RANGE`,{name:Kt(j(`Named_Range`),e,{compute:(e,t)=>`${e}${t}`}),ranges:[this.env.model.getters.getRangeDataFromZone(t,n)]})}},JA=class extends wr{pivotId;initialMeasure;mutators=[`cancelMeasureDisplayEdition`,`updateMeasureDisplayType`,`updateMeasureDisplayField`,`updateMeasureDisplayValue`];measureDisplay;constructor(e,t,n){super(e),this.pivotId=t,this.initialMeasure=n,this.measureDisplay=n.display||{type:`no_calculations`}}updateMeasureDisplayType(e){this.updatePivotMeasureDisplay(this.getMeasureDisplay(e,this.measureDisplay.fieldNameWithGranularity,this.measureDisplay.value))}updateMeasureDisplayField(e){this.updatePivotMeasureDisplay(this.getMeasureDisplay(this.measureDisplay.type,e,this.measureDisplay.value))}updateMeasureDisplayValue(e){this.updatePivotMeasureDisplay(this.getMeasureDisplay(this.measureDisplay.type,this.measureDisplay.fieldNameWithGranularity,e))}updatePivotMeasureDisplay(e){let t=x(this.model.getters.getPivotCoreDefinition(this.pivotId)),n=this.getMeasureIndex(this.initialMeasure.id,t),r={...t.measures[n],display:e};t.measures[n]=r,this.model.dispatch(`UPDATE_PIVOT`,{pivot:t,pivotId:this.pivotId}).isSuccessful&&(this.measureDisplay=e)}getMeasureDisplay(e,t,n){switch(e){case`no_calculations`:case`%_of_grand_total`:case`%_of_col_total`:case`%_of_row_total`:case`%_of_parent_row_total`:case`%_of_parent_col_total`:case`index`:return{type:e};case`%_of_parent_total`:case`running_total`:case`%_running_total`:case`rank_asc`:case`rank_desc`:return t||=this.fields[0]?.nameWithGranularity,{type:e,fieldNameWithGranularity:t};case`%_of`:case`difference_from`:case`%_difference_from`:t||=this.fields[0]?.nameWithGranularity;let r=this.getPossibleValues(t);return(n===void 0||!r.find(e=>e.value===n))&&(n=Uh),{type:e,fieldNameWithGranularity:t,value:n??`(previous)`}}}getMeasureIndex(e,t){let n=t.measures.findIndex(t=>t.id===e);if(n===-1)throw Error(`Measure with id ${e} not found in pivot.`);return n}get doesDisplayNeedsField(){return[`%_of_parent_total`,`running_total`,`%_running_total`,`rank_asc`,`rank_desc`].includes(this.measureDisplay.type)||this.doesDisplayNeedsValue}get fields(){let e=this.getters.getPivot(this.pivotId).definition;return[...e.columns,...e.rows].map(e=>({...e,displayName:Ng(e)}))}get doesDisplayNeedsValue(){return this.isDisplayValueDependant(this.measureDisplay)}isDisplayValueDependant(e){return[`%_of`,`difference_from`,`%_difference_from`].includes(e.type)}get values(){let e=this.measureDisplay;return this.isDisplayValueDependant(e)?this.getPossibleValues(e.fieldNameWithGranularity):[]}getPossibleValues(e){let t=[{value:Uh,label:j(`(previous)`)},{value:Wh,label:j(`(next)`)}],n=this.fields.find(t=>t.nameWithGranularity===e);if(!n)return[];let r=this.getters.getPivot(this.pivotId).getPossibleFieldValues(n);return[...t,...r]}cancelMeasureDisplayEdition(){let e=x(this.model.getters.getPivotCoreDefinition(this.pivotId)),t=this.getMeasureIndex(this.initialMeasure.id,e);e.measures[t]={...e.measures[t],display:this.initialMeasure.display},this.model.dispatch(`UPDATE_PIVOT`,{pivot:e,pivotId:this.pivotId})}},YA=class extends t.Component{static template=`o-spreadsheet-PivotMeasureDisplayPanel`;static props={onCloseSidePanel:Function,pivotId:String,measure:Object};static components={Section:Z,Checkbox:IT,RadioSelection:cO,Select:Ty};measureDisplayTypeLabels=Hy.labels;measureDisplayDescription=Hy.documentation;store;setup(){this.store=hr(JA,this.props.pivotId,this.props.measure)}onSave(){this.env.replaceSidePanel(`PivotSidePanel`,`pivot_measure_display_${this.props.pivotId}_${this.props.measure.id}`,{pivotId:this.props.pivotId})}onCancel(){this.store.cancelMeasureDisplayEdition(),this.env.replaceSidePanel(`PivotSidePanel`,`pivot_measure_display_${this.props.pivotId}_${this.props.measure.id}`,{pivotId:this.props.pivotId})}get fieldChoices(){return this.store.fields.map(e=>({value:e.nameWithGranularity,label:e.displayName}))}get measureDisplayTypeOptions(){return Object.keys(this.measureDisplayTypeLabels).map(e=>({value:e,label:this.measureDisplayTypeLabels[e]}))}};function XA(e,t){let n=e.getActiveSheetId();return ar(ZA(e,t).map(D)).map(t=>({range:e.getRangeFromZone(n,t),noFill:!0,color:ee}))}function ZA(e,t){let n=[],r=e.getActiveSheetId();for(let i of e.getSheetViewVisibleCols())for(let a of e.getSheetViewVisibleRows()){let o={sheetId:r,col:i,row:a};e.getPivotIdsFromPosition(o).includes(t)&&n.push(o)}return n}var QA=class extends t.Component{static template=`o-spreadsheet-PivotDeferUpdate`;static props={deferUpdate:Boolean,isDirty:Boolean,toggleDeferUpdate:Function,discard:Function,apply:Function};static components={Section:Z,Checkbox:IT};get deferUpdatesLabel(){return j(`Defer updates`)}get deferUpdatesTooltip(){return j(`Changing the pivot definition requires to reload the data. It may take some time.`)}},$A=class extends t.Component{static template=`o-spreadsheet-PivotCustomGroupsCollapsible`;static props={pivotId:String,customField:Object,onCustomFieldUpdated:Function};static components={SidePanelCollapsible:ww,TextInput:BD,Checkbox:IT};get groups(){return this.props.customField.groups.sort((e,t)=>!e.isOtherGroup&&!t.isOtherGroup?0:e.isOtherGroup?1:-1)}get hasOthersGroup(){return this.props.customField.groups.some(e=>e.isOtherGroup)}addOthersGroup(){if(this.hasOthersGroup)return;let e={name:Ig(j(`Others`),this.props.customField),values:[],isOtherGroup:!0},t=[...this.props.customField.groups,e];this.updateCustomField({...this.props.customField,groups:t})}onDeleteGroup(e){let t=[...this.props.customField.groups];t.splice(e,1),this.updateCustomField({...this.props.customField,groups:t})}onRenameGroup(e,t){let n=x(this.props.customField.groups),r=n[e];r&&(r.name=Ig(t,this.props.customField),this.updateCustomField({...this.props.customField,groups:n}))}updateCustomField(e){let t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);this.props.onCustomFieldUpdated({customFields:{...t.customFields,[e.name]:e}})}};function ej(e,t,n,r){let i=[];e=e.toLowerCase();for(let a of e){let e=t.toLocaleLowerCase().indexOf(a);e!==-1&&(i.push({value:t.slice(0,e),color:``},{value:t[e],color:n,classes:[r]}),t=t.slice(e+1))}return i.push({value:t}),i.filter(e=>e.value)}var tj=class extends t.Component{static template=`o-spreadsheet-AddDimensionButton`;static components={Popover:by,TextValueProvider:Rw};static props={onFieldPicked:Function,fields:Array,slots:{type:Object,optional:!0}};buttonRef=(0,t.useRef)(`button`);popover=(0,t.useState)({isOpen:!1});search=(0,t.useState)({input:``});autoComplete;setup(){this.autoComplete=hr(uT),this.autoComplete.useProvider(this.getProvider()),(0,t.useExternalListener)(window,`click`,e=>{e.target!==this.buttonRef.el&&(this.popover.isOpen=!1)}),RD({refName:`autofocus`})}getProvider(){return{proposals:this.proposals,autoSelectFirstProposal:!1,selectProposal:e=>{let t=this.props.fields.find(t=>t.string===e.text);t&&this.pickField(t)}}}get proposals(){let e;return e=this.search.input?fd(this.search.input,this.props.fields,e=>e.string===e.name?e.string:e.string+e.name):this.props.fields,e.map(e=>{let t=e.string;return{text:t,fuzzySearchKey:t,htmlContent:ej(this.search.input,t,ue,`o-semi-bold`)}})}get popoverProps(){let{x:e,y:t,width:n,height:r}=this.buttonRef.el.getBoundingClientRect();return{anchorRect:{x:e,y:t,width:n,height:r},positioning:`bottom-left`}}updateSearch(e){this.search.input=e,this.autoComplete.useProvider(this.getProvider())}pickField(e){this.props.onFieldPicked(e.name),this.togglePopover()}togglePopover(){this.popover.isOpen=!this.popover.isOpen,this.search.input=``,this.autoComplete.useProvider(this.getProvider())}onKeyDown(e){switch(e.key){case`Enter`:let t=this.autoComplete.provider?.proposals;t?.length===1&&this.autoComplete.provider?.selectProposal(t[0]);let n=this.autoComplete.selectedProposal;n&&this.autoComplete.provider?.selectProposal(n);break;case`ArrowUp`:case`ArrowDown`:this.autoComplete.moveSelection(e.key===`ArrowDown`?`next`:`previous`);break;case`Escape`:this.popover.isOpen=!1;break;default:break}}},nj=class extends t.Component{static template=`o-spreadsheet-PivotDimension`;static props={dimension:Object,onRemoved:{type:Function,optional:!0},onNameUpdated:{type:Function,optional:!0},slots:{type:Object,optional:!0}};static components={CogWheelMenu:KD,TextInput:BD};updateName(e){this.props.onNameUpdated?.(this.props.dimension,e===``||e.startsWith(`=`)?void 0:e)}get dimensionDisplayName(){let e=this.props.dimension.displayName;return Wg(e)}},rj=class extends t.Component{static template=`o-spreadsheet-PivotDimensionGranularity`;static props={dimension:Object,onUpdated:Function,availableGranularities:Set,allGranularities:Array};static components={Select:Ty};periods=bg;get granularityOptions(){let e=this.props.dimension.granularity||`month`;return this.props.allGranularities.filter(t=>this.props.availableGranularities.has(t)||t===e).map(e=>({value:e,label:this.periods[e]}))}},ij=class extends t.Component{static template=`o-spreadsheet-PivotDimensionOrder`;static props={dimension:Object,onUpdated:Function};static components={Select:Ty};get orderSelectOptions(){let e=[{value:`asc`,label:j(`Ascending`)},{value:`desc`,label:j(`Descending`)}];return this.props.dimension.type===`date`?e:[{value:``,label:j(`Unsorted`)},...e]}};function aj(e,t){return{sequence:0,autoSelectFirstProposal:!0,getProposals(n){let r=e.measures.filter(e=>e!==t).map(e=>{let t=tt(e.id);return{text:t,description:e.displayName,htmlContent:[{value:t,color:ve}],fuzzySearchKey:e.displayName+t+e.fieldName}}),i=e.rows.concat(e.columns).map(e=>{let t=tt(e.nameWithGranularity);return{text:t,description:e.displayName,htmlContent:[{value:t,color:ve}],fuzzySearchKey:e.displayName+t+e.fieldName}});return r.concat(i)},selectProposal(e,t){let n=e.end;e.type===`SYMBOL`&&(n=e.start);let r=e.end;this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t.text)}}}var oj=class extends t.Component{static template=`o-spreadsheet-PivotMeasureEditor`;static components={PivotDimension:nj,StandaloneComposer:pT,Select:Ty};static props={definition:Object,measure:Object,onMeasureUpdated:Function,onRemoved:Function,generateMeasureId:Function,aggregators:Object,pivotId:String};getMeasureAutocomplete(){return aj(this.props.definition,this.props.measure)}updateMeasureFormula(e){this.props.onMeasureUpdated({...this.props.measure,computedBy:{sheetId:this.env.model.getters.getActiveSheetId(),formula:e[0]===`=`?e:`=`+e}})}updateAggregator(e){this.props.onMeasureUpdated({...this.props.measure,aggregator:e,id:this.props.generateMeasureId(this.props.measure.fieldName,e)})}updateName(e,t){this.props.measure.computedBy&&t?this.props.onMeasureUpdated({...this.props.measure,userDefinedName:t,id:this.props.generateMeasureId(t,this.props.measure.aggregator),fieldName:t}):this.props.onMeasureUpdated({...this.props.measure,userDefinedName:t})}toggleMeasureVisibility(){this.props.onMeasureUpdated({...this.props.measure,isHidden:!this.props.measure.isHidden})}openShowValuesAs(){this.env.replaceSidePanel(`PivotMeasureDisplayPanel`,`pivot_key_${this.props.pivotId}`,{pivotId:this.props.pivotId,measure:this.props.measure})}getColoredSymbolToken(e){if(e.type!==`SYMBOL`)return;let t=et(e.value,`'`);if(this.props.definition.columns.some(e=>e.nameWithGranularity===t)||this.props.definition.rows.some(e=>e.nameWithGranularity===t)||this.props.definition.measures.some(e=>e.id===t&&e.id!==this.props.measure.id))return ve}get isCalculatedMeasureInvalid(){return Rc.IsBadExpression(this.props.measure.computedBy?.formula??``)}get aggregatorOptions(){let e=this.props.aggregators[this.props.measure.type],t=Object.keys(e).map(t=>({value:t,label:e[t]}));return this.props.measure.computedBy?[...t,{value:``,label:j(`Compute from totals`)}]:t}getMeasureDescription(e){let t=e.display;if(!t||t.type===`no_calculations`)return``;let n=this.env.model.getters.getPivot(this.props.pivotId),r=[...n.definition.columns,...n.definition.rows].find(e=>e.nameWithGranularity===t.fieldNameWithGranularity),i=r?Ng(r):``,a=t.value?.toString()||``;return Hy.descriptions[t.type](i,a)}},sj=class extends t.Component{static template=`o-spreadsheet-PivotSortSection`;static components={Section:Z};static props={definition:Object,pivotId:String};get hasValidSort(){let e=this.env.model.getters.getPivot(this.props.pivotId);return!!this.props.definition.sortedColumn&&Fg(this.props.definition.sortedColumn,e)}get sortDescription(){return j(`Sorted on column (%(ascOrDesc)s):`,{ascOrDesc:this.props.definition.sortedColumn?.order===`asc`?j(`ascending`):j(`descending`)})}get sortValuesAndFields(){let e=this.props.definition.sortedColumn;if(!e)return[];let t=this.env.model.getters.getPivot(this.props.pivotId),n=this.env.model.getters.getLocale(),r=[],i=[];for(let a of e.domain){r.push(a);let{value:e,format:o}=t.getPivotHeaderValueAndFormat(r),s=H(e,{format:o,locale:n}),c=t.definition.getDimension(a.field);i.push({field:Ng(c),value:s})}e.domain.length===0&&i.push({value:j(`Total`)});let a=t.getMeasure(e.measure).displayName;return i.push({value:a,field:j(`Measure`)}),i}},cj=class extends t.Component{static template=`o-spreadsheet-PivotLayoutConfigurator`;static components={AddDimensionButton:tj,PivotDimension:nj,PivotDimensionOrder:ij,PivotDimensionGranularity:rj,PivotMeasureEditor:oj,PivotSortSection:sj,PivotCustomGroupsCollapsible:$A};static props={definition:Object,onDimensionsUpdated:Function,unusedGroupableFields:Array,measureFields:Array,unusedGranularities:Object,dateGranularities:Array,datetimeGranularities:Array,getScrollableContainerEl:{type:Function,optional:!0},pivotId:String};dimensionsRef=(0,t.useRef)(`pivot-dimensions`);dragAndDrop=wT();AGGREGATORS=_g;composerFocus;isDateOrDatetimeField=Cg;setup(){this.composerFocus=O(Er)}startDragAndDrop(e,t){if(t.button!==0||t.target.tagName===`SELECT`)return;let n=this.getDimensionElementsRects(),{columns:r,rows:i}=this.props.definition,a=[...r.map(e=>e.nameWithGranularity),`__rows_title__`,...i.map(e=>e.nameWithGranularity)],o=r.concat(i),s=a.map((e,t)=>({id:e,size:n[t+1].height,position:n[t+1].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.nameWithGranularity,initialMousePosition:t.clientY,items:s,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{let n=a.findIndex(t=>t===e);if(n===t)return;let r=[...a];r.splice(n,1),r.splice(t,0,e);let i=r.slice(0,r.indexOf(`__rows_title__`)),s=r.slice(r.indexOf(`__rows_title__`)+1);this.props.onDimensionsUpdated({columns:i.map(e=>o.find(t=>t.nameWithGranularity===e)).filter(w),rows:s.map(e=>o.find(t=>t.nameWithGranularity===e)).filter(w)})}})}getGranularitiesFor(e){return Cg(e)?e.type===`date`?this.props.dateGranularities:this.props.datetimeGranularities:[]}startDragAndDropMeasures(e,t){if(t.button!==0||t.target.tagName===`SELECT`||t.target.tagName===`INPUT`||this.composerFocus.focusMode!==`inactive`)return;let n=this.getDimensionElementsRects(),{measures:r,columns:i,rows:a}=this.props.definition,o=r.map(e=>e.id),s=3+i.length+a.length,c=o.map((e,t)=>({id:e,size:n[t+s].height,position:n[t+s].y}));this.dragAndDrop.start(`vertical`,{draggedItemId:e.id,initialMousePosition:t.clientY,items:c,scrollableContainerEl:this.props.getScrollableContainerEl?.()||this.dimensionsRef.el,onDragEnd:(e,t)=>{let n=o.findIndex(t=>t===e);if(n===t)return;let i=[...o];i.splice(n,1),i.splice(t,0,e),this.props.onDimensionsUpdated({measures:i.map(e=>r.find(t=>t.id===e)).filter(w)})}})}getDimensionElementsRects(){return Array.from(this.dimensionsRef.el.children).map(e=>{let t=getComputedStyle(e),n=e.getBoundingClientRect();return{x:n.x,y:n.y,width:n.width+parseInt(t.marginLeft||`0`)+parseInt(t.marginRight||`0`),height:n.height+parseInt(t.marginTop||`0`)+parseInt(t.marginBottom||`0`)}})}removeDimension(e){let{columns:t,rows:n}=this.props.definition;this.props.onDimensionsUpdated({columns:t.filter(t=>t.nameWithGranularity!==e.nameWithGranularity),rows:n.filter(t=>t.nameWithGranularity!==e.nameWithGranularity)})}removeMeasureDimension(e){let{measures:t}=this.props.definition;this.props.onDimensionsUpdated({measures:t.filter(t=>t.id!==e.id)})}addColumnDimension(e){let{columns:t}=this.props.definition;this.props.onDimensionsUpdated({columns:t.concat([{fieldName:e,order:`asc`}])})}addRowDimension(e){let{rows:t}=this.props.definition;this.props.onDimensionsUpdated({rows:t.concat([{fieldName:e,order:`asc`}])})}addMeasureDimension(e){let{measures:t}=this.props.definition,n=this.getDefaultMeasureAggregator(e);this.props.onDimensionsUpdated({measures:t.concat([{id:this.getMeasureId(e,n),fieldName:e,aggregator:n}])})}updateMeasure(e,t){let{measures:n}=this.props.definition,r={measures:Gg(e,t,n)};this.props.definition.sortedColumn?.measure===e.id&&(r.sortedColumn={...this.props.definition.sortedColumn,measure:t.id}),this.props.onDimensionsUpdated(r)}getMeasureId(e,t){let n=e.replaceAll(`'`,``)+(t?`:${t}`:``),r=n,i=2;for(;this.props.definition.measures.some(e=>e.id===r);)r=`${n}:${i}`,i++;return r}getDefaultMeasureAggregator(e){let t=this.props.measureFields.find(t=>t.name===e);return t?.aggregator?t.aggregator:`count`}addCalculatedMeasure(){let{measures:e}=this.props.definition,t=this.env.model.getters.generateNewCalculatedMeasureName(e);this.props.onDimensionsUpdated({measures:e.concat([{id:this.getMeasureId(t,`sum`),fieldName:t,aggregator:`sum`,computedBy:{sheetId:this.env.model.getters.getActiveSheetId(),formula:`=0`}}])})}getCustomField(e){return this.env.model.getters.getPivotCoreDefinition(this.props.pivotId).customFields?.[e.nameWithGranularity]}updateOrder(e,t){let{rows:n,columns:r}=this.props.definition;this.props.onDimensionsUpdated({rows:n.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,order:t||void 0}:n),columns:r.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,order:t||void 0}:n)})}updateGranularity(e,t){let{rows:n,columns:r}=this.props.definition;this.props.onDimensionsUpdated({rows:n.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,granularity:t}:n),columns:r.map(n=>n.nameWithGranularity===e.nameWithGranularity?{...n,granularity:t}:n)})}getHugeDimensionErrorMessage(e){let t=this.env.model.getters.getPivot(this.props.pivotId).getPossibleFieldValues(e);return t.length>100?j(`This dimension contains a lot of values (%s), and might slow down the pivot table.`,t.length):void 0}},lj=class extends t.Component{static template=`o-spreadsheet-PivotTitleSection`;static components={CogWheelMenu:KD,Section:Z,TextInput:BD};static props={pivotId:String,flipAxis:Function};get cogWheelMenuItems(){return[{name:j(`Flip axes`),icon:`o-spreadsheet-Icon.EXCHANGE`,execute:this.props.flipAxis,isEnabledOnLockedSheet:!0},{name:j(`Duplicate`),icon:`o-spreadsheet-Icon.COPY`,execute:()=>this.duplicatePivot(),isEnabledOnLockedSheet:!0},{name:j(`Delete`),icon:`o-spreadsheet-Icon.TRASH`,execute:()=>this.delete(),isEnabledOnLockedSheet:!0}]}get name(){return this.env.model.getters.getPivotName(this.props.pivotId)}get displayName(){return this.env.model.getters.getPivotDisplayName(this.props.pivotId)}duplicatePivot(){let e=this.env.model.uuidGenerator.smallUuid(),t=this.env.model.uuidGenerator.smallUuid(),n=this.env.model.dispatch(`DUPLICATE_PIVOT_IN_NEW_SHEET`,{pivotId:this.props.pivotId,newPivotId:e,newSheetId:t}),r;r=n.isSuccessful?j(`Pivot duplicated.`):n.isCancelledBecause(`PivotInError`)?j(`Cannot duplicate a pivot in error.`):j(`Pivot duplication failed.`);let i=n.isSuccessful?`success`:`danger`;this.env.notifyUser({text:r,sticky:!1,type:i}),n.isSuccessful&&this.env.openSidePanel(`PivotSidePanel`,{pivotId:e})}delete(){this.env.askConfirmation(j(`Are you sure you want to delete this pivot?`),()=>{this.env.model.dispatch(`REMOVE_PIVOT`,{pivotId:this.props.pivotId})})}onNameChanged(e){let t=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);this.env.model.dispatch(`UPDATE_PIVOT`,{pivotId:this.props.pivotId,pivot:{...t,name:e}})}},uj=class{measures;columns;rows;sortedColumn;collapsedDomains;customFields;constructor(e,t){this.columns=e.columns.map(e=>this.createPivotDimension(t,e)),this.rows=e.rows.map(e=>this.createPivotDimension(t,e)),this.measures=e.measures.map(e=>this.createMeasure(t,e)),this.sortedColumn=e.sortedColumn,this.collapsedDomains=e.collapsedDomains,this.customFields=e.customFields}getDimension(e){let t=this.columns.find(t=>t.nameWithGranularity===e)||this.rows.find(t=>t.nameWithGranularity===e);if(!t)throw new N(j(`Dimension %s does not exist`,e));return t}getMeasure(e){let t=this.measures.find(t=>t.id===e);if(!t)throw new N(j(`Field %s is not a measure`,e));return t}get invalidAggregatorsForCustomField(){return[]}createMeasure(e,t){let n=t.fieldName,r=n===`__count`?{name:`__count`,string:j(`Count`),type:`integer`,aggregator:`sum`}:e[n],i=t.aggregator,a=!!(r||t.computedBy);for(let t of[...this.rows,...this.columns])if(e[t.fieldName]?.isCustomField&&this.invalidAggregatorsForCustomField.includes(i)){a=!1;break}return{id:t.id,get displayName(){return t.userDefinedName??r?.string??t.fieldName},userDefinedName:t.userDefinedName,fieldName:n,aggregator:i,type:n===`__count`?`integer`:r?.type??`integer`,isValid:a,isHidden:t.isHidden,format:t.format,computedBy:t.computedBy,display:t.display}}createPivotDimension(e,t){let n=e[t.fieldName],r=n?.type??`integer`,i=n&&Cg(n)?t.granularity:void 0;return{displayName:n?.string??t.fieldName,nameWithGranularity:t.fieldName+(i?`:${i}`:``),fieldName:t.fieldName,granularity:i,type:n?.isCustomField?`custom`:r,order:t.order,isValid:!!n,isCustomField:!!n?.isCustomField,customGroups:n?.customGroups,parentField:n?.parentField}}},dj=class extends uj{range;constructor(e,t,n){if(super(e,t),e.dataSet){let{sheetId:t,zone:r}=e.dataSet;this.range=n.getRangeFromZone(t,r)}}};function fj(e,t){let{colDomain:n,rowDomain:r}=mj(e,t);return[...n,...r.slice(0,r.length-1)]}function pj(e,t){let{colDomain:n,rowDomain:r}=mj(e,t);return[...n.slice(0,n.length-1),...r]}function mj(e,t){let n=e.definition.rows.map(e=>e.nameWithGranularity),r=t.filter(e=>n.includes(e.field)),i=e.definition.columns.map(e=>e.nameWithGranularity);return{colDomain:t.filter(e=>i.includes(e.field)),rowDomain:r}}function hj(e,t,n){return t===`column`?mj(e,n).colDomain:mj(e,n).rowDomain}function gj(e,t){return t.find(t=>t.field===e)?.value}function _j(e,t){for(let n of t)if(e.definition.rows.find(e=>e.nameWithGranularity===n.field)===void 0&&e.definition.columns.find(e=>e.nameWithGranularity===n.field)===void 0)return!1;let{rowDomain:n,colDomain:r}=mj(e,t);return vj(n,e.getExpandedTableStructure().getRowTree())&&vj(r,e.getExpandedTableStructure().getColTree())}function vj(e,t){return yj(e,t)!==void 0}function yj(e,t,n){let r=t;for(let t of e){let e=r.find(e=>e.value===t.value);if(!e)return;if(e.field===n)return r;r=e.children}return r}function bj(e,t,n){let{rowDomain:r,colDomain:i}=mj(e,n);if(Cj(e,t)===`row`){let e=r.findIndex(e=>e.field===t);if(e===-1)return n;r=r.slice(0,e+1)}else{let e=i.findIndex(e=>e.field===t);if(e===-1)return n;i=i.slice(0,e+1)}return[...r,...i]}function xj(e,t,n){e=x(e);let r=e.find(e=>e.field===t);return r&&(r.value=n),e}function Sj(e,t){return t.some(t=>t.field===e)}function Cj(e,t){if(e.definition.rows.map(e=>e.nameWithGranularity).includes(t))return`row`;if(e.definition.columns.map(e=>e.nameWithGranularity).includes(t))return`column`;throw Error(`Field ${t} not found in pivot`)}function wj(e,t,n,r){let i=Cj(e,n),a=i===`row`?e.getExpandedTableStructure().getRowTree():e.getExpandedTableStructure().getColTree(),o=yj(hj(e,i,t),a,n)?.map(e=>e.value)??[],s=gj(n,t);if(s===void 0)return;let c=o.indexOf(s);if(!(s===void 0||c===-1))return xj(t,n,o[S(c+(r===`(previous)`?-1:1),0,o.length-1)])}function Tj(e){return e?e.map(Ej).join(`, `):``}function Ej(e){return e?`${e.field}=${e.value}`:``}function Dj(e,t){let n=e.findIndex(e=>e.field===t);if(n===-1)return``;let r=e.slice(0,n),i=e.at(-1);return Tj(i.field===t?r:[...r,i])}function Oj(e,t){let n=e.findIndex(e=>e.field===t);return n===-1?``:Tj([...e.slice(0,n),...e.slice(n+1)])}function kj(e,t,n){let r=[...e],i=[...t];r.sort((e,t)=>n([...i,e],[...i,t]));for(let t of e)t.children=kj(t.children,[...i,t],n);return r}function Aj(e,t){return e.length>t.length&&t.every((t,n)=>T(t,e[n]))}var jj=class{columns;rows;rowFields;measures;fieldsType;maxIndent;pivotCells={};rowTree;colTree;isSorted=!1;constructor(e,t,n,r,i={COL:[],ROW:[]}){this.measures=n,this.fieldsType=r,i.COL.length&&(e=this.removeCollapsedColumns(e,n,i.COL)),this.columns=e.map(e=>{let t=0;return e.map(e=>(e={...e,offset:t},t+=e.width,e))}),this.rows=t.filter(e=>!this.isParentCollapsed(i.ROW,e));let a=Math.max(...t.map(e=>e.fields.length)),o=t.find(e=>e.fields.length===a);this.rowFields=o?[...o.fields]:[],this.maxIndent=Math.max(...this.rows.map(e=>e.indent)),this.rowTree=xt(()=>this.buildRowsTree()),this.colTree=xt(()=>this.buildColumnsTree())}removeCollapsedColumns(e,t,n){let r=(n,r)=>{let i=this.getDomain(n),a=e[r],o=a.findIndex(e=>Aj(this.getDomain(e),i)),s=a.findLastIndex(e=>Aj(this.getDomain(e),i)),c=r===e.length-1,l=t.map(e=>({fields:c?[...n.fields,`measure`]:[],values:c?[...n.values,e]:[],width:1,offset:0,collapsedHeader:!c}));a.splice(o,s-o+1,...l)};return e.map((i,a)=>{for(let o of i){if(a>=e.length-2)return i;let s=this.getDomain(o);if(n.some(e=>T(s,e))){o.width=t.length;for(let t=a+1;t<e.length;t++)r(o,t)}}return i})}isParentCollapsed(e,t){let n=this.getDomain(t);return e.some(e=>Aj(n,e))}getNumberOfDataColumns(){return this.columns.at(-1)?.length||0}getSkippedRows(e){let t=new Set,n=this.getColHeadersHeight();if(!e.displayColumnHeaders)for(let e=0;e<n-1;e++)t.add(e);if(e.displayMeasuresRow||t.add(n-1),e.tabularForm)for(let e=0;e<this.rows.length;e++){let r=this.rows[e].indent;r!==0&&r!==this.maxIndent&&t.add(e+n)}return t}getPivotCells(e=pg){let t=JSON.stringify(e);if(!this.pivotCells[t]){let{displayTotals:n}=e,r=this.rows.length,i=this.getNumberOfDataColumns(),a=r+this.getColHeadersHeight(),o=i+this.getRowHeadersWidth(e);!n&&r!==1&&--a,!n&&i!==this.measures.length&&(o-=this.measures.length);let s=[],c=this.getSkippedRows(e);for(let t=0;t<o;t++){s.push([]);for(let n=0;n<a;n++){if(c.has(n))continue;let r=this.getPivotCell(t,n,e);s[t].push(r)}}this.pivotCells[t]=s}return this.pivotCells[t]}getRowTree(){return this.rowTree()}getColTree(){return this.colTree()}isTotalRow(e){return this.rows[e].indent!==this.maxIndent}getPivotCell(e,t,n){let r=this.getColHeadersHeight(),i=this.getRowHeadersWidth(n),a=n.tabularForm,o=t<r-1&&e>=i,s=t===r-1&&e>=i,c=t>r-1&&e<i,l=t>r-1&&e>=i,u=a&&t===r-1&&e<i;if(a&&c){let n=t-r,i=this.getDomain(this.rows[n]).slice(0,e+1);return i.length===0&&e!==0?Mj:{type:`HEADER`,domain:i,dimension:`ROW`}}else if(a&&u)return{type:`ROW_GROUP_NAME`,rowField:this.rowFields[e]};else if(s){let n=e-i,r=this.getColHeaderDomain(n,t);if(!r)return Mj;let a=r.at(-1)?.value?.toString()||``;return{type:`MEASURE_HEADER`,domain:r.slice(0,-1),measure:a}}else if(o){let n=e-i,r=this.getColHeaderDomain(n,t);return r?{type:`HEADER`,domain:r,dimension:`COL`}:Mj}else if(c){let e=t-r;return{type:`HEADER`,domain:this.getDomain(this.rows[e]),dimension:`ROW`}}else if(l){let a=t-r,o=e-i;return!n.displayTotals&&this.isTotalRow(a)?Mj:{type:`VALUE`,domain:[...this.getDomain(this.rows[a]),...this.getColDomain(o)],measure:this.getColMeasure(o)}}return Mj}getColHeaderDomain(e,t){let n=this.columns[t].find(t=>t.offset===e);if(!(!n||n.collapsedHeader))return this.getDomain(n)}getDomain(e){return e.fields.map((t,n)=>{if(t===`measure`)return{type:`char`,field:t,value:Dg({displayName:`measure`,type:`char`},e.values[n])};{let{fieldName:r,granularity:i}=Sg(t),a=this.fieldsType[r]||`char`;return{type:a,field:t,value:Dg({displayName:r,type:a,granularity:i},e.values[n])}}})}getColDomain(e){let t=this.getColHeaderDomain(e,this.getColHeadersHeight()-1);return t?t.slice(0,-1):[]}getColMeasure(e){let t=this.getColHeaderDomain(e,this.getColHeadersHeight()-1)?.at(-1)?.value;if(t==null)throw Error(`Measure is missing`);return t.toString()}getRowHeadersWidth(e){return e.tabularForm?this.rowFields.length:1}getColHeadersHeight(){return this.columns.length}buildRowsTree(){let e=[],t=0,n={};n[0]=e;for(let r of this.rows){if(r.fields.length===0||r.values.length===0)return e;let i=r.fields.length-1,a=r.fields[i],{fieldName:o,granularity:s}=Sg(a),c=Dg({displayName:o,type:this.fieldsType[o]??`char`,granularity:s},r.values[i]);if(i>t){t=i,n[t]=[];let e=n[t-1].at(-1);e&&(e.children=n[t])}t=i;let l={value:c,field:r.fields[i],children:[],type:this.fieldsType[o]||`char`,width:0};n[t].push(l)}return e}buildColumnsTree(){let e=[],t=this.columns.at(-2)||[],n={};n[0]=e;for(let e of t)for(let t=0;t<e.fields.length;t++){let r=e.fields[t],{fieldName:i,granularity:a}=Sg(r),o=Dg({displayName:i,type:this.fieldsType[i]??`char`,granularity:a},e.values[t]),s={value:o,field:e.fields[t],children:[],width:e.width,type:this.fieldsType[i]||`char`};n[t]?.at(-1)?.value!==o&&(n[t+1]=[],s.children=n[t+1],n[t].push(s))}return e}export(){return{cols:this.columns,rows:this.rows,measures:this.measures,fieldsType:this.fieldsType}}sort(e,t,n){if(this.isSorted)return;let r=(e,t)=>{let r=n(e,t).value;return typeof r==`number`?r:-1/0},i=t.domain,a=kj(this.rowTree(),[],(n,a)=>{let o=r(e,[...n,...i]),s=r(e,[...a,...i]);return t.order===`asc`?o-s:s-o});this.rowTree=xt(a),this.rows=[...this.rowTreeToRows(a),this.rows[this.rows.length-1]],this.isSorted=!0}rowTreeToRows(e,t){return e.flatMap(e=>{let n={indent:t?t.indent+1:1,fields:[...t?.fields||[],e.field],values:[...t?.values||[],e.value]};return[n,...this.rowTreeToRows(e.children,n)]})}get numberOfCells(){return this.rows.length*this.getNumberOfDataColumns()}getColumnDomainsAtDepth(e){return e<0||e>=this.getColHeadersHeight()-1?[]:this.columns[e].map(e=>this.getDomain(e)).filter(e=>e.length)}getRowDomainsAtDepth(e){return e<0||e>this.maxIndent?[]:this.rows.filter(t=>t.indent===e+1).map(e=>this.getDomain(e))}getPivotTableDimensions(e){let t=this.getPivotCells(e),n=0;return e.displayColumnHeaders&&(n=this.getColHeadersHeight()-1),e.displayMeasuresRow&&n++,{numberOfCols:Math.min(this.getRowHeadersWidth(e)+e.numberOfColumns,t.length),numberOfRows:Math.min(n+e.numberOfRows,t[0].length),numberOfHeaderRows:n}}getNumberOfRowGroupBys(){return Math.max(...this.rows.map(e=>e.fields.length))}};let Mj={type:`EMPTY`};function Nj(e,t,n){let r=t.measures.filter(e=>!e.isHidden).map(e=>e.id),i=Fj(e,t.columns,0);Ij(i,r.length);let a=Lj(i,t),o=Pj(e,0,t.rows,[],[]);o.push({fields:[],values:[],indent:0});let s={};for(let e of t.columns)s[e.fieldName]=e.type;for(let e of t.rows)s[e.fieldName]=e.type;return new jj(a,o,r,s,n===`collapsed`?t.collapsedDomains:void 0)}function Pj(e,t,n,r,i){if(t>=n.length)return[];let a=n[t],o=a.nameWithGranularity,s=Rj(e,a),c=Bj(s,a),l=[],u=r.concat(o);for(let e of c){let r=i.concat(e);l.push({fields:u,values:r,indent:t+1});let a=s[e];a&&l.push(...Pj(a,t+1,n,u,r))}return l}function Fj(e,t,n){if(n>=t.length)return[];let r=t[n],i=t[n].nameWithGranularity,a=Rj(e,r);return Bj(a,t[n]).map(e=>({value:a[e]?.[0]?.[r.nameWithGranularity]?.value??null,field:i,children:Fj(a[e]||[],t,n+1),type:r.type,width:0}))}function Ij(e,t){for(let n in e){let r=e[n];r.children.length===0?r.width=t:(Ij(r.children,t),r.width=r.children.reduce((e,t)=>e+t.width,0))}}function Lj(e,t){let n=t.columns.map(e=>e.nameWithGranularity),r=n.length,i=t.measures.filter(e=>!e.isHidden),a=i.length,o=Array(r).fill(0).map(()=>[]);function s(e,t,i){let a=o[t];for(let o of e){let e=i.concat([o.value]),c={fields:n.slice(0,t+1),values:e,width:o.width,offset:0};a.push(c),t<=r-1&&s(o.children,t+1,e)}}s(e,0,[]);let c=n.length>0,l=[];return c&&o[o.length-1].forEach(e=>{i.forEach(t=>{let n={fields:[...e.fields,`measure`],values:[...e.values,t.id],width:1,offset:0};l.push(n)})}),i.forEach(e=>{let t={fields:[`measure`],values:[e.id],width:1,offset:0};l.push(t)}),o.push(l),o.length===1&&o.unshift([]),o[o.length-2].push({fields:[],values:[],width:a,offset:0}),o}function Rj(e,t){return Object.groupBy(e,zj(t))}function zj(e){let t=e.nameWithGranularity;return e=>`${e[t]?.value??null}`}function Bj(e,t){let n=t.order,r=t.customGroups?.find(e=>e.isOtherGroup);return!n&&!r?Object.keys(e):Object.keys(e).sort((e,i)=>r&&e===r.name?1:r&&i===r.name?-1:n?Vj(t,e,i):0)}function Vj(e,t,n){return t===`null`?e.order===`asc`?1:-1:n===`null`?e.order===`asc`?-1:1:e.type===`integer`||e.type===`datetime`?e.order===`asc`?I(t,V)-I(n,V):I(n,V)-I(t,V):e.order===`asc`?t.localeCompare(n):n.localeCompare(t)}var Hj=class{type=`SPREADSHEET`;getters;_definition;coreDefinition;metaData={fields:{},fieldKeys:[]};dataEntries=[];collapsedTable;expandedTable;invalidRangeError;needsReevaluation=!0;constructor(e,t){this.getters=t.getters,this.coreDefinition=t.definition}init(e={}){(!this._definition||e.reload)&&(this.reload(4),this.needsReevaluation=!1)}reload(e){e===4&&(this.metaData=this.loadMetaData()),e>=3&&(this._definition=this.loadRuntimeDefinition()),e>=2&&(this.dataEntries=this.loadData()),e>=1&&(this.collapsedTable=void 0,this.expandedTable=void 0)}onDefinitionChange(e){let t=this.coreDefinition;if(this.coreDefinition=e,this._definition){let n=Math.max(this.computeShouldReload(t,e),0);this.reload(n)}}computeShouldReload(e,t){return T(e.dataSet,t.dataSet)?3:4}get isInvalidRange(){return!!this.invalidRangeError}get invalidRangeMessage(){return this.invalidRangeError?.message}get definition(){if(this._definition||this.init(),!this._definition)throw Error(`Pivot definition should be defined at this point.`);return this._definition}isValid(){if(this.invalidRangeError||!this.definition)return!1;for(let e of this.definition.measures)if(!e.isValid)return!1;for(let e of this.definition.columns)if(!e.isValid)return!1;for(let e of this.definition.rows)if(!e.isValid)return!1;return!0}assertIsValid({throwOnError:e}){if(!this.isValid()){if(e)throw this.invalidRangeError?this.invalidRangeError:new N(j(`At least one measure and/or dimension is not correct.`));return{value:M.GenericError,message:this.invalidRangeError?.message??j(`At least one measure and/or dimension is not correct.`)}}}areDomainArgsFieldsValid(e){let t=e.filter((e,t)=>t%2==0).map(L);return t.length&&t.at(-1)===`measure`&&(t=t.slice(0,-1)),Tg(t,this.definition)}parseArgsToPivotDomain(e){let t=[];for(let n=0;n<e.length-1;n+=2){let r=L(e[n]),i=this.getTypeOfDimension(r),a=r===`measure`?L(e[n+1]):Dg(this.getDimension(r),e[n+1]);t.push({field:r,value:a,type:i})}return t}markAsDirtyForEvaluation(){this.needsReevaluation=!0}getMeasure(e){return this.definition.getMeasure(e)}getPivotMeasureValue(e){return{value:this.getMeasure(e).displayName}}getPivotHeaderValueAndFormat(e){let t=e.at(-1);if(!t)return{value:j(`Total`)};let n=this.getDimension(t.field),r=this.filterDataEntriesFromDomain(this.dataEntries,e)[0]?.[n.nameWithGranularity];return n.type===`datetime`?eg(n.granularity||`month`).toValueAndFormat(t.value,this.getters.getLocale()):r?r.value===null?{value:j(`(Undefined)`)}:r:{value:``}}getPivotCellValueAndFormat(e,t){let n=this.filterDataEntriesFromDomain(this.dataEntries,t);if(n.length===0)return{value:``};let r=this.getMeasure(e),i=n.map(e=>e[r.fieldName]).filter(w),a=i.filter(e=>e.type!==`empty`),o=r.aggregator,s=vg[o];if(!s)throw Error(`Aggregator ${o} does not exist`);try{let e=s([i],this.getters.getLocale());return a.length===0?{...e,value:``}:e}catch(e){return ko(e,o.toUpperCase())}}getPossibleFieldValues(e){let t=[],n=Rj(this.dataEntries,e),r=Bj(n,e);for(let i of r)t.push({value:n[i]?.[0]?.[e.nameWithGranularity]?.value??``,label:n[i]?.[0]?.[e.nameWithGranularity]?.formattedValue||``});return t}getCollapsedTableStructure(){if(!this.isValid())throw Error(`Pivot is not valid !`);return this.coreDefinition.style?.tabularForm?this.getExpandedTableStructure():(this.collapsedTable||=Nj(this.dataEntries,this.definition,`collapsed`),this.collapsedTable)}getExpandedTableStructure(){if(!this.isValid())throw Error(`Pivot is not valid !`);return this.expandedTable||=Nj(this.dataEntries,this.definition,`expanded`),this.expandedTable}getFields(){return this.metaData.fields}get fields(){return this.getFields()}loadMetaData(){if(this.invalidRangeError=void 0,this.coreDefinition.dataSet){let{zone:e,sheetId:t}=this.coreDefinition.dataSet,n=this.getters.getRangeFromZone(t,e);try{let e=this.extractFieldsFromRange(n),t=Rg(this.coreDefinition,e.fields);return{...e,fields:{...e.fields,...t}}}catch(e){return this.invalidRangeError=e,{fields:{},fieldKeys:[]}}}else return this.invalidRangeError=new N(j(`The pivot cannot be created because the dataset is missing.`)),{fields:{},fieldKeys:[]}}loadRuntimeDefinition(){return new dj(this.coreDefinition,this.fields,this.getters)}loadData(){let e=this._definition?.range;return this.isValid()&&e?this.extractDataEntriesFromRange(e):[]}getTypeOfDimension(e){if(e===`measure`)return`char`;let{fieldName:t}=Sg(e),n=this.fields[t]?.type;if(!n)throw Error(`Field ${t} does not exist`);return n}filterDataEntriesFromDomain(e,t){return t.reduce((e,t)=>this.filterDataEntriesFromDomainNode(e,t),e)}filterDataEntriesFromDomainNode(e,t){let{field:n,value:r,type:i}=t,{nameWithGranularity:a}=this.getDimension(n);return e.filter(e=>{let t=e[a]?.value;return i===`char`?String(t)===String(r):t===r})}getDimension(e){return this.definition.getDimension(e)}getTypeFromZone(e,t){let n=this.getters.getEvaluatedCellsInZone(e,t).filter(e=>!(e.type===`empty`||e.value===``));return n.length===0?`integer`:n.every(e=>e.type===`number`&&e.format&&Il(e.format))?`datetime`:n.every(e=>e.type===`boolean`)?`boolean`:n.every(e=>e.type===`number`)?`integer`:`char`}assertCellIsValidField(e,t,n){if(n.type===`error`)throw new N(j(`The pivot cannot be created because cell %s contains an error`,E(e,t)));if(n.type===`empty`||n.value===``)throw new N(j(`The pivot cannot be created because cell %s is empty`,E(e,t)));if(n.value===`__count`)throw new N(j(`The pivot cannot be created because cell %s contains a reserved value`,E(e,t)))}extractFieldsFromRange(e){let t={},n=[],r=e.sheetId,i=e.zone.top;for(let a=e.zone.left;a<=e.zone.right;a++){let o=this.getters.getEvaluatedCell({sheetId:r,col:a,row:i});this.assertCellIsValidField(a,i,o);let s=o.value?.toString();if(s){let i=this.getTypeFromZone(r,{top:e.zone.top+1,left:a,bottom:e.zone.bottom,right:a}),o=Lg(s,t);t[o]={name:o,type:i,string:o,aggregator:i===`integer`?`sum`:`count`},n.push(o)}}return{fields:t,fieldKeys:n}}extractDataEntriesFromRange(e){let t=[];for(let n=e.zone.top+1;n<=e.zone.bottom;n++){let r={top:n,bottom:n,left:e.zone.left,right:e.zone.right},i=this.getters.getEvaluatedCellsInZone(e.sheetId,r),a={};for(let e in i){let t=i[e],n=this.fields[this.metaData.fieldKeys[e]];if(!n)throw Error(`Field ${this.metaData.fieldKeys[e]} does not exist`);t.value===``?a[n.name]={value:null,type:`empty`,formattedValue:``}:a[n.name]=t}for(let e in this.definition.customFields||{}){let t=this.definition.customFields?.[e];if(!t)continue;let n=a[t.parentField],r=this.fields[t.parentField];if(!n||!r){a[e]={value:null,type:`empty`,formattedValue:``};continue}let i=t.groups.find(e=>e.values.some(e=>e===n?.value))||t.groups.find(e=>e.isOtherGroup);a[e]={...n,value:i?i.name:n.value}}a.__count={value:1,type:`number`,formattedValue:`1`},t.push(a)}let n=this.definition.columns.concat(this.definition.rows).filter(e=>e.type===`datetime`);if(n.length){let e=this.getters.getLocale();for(let r of t)for(let t of n){let n=qg(t,r[t.fieldName]?.value||null,this.getters.getLocale()),{format:i,value:a}=eg(t.granularity||`month`).toValueAndFormat(n,e);r[t.nameWithGranularity]={value:n,type:r[t.fieldName]?.type||`empty`,format:r[t.fieldName]?.format,formattedValue:H(a,{locale:e,format:i})}}}return t}};let Uj=new A,Wj=[`year`,`quarter_number`,`month_number`,`month`,`iso_week_number`,`day_of_month`,`day`,`day_of_week`],Gj=[...Wj,`hour_number`,`minute_number`,`second_number`];Uj.add(`SPREADSHEET`,{ui:Hj,definition:dj,dateGranularities:[...Wj],isMeasureCandidate:e=>e.type!==`boolean`,datetimeGranularities:[...Gj],isGroupable:()=>!0,canHaveCustomGroup:e=>e.type===`char`&&!e.isCustomField,isPivotUnused:()=>!0,adaptRanges:(e,t,n)=>{if(t.type!==`SPREADSHEET`||!t.dataSet)return t;let{sheetId:r,zone:i}=t.dataSet,a=e.getRangeFromZone(r,i),o=Kj(a,n);if(o===a)return t;let s=o&&{sheetId:o.sheetId,zone:o.zone};return{...t,dataSet:s}}});function Kj(e,t){if(!e)return;let n=t(e);switch(n.changeType){case`REMOVE`:return;default:return n.range}}let qj=[`PIVOT.VALUE`,`PIVOT.HEADER`,`PIVOT`];function Jj(e,t){return e.getFunctionsFromTokens(qj,t)[0]}function Yj(e,t){return e.getFunctionsFromTokens(qj,t)}function Xj(e,t){return e.getFunctionsFromTokens(qj,t).length}function Zj(e,t){let n=`"${t?`${e.name}:${t}`:e.name}"`,r=e.string===e.name?n:e.string+n;return{text:n,description:e.string+(e.help?` (${e.help})`:``),htmlContent:[{value:n,color:Ke.STRING}],fuzzySearchKey:r}}function Qj(e){let t=`"${e.id}"`,n=e.displayName+e.fieldName+t;return{text:t,description:e.displayName,htmlContent:[{value:t,color:Ke.STRING}],fuzzySearchKey:n}}function $j(e,t){let n=e.end,r=e.end;e.type!==`ARG_SEPARATOR`&&(n=e.start),this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t.text)}function eM(e,t){let n=e.end,r=e.end;e.type!==`LEFT_PAREN`&&(n=e.start),this.composer.changeComposerCursorSelection(n,r),this.composer.replaceComposerCursorSelection(t.text)}function tM(e){let t=e.functionContext?.args[0];if(!(!t||![`STRING`,`NUMBER`].includes(t.type)))return t.value}var nM=class extends wr{pivotId;updateMode;mutators=[`reset`,`deferUpdates`,`applyUpdate`,`discardPendingUpdate`,`update`];_updatesAreDeferred;draft=null;notification=this.get(lT);alreadyNotified=!1;alreadyNotifiedForPivotSize=!1;constructor(e,t,n=`canDefer`){super(e),this.pivotId=t,this.updateMode=n,this._updatesAreDeferred=this.getters.getPivotCoreDefinition(this.pivotId).deferUpdates??!1}handle(e){switch(e.type){case`UPDATE_PIVOT`:e.pivotId===this.pivotId&&this.getters.getPivot(this.pivotId).init()}}get updatesAreDeferred(){return this.updateMode===`neverDefer`?!1:this._updatesAreDeferred}get fields(){return this.pivot.getFields()}get pivot(){return this.getters.getPivot(this.pivotId)}get definition(){let e=Uj.get(this.pivot.type).definition;return this.draft?new e(this.draft,this.fields,this.getters):this.pivot.definition}get isDirty(){return!!this.draft}get measureFields(){let e=[{name:`__count`,string:j(`Count`),type:`integer`,aggregator:`sum`}],t=this.fields;for(let n in t){let r=t[n];r&&Uj.get(this.pivot.type).isMeasureCandidate(r)&&e.push(r)}return e.sort((e,t)=>e.string.localeCompare(t.string))}get unusedGroupableFields(){let e=[],t=this.fields;for(let n in t){let r=t[n];r&&Uj.get(this.pivot.type).isGroupable(r)&&e.push(r)}let{columns:n,rows:r,measures:i}=this.definition,a=i.concat(r).concat(n).map(e=>e.fieldName),o=this.unusedGranularities;return e.filter(e=>Cg(e)?!a.includes(e.name)||o[e.name].size>0:!a.includes(e.name)).sort((e,t)=>e.string.localeCompare(t.string))}get datetimeGranularities(){return Uj.get(this.pivot.type).datetimeGranularities}get dateGranularities(){return Uj.get(this.pivot.type).dateGranularities}get unusedGranularities(){return this.getUnusedGranularities(this.fields,this.draft??this.getters.getPivotCoreDefinition(this.pivotId))}reset(e){this.pivotId=e,this._updatesAreDeferred=!0,this.draft=null}deferUpdates(e){e===!1&&this.draft?(this.draft.deferUpdates=!1,this.applyUpdate()):this.update({deferUpdates:e}),this._updatesAreDeferred=e}applyUpdate(){if(this.draft){if(this.model.dispatch(`UPDATE_PIVOT`,{pivotId:this.pivotId,pivot:this.draft}),this.draft=null,!this.alreadyNotified&&this.isUpdatedPivotVisibleInViewportOnlyAsStaticPivot()){let e=`=PIVOT(${this.getters.getPivotFormulaId(this.pivotId)})`;this.alreadyNotified=!0,this.notification.notifyUser({type:`info`,text:j(`Pivot updates only work with dynamic pivot tables. Use the formula '%s' or re-insert the static pivot from the Data menu.`,e),sticky:!0})}let e=this.getters.getPivot(this.pivotId),t=e.isValid()?e.getExpandedTableStructure().numberOfCells:0;!this.alreadyNotifiedForPivotSize&&t>5e5&&(this.alreadyNotifiedForPivotSize=!0,this.notification.notifyUser({type:`warning`,text:Uy(t,this.getters.getLocale()),sticky:!0}))}}discardPendingUpdate(){this.draft=null}update(e){let t=this.getters.getPivotCoreDefinition(this.pivotId),n={...t,...this.draft,...e},r={...n,columns:n.columns.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),rows:n.rows.map(e=>({fieldName:e.fieldName,order:e.order,granularity:e.granularity})),measures:n.measures.map(e=>({id:e.id,fieldName:e.fieldName,aggregator:e.aggregator,userDefinedName:e.userDefinedName,computedBy:e.computedBy,isHidden:e.isHidden,format:e.format,display:e.display})),sortedColumn:this.shouldKeepSortedColumn(n)?n.sortedColumn:void 0};if(r.collapsedDomains){let{COL:e,ROW:t}=r.collapsedDomains;r.collapsedDomains={COL:e.filter(e=>this.areDomainFieldsValid(e,r.columns)),ROW:t.filter(e=>this.areDomainFieldsValid(e,r.rows))}}if(!this.draft&&T(t,r))return;let i=this.addDefaultDateTimeGranularity(this.fields,r);this.draft=i,this.updatesAreDeferred||this.applyUpdate()}isUpdatedPivotVisibleInViewportOnlyAsStaticPivot(){let e=0,t=this.getters.getPivotFormulaId(this.pivotId);for(let n of this.getters.getVisibleCellPositions()){let r=this.getters.getCell(n);if(r?.isFormula){let n=Jj(r.compiledFormula,this.getters),i=n?.args[0]?.value;if(n&&t===i.toString()){if(n.functionName===`PIVOT`)return!1;e++}}}return e>0}addDefaultDateTimeGranularity(e,t){let{columns:n,rows:r}=t,i=x(n),a=x(r),o=this.getUnusedGranularities(e,t);for(let t of i.concat(a)){let n=e[t.fieldName]?.type;if((n===`date`||n===`datetime`)&&!t.granularity){let e=o[t.fieldName]?.values().next().value;o[t.fieldName]?.delete(e),t.granularity=e}}return{...t,columns:i,rows:a}}getUnusedGranularities(e,t){let{columns:n,rows:r,measures:i}=t,a=n.concat(r).concat(i).filter(t=>{let n=e[t.fieldName]?.type;return n===`date`||n===`datetime`}),o={};for(let t of a)o[t.fieldName]=new Set(e[t.fieldName]?.type===`date`?this.dateGranularities:this.datetimeGranularities);for(let e of a)o[e.fieldName].delete(e.granularity);return o}shouldKeepSortedColumn(e){let{sortedColumn:t}=e;if(!t)return!0;let n=this.getters.getPivotCoreDefinition(this.pivotId);return e.measures.find(e=>e.id===t.measure)&&T(n.columns,e.columns)}areDomainFieldsValid(e,t){let n=t.map(({fieldName:e,granularity:t})=>e+(t?`:${t}`:``));for(let t=0;t<e.length;t++)if(e[t].field!==n[t])return!1;return!0}},rM=class extends t.Component{static template=`o-spreadsheet-PivotSpreadsheetSidePanel`;static props={pivotId:String,onCloseSidePanel:Function};static components={PivotLayoutConfigurator:cj,Section:Z,SelectionInput:jT,Checkbox:IT,PivotDeferUpdate:QA,PivotTitleSection:lj};store;state;pivotSidePanelRef=(0,t.useRef)(`pivotSidePanel`);setup(){this.store=hr(nM,this.props.pivotId),this.state=(0,t.useState)({range:void 0,rangeHasChanged:!1})}get shouldDisplayInvalidRangeError(){return this.store.isDirty&&this.state.rangeHasChanged?!1:this.pivot.isInvalidRange}get ranges(){return this.state.range?[this.state.range]:this.definition.range?[this.env.model.getters.getRangeString(this.definition.range,`forceSheetReference`)]:[]}get pivot(){return this.store.pivot}get definition(){return this.store.definition}getScrollableContainerEl(){return this.pivotSidePanelRef.el}onSelectionChanged(e){this.state.rangeHasChanged=!0,this.state.range=e[0]}onSelectionConfirmed(){if(this.state.range){let e=this.env.model.getters.getRangeFromSheetXC(this.env.model.getters.getActiveSheetId(),this.state.range);if(e.invalidSheetName||e.invalidXc)return;let t={sheetId:e.sheetId,zone:e.zone};this.store.update({dataSet:t}),this.store.applyUpdate()}}flipAxis(){let{rows:e,columns:t}=this.definition;this.onDimensionsUpdated({rows:t,columns:e})}onDimensionsUpdated(e){this.store.update(e)}};let iM=new A;iM.add(`SPREADSHEET`,{editor:rM});let aM=e=>({category:`light`,templateName:`pivotLightWithLightBorders`,primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0},border:{horizontal:{color:e.light,style:`thin`}}},headerRow:{style:{bold:!0},border:{top:{color:e.highlight,style:`thin`},bottom:{color:e.highlight,style:`thin`}}},mainSubHeaderRow:{style:{bold:!0}},firstAlternatingSubHeaderRow:{style:{bold:!0,textColor:e.highlight}},totalRow:{border:{top:{color:e.highlight,style:`thin`},bottom:{color:e.highlight,style:`thin`}},style:{bold:!0,fillColor:`#FFFFFF`}},firstRowStripe:{style:{fillColor:e.light},border:{bottom:{color:e.medium,style:`thin`},top:{color:e.medium,style:`thin`},vertical:{color:e.medium,style:`thin`}}},secondColumnStripe:{style:{fillColor:e.light},border:{left:{color:e.medium,style:`thin`},right:{color:e.medium,style:`thin`},horizontal:{color:e.medium,style:`thin`}}}}),oM=e=>({category:`light`,templateName:`pivotLightWithMediumBorders`,primaryColor:e.highlight,wholeTable:{style:{textColor:e.coloredText,hideGridLines:!0},border:{horizontal:{color:e.light,style:`thin`}}},firstColumn:{border:{right:{color:e.highlight,style:`thin`}}},headerRow:{style:{bold:!0,textColor:`#000000`},border:{top:{color:e.highlight,style:`medium`},bottom:{color:e.highlight,style:`medium`},left:{color:e.highlight,style:`medium`},right:{color:e.highlight,style:`medium`}}},measureHeader:{border:{top:{color:e.light,style:`thin`}}},mainSubHeaderRow:{style:{bold:!0,textColor:`#000000`,fillColor:e.light}},firstAlternatingSubHeaderRow:{style:{bold:!0,textColor:`#000000`}},totalRow:{border:{top:{color:e.highlight,style:`medium`},bottom:{color:e.highlight,style:`medium`},left:{color:e.highlight,style:`medium`},right:{color:e.highlight,style:`medium`}},style:{bold:!0,textColor:`#000000`}},firstRowStripe:{border:{bottom:{color:e.highlight,style:`thin`},top:{color:e.highlight,style:`thin`}}},secondRowStripe:{border:{bottom:{color:e.highlight,style:`thin`}}},firstColumnStripe:{border:{left:{color:e.highlight,style:`thin`},right:{color:e.highlight,style:`thin`}}},secondColumnStripe:{border:{left:{color:e.highlight,style:`thin`},right:{color:e.highlight,style:`thin`}}}}),sM=e=>({category:`light`,templateName:`PivotLightWithGrayBands`,primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0}},headerRow:{style:{bold:!0,fillColor:e.light},border:{horizontal:{color:e.light,style:`thin`},vertical:{color:e.light,style:`thin`},bottom:{color:e.mediumBorder,style:`thin`}}},measureHeader:{border:{top:{color:`#FFFFFF`,style:`thin`}}},mainSubHeaderRow:{style:{bold:!0},border:{bottom:{color:e.mediumBorder,style:`thin`}}},firstAlternatingSubHeaderRow:{style:{bold:!0}},totalRow:{border:{top:{color:e.mediumBorder,style:`medium`}},style:{bold:!0,fillColor:e.light}},firstRowStripe:{style:{fillColor:G.black.light}},secondColumnStripe:{style:{fillColor:G.black.light},border:{left:{color:G.black.medium,style:`thin`},right:{color:G.black.medium,style:`thin`}}}}),cM=e=>({category:`light`,templateName:`pivotLightWithColoredText`,primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0,textColor:e.coloredText},border:{vertical:{color:e.mediumBorder,style:`thin`},top:{color:e.mediumBorder,style:`thin`},bottom:{color:e.mediumBorder,style:`thin`},left:{color:e.mediumBorder,style:`thin`},right:{color:e.mediumBorder,style:`thin`}}},headerRow:{border:{bottom:{color:e.mediumBorder,style:`thin`},vertical:{color:e.mediumBorder,style:`thin`}}},totalRow:{border:{top:{color:e.mediumBorder,style:`thin`}}},firstRowStripe:{style:{fillColor:e.light},border:{top:{color:G.black.medium,style:`thin`},bottom:{color:G.black.medium,style:`thin`}}},secondColumnStripe:{style:{fillColor:e.light}}}),lM=e=>({category:`medium`,templateName:`pivotMediumHeavyColors`,primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0},border:{horizontal:{color:e.light,style:`thin`}}},headerRow:{style:{fillColor:e.highlight,textColor:`#FFFFFF`}},measureHeader:{border:{top:{color:e.light,style:`thin`}}},mainSubHeaderRow:{style:{fillColor:e.mediumBorder,textColor:`#FFFFFF`}},firstAlternatingSubHeaderRow:{style:{fillColor:e.light},border:{bottom:{color:e.highlight,style:`thin`}}},totalRow:{border:{top:{color:e.highlight,style:`medium`}},style:{bold:!0}},firstRowStripe:{border:{bottom:{color:e.highlight,style:`thin`},top:{color:e.highlight,style:`thin`}}},firstColumnStripe:{border:{left:{color:e.highlight,style:`thin`},right:{color:e.highlight,style:`thin`}}}}),uM=e=>({category:`medium`,templateName:`pivotMediumLightColors`,primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0},border:{top:{color:e.dark,style:`medium`},bottom:{color:e.dark,style:`medium`}}},headerRow:{style:{fillColor:e.highlight,textColor:`#FFFFFF`,bold:!0}},measureHeader:{border:{top:{color:e.mediumBorder,style:`thin`}}},mainSubHeaderRow:{style:{fillColor:e.light,bold:!0}},firstAlternatingSubHeaderRow:{style:{bold:!0}},totalRow:{border:{top:{color:e.dark,style:`thin`}},style:{bold:!0}},firstRowStripe:{border:{bottom:{color:e.mediumBorder,style:`thin`},top:{color:e.mediumBorder,style:`thin`}}},firstColumnStripe:{border:{left:{color:e.mediumBorder,style:`thin`},right:{color:e.mediumBorder,style:`thin`}}}}),dM=e=>({category:`medium`,templateName:`pivotMediumBlackHeaders`,primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0,fillColor:e.light},border:{vertical:{color:e.mediumBorder,style:`thin`}}},headerRow:{style:{fillColor:`#000000`,textColor:`#FFFFFF`}},measureHeader:{border:{top:{color:`#FFFFFF`,style:`thin`}}},mainSubHeaderRow:{style:{bold:!0}},firstAlternatingSubHeaderRow:{style:{bold:!0,textColor:`#808080`}},secondAlternatingSubHeaderRow:{style:{bold:!0}},totalRow:{style:{fillColor:`#000000`,textColor:`#FFFFFF`},border:{vertical:null}},firstRowStripe:{border:{bottom:{color:e.mediumBorder,style:`thin`},top:{color:e.mediumBorder,style:`thin`}}}}),fM=e=>({category:`medium`,templateName:`pivotMediumBlackHeaders`,primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0,fillColor:e.light,textColor:e.coloredText},border:{vertical:{color:`#FFFFFF`,style:`thin`}}},headerRow:{style:{bold:!0},border:{vertical:{color:`#FFFFFF`,style:`thin`},bottom:{color:`#FFFFFF`,style:`thin`}}},firstColumn:{style:{fillColor:e.medium}},measureHeader:{border:{top:{color:`#FFFFFF`,style:`thin`}}},mainSubHeaderRow:{style:{bold:!0,textColor:`#000000`}},firstAlternatingSubHeaderRow:{style:{bold:!0}},secondAlternatingSubHeaderRow:{style:{bold:!0}},totalRow:{style:{bold:!0}},firstRowStripe:{style:{fillColor:e.medium}},firstColumnStripe:{style:{fillColor:e.medium}}}),pM=e=>({category:`dark`,templateName:`pivotDarkWithDarkHeader`,primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0,fillColor:e.medium},border:{horizontal:{color:e.light,style:`thin`}}},headerRow:{style:{bold:!0,fillColor:e.dark,textColor:`#FFFFFF`}},measureHeader:{border:{top:{color:e.light,style:`thin`}}},mainSubHeaderRow:{style:{bold:!0,fillColor:e.light}},firstAlternatingSubHeaderRow:{style:{bold:!0}},totalRow:{style:{bold:!0,fillColor:e.dark,textColor:`#FFFFFF`}},secondRowStripe:{style:{fillColor:e.mediumBorder}},firstColumnStripe:{border:{left:{color:e.light,style:`thin`},right:{color:e.light,style:`thin`}}}}),mM=e=>({category:`dark`,templateName:`pivotDarkWithGrayHeader`,primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0,fillColor:e.light}},headerRow:{style:{bold:!0,fillColor:G.black.dark,textColor:`#FFFFFF`}},measureHeader:{border:{top:{color:e.light,style:`medium`}}},mainSubHeaderRow:{style:{bold:!0,fillColor:e.medium}},firstAlternatingSubHeaderRow:{style:{bold:!0}},totalRow:{style:{bold:!0,fillColor:G.black.dark,textColor:`#FFFFFF`}},firstRowStripe:{border:{bottom:{color:e.medium,style:`thin`},top:{color:e.medium,style:`thin`}}},firstColumnStripe:{border:{left:{color:e.mediumBorder,style:`thin`},right:{color:e.mediumBorder,style:`thin`}}}}),hM=e=>({category:`dark`,templateName:`pivotDarkWithBlackHeader`,primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0,fillColor:e.highlight,textColor:`#FFFFFF`}},headerRow:{style:{bold:!0,fillColor:`#000000`}},measureHeader:{border:{top:{color:e.light,style:`thin`}}},mainSubHeaderRow:{style:{bold:!0,fillColor:e.dark}},firstAlternatingSubHeaderRow:{style:{bold:!0}},totalRow:{style:{bold:!0,fillColor:`#000000`}},firstRowStripe:{border:{bottom:{color:e.mediumBorder,style:`thin`},top:{color:e.mediumBorder,style:`thin`}}},firstColumnStripe:{border:{left:{color:e.mediumBorder,style:`thin`},right:{color:e.mediumBorder,style:`thin`}}}}),gM=e=>({category:`dark`,templateName:`pivotDarkWithFirstColumn`,primaryColor:e.highlight,wholeTable:{style:{hideGridLines:!0,fillColor:e.highlight,textColor:`#FFFFFF`},border:{vertical:{color:`#FFFFFF`,style:`thin`}}},headerRow:{style:{fillColor:e.dark},border:{bottom:{color:`#FFFFFF`,style:`medium`}}},firstColumn:{style:{fillColor:e.dark}},measureHeader:{border:{top:{color:e.light,style:`thin`}}},mainSubHeaderRow:{style:{bold:!0}},firstAlternatingSubHeaderRow:{style:{bold:!0}},totalRow:{style:{bold:!0,fillColor:e.dark},border:{top:{color:`#FFFFFF`,style:`medium`}}},secondRowStripe:{style:{fillColor:e.mediumBorder}},firstColumnStripe:{style:{fillColor:e.mediumBorder}}}),_M={None:{category:`light`,templateName:`none`,primaryColor:``,displayName:j(`None`)}},vM=[G.black,G.lightBlue,G.red,G.lightGreen,G.purple,G.gray,G.orange];function yM(e,t){let n=1;for(let r of t)for(let t of vM){let i=e+n++;_M[i]={...r(t),displayName:bM(t.name,e,n-1)}}}function bM(e,t,n){let r=``;return t.includes(`Light`)?r=VS.light:t.includes(`Medium`)?r=VS.medium:t.includes(`Dark`)&&(r=VS.dark),`${r} ${e} ${n}`}yM(`PivotTableStyleLight`,[aM,oM,sM,cM]),yM(`PivotTableStyleMedium`,[lM,uM,dM,fM]),yM(`PivotTableStyleDark`,[pM,mM,hM,gM]),_M.PivotTableStyleDark1={..._M.PivotTableStyleDark1,...pM({...G.black,mediumBorder:Zr(G.black.medium,.1)})},_M.PivotTableStyleDark15={..._M.PivotTableStyleDark15,...hM({...G.black,highlight:G.gray.dark,mediumBorder:G.black.medium})},_M.PivotTableStyleDark22={..._M.PivotTableStyleDark22,...gM({...G.black,highlight:G.gray.dark,mediumBorder:G.black.medium})};function xM(e){let t=_M[e];return t&&Object.keys(tC).find(e=>{let n=tC[e];return n.category===t.category&&n.primaryColor===t.primaryColor})||`None`}let SM=[`wholeTable`,`firstColumnStripe`,`secondColumnStripe`,`firstRowStripe`,`secondRowStripe`,`firstColumn`,`lastColumn`,`headerRow`,`measureHeader`,`firstAlternatingSubHeaderRow`,`secondAlternatingSubHeaderRow`,`mainSubHeaderRow`,`totalRow`];function CM(e,t){let n=t.numberOfHeaders,r={...e,top:e.top+n};return r.top<=r.bottom?r:void 0}function wM(e){let t=e.range;return{row:t.zone.top,col:t.zone.left,sheetId:t.sheetId}}function TM(e,t,n,r){let i=t.zone;if(i.left!==i.right)throw Error(`Can only define a filter on a single column`);let a={...i,top:i.top+n.numberOfHeaders},o=r(t.sheetId,a);return{id:e,rangeWithHeaders:t,col:i.left,filteredRange:a.top>a.bottom?void 0:o}}function EM(e){return e.type===`static`||e.type===`forceStatic`}function DM(e,t,n){return{borders:OM(e,t,n),styles:AM(e,t,n)}}function OM(e,t,n){let{numberOfCols:r,numberOfRows:i}=n,a=so(r,i,()=>({}));for(let o of SM){let s=t[o]?.border;if(!s)continue;let c=jM(o,e,n);for(let t of c)for(let n=t.left;n<=t.right;n++)for(let c=t.top;c<=t.bottom;c++){let l=o===`wholeTable`&&c<=e.numberOfHeaders-1;c===t.top&&s?.top!==void 0?kM(a,`top`,s.top,n,c,r,i):c!==t.top&&!l&&s?.horizontal!==void 0&&kM(a,`top`,s.horizontal,n,c,r,i),c===t.bottom&&s?.bottom!==void 0&&kM(a,`bottom`,s.bottom,n,c,r,i),n===t.left&&s?.left!==void 0&&kM(a,`left`,s.left,n,c,r,i),n===t.right&&s?.right!==void 0?kM(a,`right`,s.right,n,c,r,i):n!==t.right&&!l&&s?.vertical!==void 0&&kM(a,`right`,s.vertical,n,c,r,i)}}return a}function kM(e,t,n,r,i,a,o){switch(t){case`top`:e[r][i].top=n??void 0,i!==0&&(e[r][i-1].bottom=n??void 0);return;case`bottom`:e[r][i].bottom=n??void 0,i!==o-1&&(e[r][i+1].top=n??void 0);return;case`left`:e[r][i].left=n??void 0,r!==0&&(e[r-1][i].right=n??void 0);return;case`right`:e[r][i].right=n??void 0,r!==a-1&&(e[r+1][i].left=n??void 0);return}}function AM(e,t,n){let{numberOfCols:r,numberOfRows:i}=n,a=so(r,i,()=>({}));for(let r of SM){let i=t[r];if(!i)continue;let o=jM(r,e,n);for(let e of o)for(let t=e.left;t<=e.right;t++)for(let n=e.top;n<=e.bottom;n++)a[t][n]||(a[t][n]={}),a[t][n]={...a[t][n],...i?.style}}return a}function jM(e,t,n){let{numberOfCols:r,numberOfRows:i}=n,a=[],o=Math.min(t.numberOfHeaders,i),s=+!!t.totalRow,c=r-1,l=i-1;switch(e){case`wholeTable`:a.push({top:0,left:0,bottom:l,right:c});break;case`firstColumn`:if(!t.firstColumn)break;a.push({top:0,left:0,bottom:l,right:0});break;case`lastColumn`:if(!t.lastColumn)break;a.push({top:0,left:c,bottom:l,right:c});break;case`headerRow`:if(!t.numberOfHeaders)break;a.push({top:0,left:0,bottom:o-1,right:c});break;case`totalRow`:if(!t.totalRow)break;a.push({top:l,left:0,bottom:l,right:c});break;case`firstRowStripe`:if(!t.bandedRows)break;for(let e=o;e<i-s;e+=2)a.push({top:e,left:0,bottom:e,right:c});break;case`secondRowStripe`:if(!t.bandedRows)break;for(let e=o+1;e<i-s;e+=2)a.push({top:e,left:0,bottom:e,right:c});break;case`firstColumnStripe`:{if(!t.bandedColumns)break;let e=n.mode===`pivot`?l:l-s;for(let t=0;t<r;t+=2)a.push({top:o,left:t,bottom:e,right:t});break}case`secondColumnStripe`:{if(!t.bandedColumns)break;let e=n.mode===`pivot`?l:l-s;for(let t=1;t<r;t+=2)a.push({top:o,left:t,bottom:e,right:t});break}case`mainSubHeaderRow`:if(n.isTabular)for(let e of n.mainSubHeaderRows||[])a.push({top:o,bottom:l-s,left:e,right:e});else for(let e of n.mainSubHeaderRows||[])a.push({top:e,bottom:e,left:0,right:r-1});break;case`firstAlternatingSubHeaderRow`:if(n.isTabular)for(let e of n.firstAlternatingSubHeaderIndexes||[])a.push({top:o,bottom:l-s,left:e,right:e});else for(let e of n.firstAlternatingSubHeaderIndexes||[])a.push({top:e,bottom:e,left:0,right:r-1});break;case`secondAlternatingSubHeaderRow`:if(n.isTabular)for(let e of n.secondAlternatingSubHeaderIndexes||[])a.push({top:o,bottom:l-s,left:e,right:e});else for(let e of n.secondAlternatingSubHeaderIndexes||[])a.push({top:e,bottom:e,left:0,right:r-1});break;case`measureHeader`:if(n.measureRow!==void 0&&r>1){let e=n.measureRow,t=+!n.isTabular;a.push({top:e,bottom:e,left:t,right:r-1})}break}return a}function MM(e,t){return e.model.getters.isTableStyleEditable(t)?p([{id:`editTableStyle`,name:j(`Edit table style`),execute:e=>e.openSidePanel(`TableStyleEditorPanel`,{styleId:t}),isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.EDIT`},{id:`deleteTableStyle`,name:j(`Delete table style`),execute:e=>e.model.dispatch(`REMOVE_TABLE_STYLE`,{tableStyleId:t}),icon:`o-spreadsheet-Icon.TRASH`}]):[]}function NM(e,t,n){e.resetTransform(),PM(e,t,n),FM(e,t,n),IM(e,t,n)}function PM(e,t,n){let{colWidth:r,rowHeight:i,numberOfCols:a,numberOfRows:o}=n;e.save();for(let n=0;n<a;n++)for(let s=0;s<o;s++){e.fillStyle=t.styles[n][s].fillColor||`#fff`;let c=n===a-1?r+1:r,l=s===o-1?i+1:i;e.fillRect(n*r,s*i,c,l)}e.restore()}function FM(e,t,n){let{colWidth:r,rowHeight:i,numberOfCols:a,numberOfRows:o}=n;e.save(),e.translate(0,.5),e.lineWidth=1;for(let n=0;n<a;n++)for(let a=0;a<o;a++){let o=t.borders[n][a];o.top&&(e.strokeStyle=o.top.color,e.beginPath(),e.moveTo(n*r,a*i),e.lineTo(n*r+r,a*i),e.stroke()),o.bottom&&(e.strokeStyle=o.bottom.color,e.beginPath(),e.moveTo(n*r,a*i+i),e.lineTo(n*r+r,a*i+i),e.stroke())}e.resetTransform(),e.translate(.5,0);for(let n=0;n<a;n++)for(let a=0;a<o;a++){let o=t.borders[n][a];o.left&&(e.strokeStyle=o.left.color,e.beginPath(),e.moveTo(n*r,a*i),e.lineTo(n*r,a*i+i),e.stroke()),o.right&&(e.strokeStyle=o.right.color,e.beginPath(),e.moveTo(n*r+r,a*i),e.lineTo(n*r+r,a*i+i+1),e.stroke())}e.restore()}function IM(e,t,n){let{colWidth:r,rowHeight:i,numberOfCols:a,numberOfRows:o}=n;e.save(),e.translate(0,.5),e.lineWidth=1;let s=Math.floor(r/4),c=Math.floor(i/2);for(let n=0;n<a;n++)for(let a=0;a<o;a++)e.strokeStyle=t.styles[n][a].textColor||`#000`,e.beginPath(),e.moveTo(n*r+s+1,a*i+c),e.lineTo(n*r+r-s,a*i+c),e.stroke();e.restore()}var LM=class extends t.Component{static template=`o-spreadsheet-TableStylePreview`;static components={MenuPopover:wy};static props={tableConfig:Object,tableStyle:Object,type:String,styleId:{type:String,optional:!0},selected:{type:Boolean,optional:!0},onClick:{type:Function,optional:!0}};canvasRef=(0,t.useRef)(`canvas`);menu=(0,t.useState)({isOpen:!1,anchorRect:null,menuItems:[]});setup(){(0,t.onWillUpdateProps)(e=>{(!T(this.props.tableConfig,e.tableConfig)||!T(this.props.tableStyle,e.tableStyle))&&this.drawTable(e)});let e=new ResizeObserver(()=>{this.drawTable(this.props)});(0,t.useEffect)(()=>(e.observe(this.canvasRef.el),()=>{e.disconnect()}),()=>[this.canvasRef.el])}drawTable(e){let t=this.canvasRef.el.getContext(`2d`),{width:n,height:r}=this.canvasRef.el.getBoundingClientRect();if(!n||!r)return;this.canvasRef.el.width=n,this.canvasRef.el.height=r;let i;i=e.type===`table`?{mode:`table`,numberOfCols:5,numberOfRows:5}:{mode:`pivot`,numberOfCols:5,numberOfRows:8,mainSubHeaderRows:new Set([e.tableConfig.numberOfHeaders,e.tableConfig.numberOfHeaders+3])},NM(t,DM(e.tableConfig,e.tableStyle,i),{...i,colWidth:(n-1)/i.numberOfCols,rowHeight:(r-1)/i.numberOfRows})}onContextMenu(e){this.props.styleId&&(this.menu.menuItems=MM(this.env,this.props.styleId),this.menu.isOpen=!0,this.menu.anchorRect={x:e.clientX,y:e.clientY,width:0,height:0})}closeMenu(){this.menu.isOpen=!1,this.menu.anchorRect=null,this.menu.menuItems=[]}get styleName(){return this.props.styleId?this.props.tableStyle.displayName:``}get isStyleEditable(){return this.props.styleId?this.env.model.getters.isTableStyleEditable(this.props.styleId):!1}editTableStyle(){this.env.openSidePanel(`TableStyleEditorPanel`,{styleId:this.props.styleId})}},RM=class extends t.Component{static template=`o-spreadsheet-TableStylesPopover`;static components={Popover:by,TableStylePreview:LM};static props={tableConfig:Object,popoverProps:{type:Object,optional:!0},closePopover:Function,onStylePicked:Function,selectedStyleId:{type:String,optional:!0},tableStyles:Object,type:String};tableStyleListRef=(0,t.useRef)(`tableStyleList`);state=(0,t.useState)({selectedCategory:this.initialSelectedCategory});setup(){(0,t.useExternalListener)(window,`click`,this.onExternalClick,{capture:!0})}onExternalClick(e){this.tableStyleListRef.el&&!fm(this.tableStyleListRef.el,e)&&(this.props.closePopover(),e.hasClosedTableStylesPopover=!0)}get displayedStyles(){let e=this.props.tableStyles;return Object.keys(e).filter(t=>e[t].category===this.state.selectedCategory)}get initialSelectedCategory(){return this.props.selectedStyleId?this.props.tableStyles[this.props.selectedStyleId].category:`medium`}get categories(){return this.props.type===`table`?{...VS,custom:j(`Custom`)}:VS}newTableStyle(){this.props.closePopover(),this.env.openSidePanel(`TableStyleEditorPanel`,{onStylePicked:this.props.onStylePicked})}},zM=class extends t.Component{static template=`o-spreadsheet-TableStylePicker`;static components={TableStylesPopover:RM,TableStylePreview:LM};static props={tableConfig:Object,onStylePicked:Function,tableStyles:Object,type:String};state=(0,t.useState)({popoverProps:void 0});getDisplayedTableStyles(){let e=this.props.tableStyles,t=e[this.props.tableConfig.styleId].category,n=Object.keys(e).filter(n=>e[n].category===t),r=n.indexOf(this.props.tableConfig.styleId);if(r===-1)return n;let i=Math.floor(r/4)*4;return n.slice(i)}onStylePicked(e){this.props.onStylePicked(e),this.closePopover()}onArrowButtonClick(e){if(e.hasClosedTableStylesPopover||this.state.popoverProps){this.closePopover();return}let{bottom:t,right:n}=e.currentTarget.getBoundingClientRect();this.state.popoverProps={anchorRect:{x:n,y:t,width:0,height:0},positioning:`top-right`,verticalOffset:0}}closePopover(){this.state.popoverProps=void 0}},BM=class extends t.Component{static template=`o-spreadsheet-PivotDesignPanel`;static props={pivotId:String};static components={Section:Z,Checkbox:IT,NumberInput:rO,TableStylePicker:zM};store;setup(){this.store=hr(nM,this.props.pivotId,`neverDefer`)}updatePivotStyleNumberProperty(e,t){let n=parseInt(e);this.store.update({style:{...this.pivotStyle,[t]:isNaN(n)?void 0:n}})}updatePivotStyleProperty(e,t){this.store.update({style:{...this.pivotStyle,[e]:t}})}get pivotStyle(){return this.env.model.getters.getPivotCoreDefinition(this.props.pivotId).style||{}}get defaultStyle(){return pg}get tableConfig(){let e=(this.pivotStyle.displayMeasuresRow??pg.displayMeasuresRow)||(this.pivotStyle.displayColumnHeaders??pg.displayColumnHeaders);return{hasFilters:!1,totalRow:this.pivotStyle.displayTotals??pg.displayTotals,firstColumn:!0,lastColumn:!1,styleId:this.pivotStyle.tableStyleId??pg.tableStyleId,bandedRows:this.pivotStyle.bandedRows??pg.bandedRows,bandedColumns:this.pivotStyle.bandedColumns??pg.bandedColumns,numberOfHeaders:+!!e}}onStylePicked(e){this.updatePivotStyleProperty(`tableStyleId`,e)}get tableStyles(){return _M}},VM=class extends t.Component{static template=`o-spreadsheet-PivotSidePanel`;static props={pivotId:String,onCloseSidePanel:Function,openTab:{type:String,optional:!0}};static defaultProps={openTab:`configuration`};static components={PivotLayoutConfigurator:cj,Section:Z,PivotDesignPanel:BM};state=(0,t.useState)({panel:this.props.openTab||`configuration`});setup(){dk(this),(0,t.onWillUpdateProps)(e=>{e.openTab&&e.openTab!==this.props.openTab&&this.switchPanel(e.openTab)})}get sidePanelEditor(){let e=this.env.model.getters.getPivotCoreDefinition(this.props.pivotId);if(!e)throw Error(`pivotId does not correspond to a pivot.`);return iM.get(e.type).editor}get highlights(){return this.state.panel===`configuration`?XA(this.env.model.getters,this.props.pivotId):[]}switchPanel(e){this.state.panel=e}},HM=class extends t.Component{static template=`o-spreadsheet-RemoveDuplicatesPanel`;static components={ValidationMessages:$D,Section:Z,Checkbox:IT};static props={onCloseSidePanel:Function};state=(0,t.useState)({hasHeader:!1,columns:{}});setup(){this.updateColumns(),(0,t.onWillUpdateProps)(()=>this.updateColumns())}toggleHasHeader(){this.state.hasHeader=!this.state.hasHeader}toggleAllColumns(){let e=!this.isEveryColumnSelected;for(let t in this.state.columns)this.state.columns[t]=e}toggleColumn(e){this.state.columns[e]=!this.state.columns[e]}onRemoveDuplicates(){this.env.model.dispatch(`REMOVE_DUPLICATES`,{hasHeader:this.state.hasHeader,columns:this.getColsToAnalyze()})}getColLabel(e){let t=parseInt(e),n=j(`Column %s`,Zt(t));if(this.state.hasHeader){let e=this.env.model.getters.getActiveSheetId(),r=this.env.model.getters.getSelectedZone().top,i=this.env.model.getters.getEvaluatedCell({sheetId:e,col:t,row:r});i.type!==`empty`&&(n+=` - ${i.value}`)}return n}get isEveryColumnSelected(){return Object.values(this.state.columns).every(e=>e)}get errorMessages(){let e=this.env.model.canDispatch(`REMOVE_DUPLICATES`,{hasHeader:this.state.hasHeader,columns:this.getColsToAnalyze()}).reasons,t=new Set;for(let n of e)t.add(zy.Errors[n]||zy.Errors.Unexpected);return Array.from(t)}get selectionStatisticalInformation(){let e=Ln(this.env.model.getters.getSelectedZone());return j(`%(row_count)s rows and %(column_count)s columns selected`,{row_count:e.numberOfRows,column_count:e.numberOfCols})}get canConfirm(){return this.errorMessages.length===0}updateColumns(){let e=this.env.model.getters.getSelectedZone(),t=this.state.columns,n={};for(let r=e.left;r<=e.right;r++)n[r]=r in t?t[r]:!0;this.state.columns=n}getColsToAnalyze(){return Object.keys(this.state.columns).filter(e=>this.state.columns[e]).map(e=>parseInt(e))}},UM=class extends t.Component{static template=`o-spreadsheet-SettingsPanel`;static components={Section:Z,ValidationMessages:$D,BadgeSelection:aO,Select:Ty};static props={onCloseSidePanel:Function};loadedLocales=[];setup(){(0,t.onWillStart)(()=>this.loadLocales())}onLocaleChange(e){let t=this.loadedLocales.find(t=>t.code===e);t&&this.env.model.dispatch(`UPDATE_LOCALE`,{locale:t})}async loadLocales(){this.loadedLocales=(await this.env.loadLocales()).filter(e=>{let t=Wy(e);return t||console.warn(`Invalid locale: ${e.code} ${e}`),t}).sort((e,t)=>e.name.localeCompare(t.name))}get numberFormatPreview(){return H(1234567.89,{format:`#,##0.00`,locale:this.env.model.getters.getLocale()})}get dateFormatPreview(){let e=this.env.model.getters.getLocale();return H(1.6,{format:e.dateFormat,locale:e})}get dateTimeFormatPreview(){let e=this.env.model.getters.getLocale();return H(1.6,{format:sb(e),locale:e})}get firstDayOfWeek(){return xl[this.env.model.getters.getLocale().weekStart%7]}get currentLocale(){return this.env.model.getters.getLocale()}get supportedLocales(){let e=this.currentLocale,t=this.loadedLocales.find(t=>t.code===e.code);if(!t)return[...this.loadedLocales,e].sort((e,t)=>e.name.localeCompare(t.name));if(!T(e,t)){let n=this.loadedLocales.indexOf(t),r=[...this.loadedLocales];return r[n]=e,r.sort((e,t)=>e.name.localeCompare(t.name)),r}return this.loadedLocales}get selectOptions(){return this.supportedLocales.map(e=>({label:e.name,value:e.code}))}};let WM={SplitIsDestructive:j(`This will overwrite data in the subsequent columns. Split anyway?`)};function GM(e,t,n){let r=e.model.dispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:t,addNewColumns:n});return r.isCancelledBecause(`SplitWillOverwriteContent`)&&e.askConfirmation(WM.SplitIsDestructive,()=>{r=e.model.dispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:t,addNewColumns:n,force:!0})}),r}let KM=[{label:j(`Detect automatically`),value:`auto`},{label:j(`Custom separator`),value:`custom`},{label:j(`Space`),value:` `},{label:j(`Comma`),value:`,`},{label:j(`Semicolon`),value:`;`},{label:j(`Line Break`),value:`
84
- `}];var qM=class extends t.Component{static template=`o-spreadsheet-SplitIntoColumnsPanel`;static components={ValidationMessages:$D,Section:Z,Checkbox:IT,Select:Ty};static props={onCloseSidePanel:Function};state=(0,t.useState)({separatorValue:`auto`,addNewColumns:!1,customSeparator:``});setup(){let e=O(Er);(0,t.useEffect)(e=>{e!==`inactive`&&this.props.onCloseSidePanel()},()=>[e.focusMode]),(0,t.onMounted)(()=>{e.activeComposer.stopEdition()})}onSeparatorChange(e){this.state.separatorValue=e}updateCustomSeparator(e){e.target&&(this.state.customSeparator=e.target.value)}updateAddNewColumnsCheckbox(e){this.state.addNewColumns=e}confirm(){GM(this.env,this.separatorValue,this.state.addNewColumns).isSuccessful&&this.props.onCloseSidePanel()}get errorMessages(){let e=this.env.model.canDispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!0}).reasons,t=new Set;for(let n of e)switch(n){case`SplitWillOverwriteContent`:case`EmptySplitSeparator`:break;default:t.add(Ry.Errors[n]||Ry.Errors.Unexpected)}return Array.from(t)}get warningMessages(){let e=[];return this.env.model.canDispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!1}).reasons.includes(`SplitWillOverwriteContent`)&&e.push(Ry.Errors.SplitWillOverwriteContent),e}get separatorValue(){return this.state.separatorValue===`custom`?this.state.customSeparator:this.state.separatorValue===`auto`?this.env.model.getters.getAutomaticSeparator():this.state.separatorValue}get separators(){return KM}get isConfirmDisabled(){return!this.separatorValue||this.errorMessages.length>0}},JM=class extends t.Component{static template=`o-spreadsheet-TablePanel`;static components={TableStylePicker:zM,SelectionInput:jT,ValidationMessages:$D,Checkbox:IT,Section:Z,NumberInput:rO};static props={onCloseSidePanel:Function,table:Object};state;setup(){let e=this.env.model.getters.getActiveSheetId();this.state=(0,t.useState)({tableZoneErrors:[],tableXc:this.env.model.getters.getRangeString(this.props.table.range,e),filtersEnabledIfPossible:this.props.table.config.hasFilters})}updateHasFilters(e){this.state.filtersEnabledIfPossible=e,this.updateTableConfig(`hasFilters`,e)}updateTableConfig(e,t){let n=this.env.model.getters.getActiveSheetId();return this.env.model.dispatch(`UPDATE_TABLE`,{sheetId:n,zone:this.props.table.range.zone,config:{[e]:t}})}updateHasHeaders(e){let t=+!!e;this.updateNumberOfHeaders(t)}updateTableIsDynamic(e){let t=e?`dynamic`:`forceStatic`;if(t===this.props.table.type)return;let n=this.env.model.getters.getTable(wM(this.props.table));if(!n)return;let r=this.env.model.getters.getActiveSheetId(),i=this.env.model.dispatch(`UPDATE_TABLE`,{sheetId:r,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeData(n.range),tableType:t}),a=this.env.model.getters.getCoreTable(wM(this.props.table));if(i.isSuccessful&&a){let e=a.range;this.state.tableXc=this.env.model.getters.getRangeString(e,r),this.state.tableZoneErrors=[]}}onChangeNumberOfHeaders(e){let t=parseInt(e);this.updateNumberOfHeaders(t)}updateNumberOfHeaders(e){let t=e>0&&(this.tableConfig.hasFilters||this.state.filtersEnabledIfPossible);return this.env.model.dispatch(`UPDATE_TABLE`,{sheetId:this.env.model.getters.getActiveSheetId(),zone:this.props.table.range.zone,config:{numberOfHeaders:e,hasFilters:t}})}onRangeChanged(e){let t=this.env.model.getters.getActiveSheetId();this.state.tableXc=e[0];let n=this.env.model.getters.getRangeFromSheetXC(t,this.state.tableXc);this.state.tableZoneErrors=this.env.model.canDispatch(`UPDATE_TABLE`,{sheetId:t,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeDataFromXc(t,this.state.tableXc),tableType:this.getNewTableType(n.zone)}).reasons}onRangeConfirmed(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getRangeFromSheetXC(e,this.state.tableXc);if(Xn(t.zone)===1){let n=this.env.model.getters.getContiguousZone(e,t.zone);t=this.env.model.getters.getRangeFromZone(e,n)}let n=t.zone,r=this.props.table.range.zone,i=n.top===r.top&&n.left===r.left?`RESIZE_TABLE`:`UPDATE_TABLE`,a=this.env.model.dispatch(i,{sheetId:e,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeData(t),tableType:this.getNewTableType(t.zone)}),o={sheetId:e,col:t.zone.left,row:t.zone.top},s=this.env.model.getters.getCoreTable(o);if(a.isSuccessful&&s){let t=wM(s);this.env.model.selection.selectZone({zone:D(t),cell:t});let n=s.range;this.state.tableXc=this.env.model.getters.getRangeString(n,e)}}onStylePicked(e){let t=this.env.model.getters.getActiveSheetId();this.env.model.dispatch(`UPDATE_TABLE`,{sheetId:t,zone:this.props.table.range.zone,config:{styleId:e}})}deleteTable(){let e=this.env.model.getters.getActiveSheetId();this.env.model.dispatch(`REMOVE_TABLE`,{sheetId:e,target:[this.props.table.range.zone]})}getNewTableType(e){if(this.props.table.type===`forceStatic`)return`forceStatic`;let t=this.env.model.getters.getActiveSheetId();return this.env.model.getters.canCreateDynamicTableOnZones(t,[e])?`dynamic`:`static`}get tableConfig(){return this.props.table.config}get errorMessages(){return(this.state.tableZoneErrors||[]).map(e=>Vy.Errors[e]||Vy.Errors.Unexpected)}getCheckboxLabel(e){return Vy.Checkboxes[e]}get canHaveFilters(){return this.tableConfig.numberOfHeaders>0}get hasFilterCheckboxTooltip(){return this.canHaveFilters?void 0:Vy.Tooltips.filterWithoutHeader}get canBeDynamic(){let e=this.env.model.getters.getActiveSheetId();return this.props.table.type===`dynamic`||this.env.model.getters.canCreateDynamicTableOnZones(e,[this.props.table.range.zone])}get dynamicTableTooltip(){return Vy.Tooltips.isDynamic}};let YM=`#3C78D8`;var XM=class extends t.Component{static template=`o-spreadsheet-TableStyleEditorPanel`;static components={Section:Z,RoundColorPicker:ST,TableStylePreview:LM};static props={onCloseSidePanel:Function,onStylePicked:{type:Function,optional:!0},styleId:{type:String,optional:!0}};state=(0,t.useState)(this.getInitialState());setup(){(0,t.useExternalListener)(window,`click`,()=>this.state.pickerOpened=!1)}getInitialState(){let e=this.props.styleId?this.env.model.getters.getTableStyle(this.props.styleId):null;return{pickerOpened:!1,primaryColor:e?.primaryColor||YM,selectedTemplateName:e?.templateName||`lightColoredText`,styleName:e?.displayName||this.env.model.getters.getNewCustomTableStyleName()}}togglePicker(){this.state.pickerOpened=!this.state.pickerOpened}onColorPicked(e){this.state.primaryColor=Pr(e)?e:YM,this.state.pickerOpened=!1}onTemplatePicked(e){this.state.selectedTemplateName=e}onConfirm(){let e=this.props.styleId||this.env.model.uuidGenerator.smallUuid();this.env.model.dispatch(`CREATE_TABLE_STYLE`,{tableStyleId:e,tableStyleName:this.state.styleName,templateName:this.state.selectedTemplateName,primaryColor:this.state.primaryColor}),this.props.onStylePicked?.(e),this.props.onCloseSidePanel()}onCancel(){this.props.onCloseSidePanel()}onDelete(){this.props.styleId&&(this.env.model.dispatch(`REMOVE_TABLE_STYLE`,{tableStyleId:this.props.styleId}),this.props.onCloseSidePanel())}get colorPreviewStyle(){return W({background:this.state.primaryColor})}get tableTemplates(){return Object.keys(nC).filter(e=>e!==`none`)}get previewTableConfig(){return{bandedColumns:!1,bandedRows:!0,firstColumn:!1,lastColumn:!1,numberOfHeaders:1,totalRow:!0,hasFilters:!0,styleId:``}}get selectedStyle(){return this.computeTableStyle(this.state.selectedTemplateName)}computeTableStyle(e){return rC(this.state.styleName,e,this.state.primaryColor)}};let ZM=new A;ZM.add(`ConditionalFormatting`,{title:j(`Conditional formatting`),Body:Ek}),ZM.add(`ConditionalFormattingEditor`,{title:j(`Conditional formatting`),Body:wk,computeState:(e,t)=>({isOpen:!0,props:t,key:`ConditionalFormattingEditor_${t.cf.id}`})}),ZM.add(`ChartPanel`,{title:j(`Chart`),Body:sk,computeState:(e,t)=>{let n=e.getSelectedFigureId(),r=n&&e.getFigureSheetId(n),i=r?e.isSheetLocked(r):!1,a=n?e.getChartIdFromFigureId(n):t.chartId;return!a||!e.isChartDefined(a)||i?{isOpen:!1}:{isOpen:!0,props:{chartId:a}}}}),ZM.add(`FindAndReplace`,{title:j(`Find and Replace`),Body:Mk}),ZM.add(`SplitToColumns`,{title:j(`Split text into columns`),Body:qM}),ZM.add(`Settings`,{title:j(`Spreadsheet settings`),Body:UM}),ZM.add(`RemoveDuplicates`,{title:j(`Remove duplicates`),Body:HM}),ZM.add(`DataValidation`,{title:j(`Data validation`),Body:Ok}),ZM.add(`DataValidationEditor`,{title:j(`Data validation`),Body:kk,computeState:(e,t)=>({isOpen:!0,props:t,key:`DataValidationEditor_${t.ruleId}`})}),ZM.add(`MoreFormats`,{title:j(`More formats`),Body:HA}),ZM.add(`ColumnStats`,{title:j(`Column statistics`),Body:gk}),ZM.add(`TableSidePanel`,{title:j(`Edit table`),Body:JM,computeState:e=>{let t=e.getFirstTableInSelection();return!t||t.isPivotTable?{isOpen:!1}:{isOpen:!0,props:{table:e.getCoreTable(wM(t))},key:t.id}}}),ZM.add(`TableStyleEditorPanel`,{title:j(`Create custom table style`),Body:XM,computeState:(e,t)=>({isOpen:!0,props:{...t},key:t.styleId??`new`})}),ZM.add(`PivotSidePanel`,{title:(e,t)=>j(`Pivot #%s`,e.model.getters.getPivotFormulaId(t.pivotId)),Body:VM,computeState:(e,t)=>({isOpen:e.isExistingPivot(t.pivotId),props:t,key:`pivot_key_${t.pivotId}`})}),ZM.add(`PivotMeasureDisplayPanel`,{title:(e,t)=>j(`Measure "%s" options`,e.model.getters.getPivot(t.pivotId).getMeasure(t.measure.id).displayName),Body:YA,computeState:(e,t)=>{try{return e.getPivot(t.pivotId).getMeasure(t.measure.id),{isOpen:!0,props:t,key:`pivot_measure_display_${t.pivotId}_${t.measure.id}`}}catch{return{isOpen:!1}}}}),ZM.add(`CarouselPanel`,{title:j(`Carousel`),Body:qD,computeState:(e,t)=>{let n=t.figureId||e.getSelectedFigureId(),r=n&&e.getFigureSheetId(n),i=r?e.isSheetLocked(r):!1;return!n||!e.doesCarouselExist(n)||i?{isOpen:!1}:{isOpen:!0,props:{figureId:n}}}}),ZM.add(`NamedRangesPanel`,{title:j(`Named Ranges`),Body:qA});var QM=class{mutators=[`setSmallThreshhold`];_isSmallCallback=()=>!1;get isSmall(){return this._isSmallCallback()}setSmallThreshhold(e){this._isSmallCallback=e}},$M=class extends wr{mutators=[`open`,`replace`,`toggle`,`close`,`changePanelSize`,`resetPanelSize`,`togglePinPanel`,`closeMainPanel`,`changeSpreadsheetWidth`,`toggleCollapsePanel`];mainPanel=void 0;secondaryPanel;availableWidth=0;screenWidthStore=this.get(QM);get isMainPanelOpen(){return this.mainPanel&&this.mainPanel.componentTag?this.computeState(this.mainPanel).isOpen:!1}get isSecondaryPanelOpen(){return this.secondaryPanel&&this.secondaryPanel.componentTag?this.computeState(this.secondaryPanel).isOpen:!1}get mainPanelProps(){return this.mainPanel?this.getPanelProps(this.mainPanel):void 0}get mainPanelKey(){return this.mainPanel?this.getPanelKey(this.mainPanel):void 0}get secondaryPanelProps(){return this.secondaryPanel?this.getPanelProps(this.secondaryPanel):void 0}get secondaryPanelKey(){return this.secondaryPanel?this.getPanelKey(this.secondaryPanel):void 0}get totalPanelSize(){return(this.mainPanel?.size||0)+(this.secondaryPanel?.size??0)}getPanelProps(e){let t=this.computeState(e);return t.isOpen?(e.currentPanelProps=t.props??e.currentPanelProps,t.props??{}):{}}getPanelKey(e){let t=this.computeState(e);if(t.isOpen)return t.key}open(e,t={}){if(this.screenWidthStore.isSmall)return;let n={currentPanelProps:t,componentTag:e,size:350},r=this.computeState(n);if(!r.isOpen)return;if(!this.mainPanel||!this.mainPanel.isPinned||this.mainPanelKey===r.key){this._openPanel(`mainPanel`,n,r);return}let i=this.mainPanel.isCollapsed?350:this.mainPanel.size;if(!this.secondaryPanel&&i+350>this.availableWidth){this.get(lT).notifyUser({sticky:!1,type:`warning`,text:j(`The window is too small to display multiple side panels.`)});return}this._openPanel(`secondaryPanel`,n,r)}replace(e,t,n={}){let r={currentPanelProps:n,componentTag:e,size:350},i=this.computeState(r);if(!i.isOpen)return;let a=()=>{this.mainPanel?.isCollapsed&&this.toggleCollapsePanel(`mainPanel`)},o=this.mainPanelKey===i.key,s=this.secondaryPanelKey===i.key;if(o&&this.secondaryPanel){this.close(),a();return}if(s){this.closeMainPanel(),this.togglePinPanel(),a();return}let c=this.mainPanelKey===t?`mainPanel`:`secondaryPanel`;this._openPanel(c,r,i)}_openPanel(e,t,n){let r=this[e];r&&t.componentTag!==r.componentTag&&r.currentPanelProps?.onCloseSidePanel?.(),this[e]={currentPanelProps:n.props??{},componentTag:t.componentTag,size:r?.size||350,isCollapsed:r?.isCollapsed||!1,isPinned:r&&`isPinned`in r?r.isPinned:!1},this[e].isCollapsed&&this.toggleCollapsePanel(e)}toggle(e,t){let n=this.mainPanel?.isPinned?this.secondaryPanel:this.mainPanel;n&&e===n.componentTag?this.close():this.open(e,t)}close(){if(this.mainPanel?.isPinned){this.secondaryPanel&&=(this.secondaryPanel.currentPanelProps.onCloseSidePanel?.(),void 0);return}this.mainPanel?.currentPanelProps.onCloseSidePanel?.(),this.mainPanel=void 0}closeMainPanel(){this.mainPanel?.currentPanelProps.onCloseSidePanel?.(),this.mainPanel=this.secondaryPanel||void 0,this.secondaryPanel=void 0}changePanelSize(e,t){let n=this[e];if(!n||`isCollapsed`in n&&n.isCollapsed)return;t=Math.max(t,350);let r=e===`mainPanel`?this.secondaryPanel?.size||0:this.mainPanel?.size||0;t>this.availableWidth-r&&(e===`mainPanel`&&this.secondaryPanel&&(this.secondaryPanel.size=Math.max(this.availableWidth-t,350),r=this.secondaryPanel.size),t=Math.max(this.availableWidth-r,350)),n.size=t}resetPanelSize(e){this[e]&&(this[e].size=350)}togglePinPanel(){this.mainPanel&&(this.mainPanel.isPinned=!this.mainPanel.isPinned,!this.mainPanel.isPinned&&this.secondaryPanel&&(this.secondaryPanel?.currentPanelProps.onCloseSidePanel?.(),this.mainPanel=this.secondaryPanel,this.secondaryPanel=void 0))}toggleCollapsePanel(e){let t=this[e];t&&(t.isCollapsed?(t.isCollapsed=!1,this.changePanelSize(e,350)):(t.isCollapsed=!0,t.size=45))}computeState({componentTag:e,currentPanelProps:t}){let n=ZM.get(e).computeState,r=n?n(this.getters,t):{isOpen:!0,props:t};return r.isOpen?{...r,key:r.key||e}:r}changeSpreadsheetWidth(e){this.availableWidth=e-150,this.secondaryPanel&&e-this.totalPanelSize<150&&(this.secondaryPanel?.currentPanelProps.onCloseSidePanel?.(),this.secondaryPanel=void 0),this.mainPanel&&e-this.totalPanelSize<150&&(this.mainPanel.size=Math.max(e-150,350))}};function eN(e,t,n){let r=e.model.getters.getActiveSheetId(),i=t===`COL`?`FREEZE_COLUMNS`:`FREEZE_ROWS`;e.model.dispatch(i,{sheetId:r,quantity:n}).isCancelledBecause(`MergeOverlap`)&&e.raiseError(Iy)}var tN=class{map={};constructor(e=[]){for(let[t,n]of e)this.set(t,n)}set({sheetId:e,col:t,row:n},r){let i=this.map;i[e]||(i[e]={}),i[e][t]||(i[e][t]={}),i[e][t][n]=r}setMany(e){for(let[t,n]of e)this.set(t,n)}get({sheetId:e,col:t,row:n}){return this.map[e]?.[t]?.[n]}getSheet(e){return this.map[e]}clearSheet(e){delete this.map[e]}has({sheetId:e,col:t,row:n}){return this.map[e]?.[t]?.[n]!==void 0}delete({sheetId:e,col:t,row:n}){delete this.map[e]?.[t]?.[n]}keys(){let e=this.map,t=[];for(let n in e)for(let r in e[n])for(let i in e[n][r])t.push({sheetId:n,col:parseInt(r),row:parseInt(i)});return t}keysForSheet(e){let t=this.map[e];if(!t)return[];let n=[];for(let r in t)for(let i in t[r])n.push({sheetId:e,col:parseInt(r),row:parseInt(i)});return n}*entries(){let e=this.map;for(let t of this.keys()){let{sheetId:n,col:r,row:i}=t;yield[t,e[n][r][i]]}}},nN=class extends wr{mutators=[`enable`,`disable`];isInvalidated=!1;fingerprintColors={[iN]:`#D9D9D9`};isEnabled=!1;colors=new tN;handle(e){switch(wu(e)&&this.isEnabled&&(this.isInvalidated=!0),e.type){case`UNDO`:case`REDO`:case`ACTIVATE_SHEET`:this.isEnabled&&(this.isInvalidated=!0);break}}finalize(){this.isInvalidated&&(this.isInvalidated=!1,this.computeFingerprints())}enable(){this.isEnabled=!0,this.computeFingerprints()}disable(){this.isEnabled=!1,this.colors=new tN}computeFingerprints(){this.colors=new tN;let e=new tN,t=new Set,n=this.getters.getActiveSheetId(),r=this.getters.getCells(n);for(let n in r){let i=r[n],a=this.computeFingerprint(i);if(!a)continue;t.add(a);let o=this.getters.getCellPosition(i.id);e.set(o,a)}this.assignColors(t);for(let[t,n]of e.entries()){let e=this.fingerprintColors[n];this.colors.set(t,e),this.colorSpreadZone(t,e)}}colorSpreadZone(e,t){let n=this.getters.getSpreadZone(e);if(!n)return;let r=e.sheetId;for(let e=n.top;e<=n.bottom;e++)for(let i=n.left;i<=n.right;i++){let n={sheetId:r,col:i,row:e};this.colors.set(n,t)}}assignColors(e){let t=new di(e.size);Object.keys(this.fingerprintColors).forEach(()=>t.next());for(let n of e)this.fingerprintColors[n]||(this.fingerprintColors[n]=Yr(t.next(),.8))}computeFingerprint(e){let t=this.getters.getCellPosition(e.id);return e.isFormula?this.computeFormulaFingerprint(t,e):this.getLiteralFingerprint(t)}computeFormulaFingerprint(e,t){let n=t.compiledFormula.rangeDependencies,r=e.col,i=e.row,a=this.getters.getSheetIds().indexOf(e.sheetId),o={dx:0,dy:0,dSheet:0};for(let e of n){let t=e.zone,[n,s]=e.parts;o.dSheet=this.getters.getSheetIds().indexOf(e.sheetId)-a;let c=$s(e)&&!e.unboundedZone.hasHeader,l=Qs(e)&&!e.unboundedZone.hasHeader,u=c||n?.colFixed?0:r,d=l||n?.rowFixed?0:i,f=!s&&n?.colFixed||s?.colFixed,p=!s&&n?.rowFixed||s?.rowFixed,m=e.unboundedZone.right===void 0,h=e.unboundedZone.bottom===void 0,g=m||f?0:r,_=h||p?0:i,v=Hn({top:t.top-d,left:t.left-u,right:t.right-g,bottom:t.bottom-_});for(let e=v.top;e<=v.bottom;e++)for(let t=v.left;t<=v.right;t++)o.dx+=t,o.dy+=e}let s=t.compiledFormula.normalizedFormula;return rN(o)+s}getLiteralFingerprint(e){switch(this.getters.getEvaluatedCell(e).type){case`number`:case`boolean`:return iN;case`text`:case`empty`:case`error`:return}}};function rN(e){return Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>t).join(`,`)}let iN=`DATA_FINGERPRINT`,aN={name:PE,execute:e=>{let t=e.model.getters.getElementsFromSelection(`COL`);e.model.dispatch(`HIDE_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),dimension:`COL`,elements:t})},isVisible:kE,icon:`o-spreadsheet-Icon.HIDE_COL`},oN={name:j(`Unhide columns`),execute:e=>{let t=e.model.getters.getElementsFromSelection(`COL`);e.model.dispatch(`UNHIDE_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),dimension:`COL`,elements:t})},isVisible:e=>{let t=e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection(`COL`).some(e=>t.includes(e))},icon:`o-spreadsheet-Icon.UNHIDE_COL`},sN={name:j(`Unhide all columns`),execute:e=>{let t=e.model.getters.getActiveSheetId();e.model.dispatch(`UNHIDE_COLUMNS_ROWS`,{sheetId:t,dimension:`COL`,elements:Array.from(Array(e.model.getters.getNumberCols(t)).keys())})},isVisible:e=>e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).length>0,icon:`o-spreadsheet-Icon.UNHIDE_COL`},cN={name:FE,execute:e=>{let t=e.model.getters.getElementsFromSelection(`ROW`);e.model.dispatch(`HIDE_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),dimension:`ROW`,elements:t})},isVisible:DE,icon:`o-spreadsheet-Icon.HIDE_ROW`},lN={name:j(`Unhide rows`),execute:e=>{let t=e.model.getters.getElementsFromSelection(`ROW`);e.model.dispatch(`UNHIDE_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),dimension:`ROW`,elements:t})},isVisible:e=>{let t=e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection(`ROW`).some(e=>t.includes(e))},icon:`o-spreadsheet-Icon.UNHIDE_ROW`},uN={name:j(`Unhide all rows`),execute:e=>{let t=e.model.getters.getActiveSheetId();e.model.dispatch(`UNHIDE_COLUMNS_ROWS`,{sheetId:t,dimension:`ROW`,elements:Array.from(Array(e.model.getters.getNumberRows(t)).keys())})},isVisible:e=>e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).length>0,icon:`o-spreadsheet-Icon.UNHIDE_ROW`},dN={name:j(`Unfreeze`),isVisible:e=>{let{xSplit:t,ySplit:n}=e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId());return t+n>0},execute:e=>e.model.dispatch(`UNFREEZE_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId()}),icon:`o-spreadsheet-Icon.UNFREEZE`},fN={name:j(`Freeze`),icon:`o-spreadsheet-Icon.FREEZE`},pN={name:j(`No rows`),execute:e=>e.model.dispatch(`UNFREEZE_ROWS`,{sheetId:e.model.getters.getActiveSheetId()}),isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).ySplit},mN={name:j(`1 row`),execute:e=>eN(e,`ROW`,1)},hN={name:j(`2 rows`),execute:e=>eN(e,`ROW`,2)},gN={name:j(`Up to current row`),execute:e=>{let{bottom:t}=e.model.getters.getSelectedZone();eN(e,`ROW`,t+1)}},_N={name:j(`No columns`),execute:e=>e.model.dispatch(`UNFREEZE_COLUMNS`,{sheetId:e.model.getters.getActiveSheetId()}),isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).xSplit},vN={name:j(`1 column`),execute:e=>eN(e,`COL`,1)},yN={name:j(`2 columns`),execute:e=>eN(e,`COL`,2)},bN={name:j(`Up to current column`),execute:e=>{let{right:t}=e.model.getters.getSelectedZone();eN(e,`COL`,t+1)}},xN={name:j(`Gridlines`),execute:e=>{let t=e.model.getters.getActiveSheetId();e.model.dispatch(`SET_GRID_LINES_VISIBILITY`,{sheetId:t,areGridLinesVisible:!e.model.getters.getGridLinesVisibility(t)})},isActive:e=>{let t=e.model.getters.getActiveSheetId();return e.model.getters.getGridLinesVisibility(t)}},SN={name:j(`Irregularity map`),execute:e=>{let t=e.getStore(nN);t.isEnabled?t.disable():t.enable()},isReadonlyAllowed:!0,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.IRREGULARITY_MAP`};function CN(e){return{name:j(`%(zoom_percentage)s%`,{zoom_percentage:e}),execute:t=>{t.model.dispatch(`SET_ZOOM`,{zoom:e/100})},isActive:t=>t.model.getters.getViewportZoomLevel()===e/100,isReadonlyAllowed:!0,isEnabledOnLockedSheet:!0,sequence:e}}let wN={name:j(`Formulas`),isActive:e=>e.model.getters.shouldShowFormulas(),execute:e=>e.model.dispatch(`SET_FORMULA_VISIBILITY`,{show:!e.model.getters.shouldShowFormulas()}),isReadonlyAllowed:!0,isEnabledOnLockedSheet:!0},TN={name:e=>{let t=e.model.getters.getSelectedZone();return t.left===t.right?j(`Group column %s`,Zt(t.left)):j(`Group columns %s - %s`,Zt(t.left),Zt(t.right))},execute:e=>kN(e,`COL`),isVisible:e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getSelectedZone(),r=e.model.getters.getHeaderGroupsInZone(t,`COL`,n);return $E(e)&&!r.some(e=>e.start===n.left&&e.end===n.right)},icon:`o-spreadsheet-Icon.GROUP_COLUMNS`},EN={name:e=>{let t=e.model.getters.getSelectedZone();return t.top===t.bottom?j(`Group row %s`,String(t.top+1)):j(`Group rows %s - %s`,String(t.top+1),String(t.bottom+1))},execute:e=>kN(e,`ROW`),isVisible:e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getSelectedZone(),r=e.model.getters.getHeaderGroupsInZone(t,`ROW`,n);return $E(e)&&!r.some(e=>e.start===n.top&&e.end===n.bottom)},icon:`o-spreadsheet-Icon.GROUP_ROWS`},DN={name:e=>{let t=e.model.getters.getSelectedZone();return t.left===t.right?j(`Ungroup column %s`,Zt(t.left)):j(`Ungroup columns %s - %s`,Zt(t.left),Zt(t.right))},execute:e=>AN(e,`COL`),icon:`o-spreadsheet-Icon.UNGROUP_COLUMNS`},ON={name:e=>{let t=e.model.getters.getSelectedZone();return t.top===t.bottom?j(`Ungroup row %s`,String(t.top+1)):j(`Ungroup rows %s - %s`,String(t.top+1),String(t.bottom+1))},execute:e=>AN(e,`ROW`),icon:`o-spreadsheet-Icon.UNGROUP_ROWS`};function kN(e,t){let n=e.model.getters.getSelectedZone(),r=e.model.getters.getActiveSheetId();e.model.dispatch(`GROUP_HEADERS`,{sheetId:r,dimension:t,start:t===`COL`?n.left:n.top,end:t===`COL`?n.right:n.bottom})}function AN(e,t){let n=e.model.getters.getSelectedZone(),r=e.model.getters.getActiveSheetId();e.model.dispatch(`UNGROUP_HEADERS`,{sheetId:r,dimension:t,start:t===`COL`?n.left:n.top,end:t===`COL`?n.right:n.bottom})}function jN(e,t){let n=e.model.getters.getActiveSheetId(),r=e.model.getters.getSelectedZones();return r.length===1&&e.model.getters.getHeaderGroupsInZone(n,t,r[0]).length>0}let MN={name:e=>{let t=e.getStore($M);return t.mainPanel&&t.mainPanel.isPinned?j(`Unpin the side panel`):j(`Pin the side panel`)},isVisible:e=>e.getStore($M).isMainPanelOpen,execute:e=>{e.getStore($M).togglePinPanel()},icon:`o-spreadsheet-Icon.THUMB_TACK`};function NN(e){let t=e.model.dispatch(`CUT`);t.isSuccessful||t.isCancelledBecause(`WrongCutSelection`)&&e.raiseError(j(`This operation is not allowed with multiple selections.`))}var PN=class extends A{replace(e,t){return t.id===void 0&&(t.id=e),this.content[e]=t,this}addChild(e,t,n){return this._replaceChild(e,t,n,{force:!1})}replaceChild(e,t,n){return this._replaceChild(e,t,n,{force:!0})}_replaceChild(e,t,n,r={force:!0}){typeof n!=`function`&&n.id===void 0&&(n.id=e);let i=t.splice(0,1)[0],a=this.content[i];if(!a)throw Error(`Path ${i+`:`+t.join(`:`)} not found`);for(let e of t){let n=a.children;if(!n||typeof n==`function`)throw Error(`${e} is either not a node or it's dynamically computed`);if(a=n.find(t=>t.id===e),!a)throw Error(`Path ${i+`:`+t.join(`:`)} not found`)}a.children||=[];let o=a.children;if(!o||typeof o==`function`)throw Error(`${t} is either not a node or it's dynamically computed`);if(`id`in n){let e=o.findIndex(e=>`id`in e&&e.id===n.id);if(e>-1){if(!r.force)throw Error(`A child with the id "${n.id}" already exists.`);return a.children.splice(e,1,n),this}}return a.children.push(n),this}getMenuItems(){return p(this.getAll())}};let FN={MergeIsDestructive:j(`Merging these cells will only preserve the top-leftmost value. Merge anyway?`),MergeInFilter:j(`You can't merge cells inside of an existing filter.`)};function IN(e,t,n){let r=e.model.dispatch(`ADD_MERGE`,{sheetId:t,target:n});r.isCancelledBecause(`MergeInTable`)?e.raiseError(FN.MergeInFilter):r.isCancelledBecause(`MergeIsDestructive`)&&e.askConfirmation(FN.MergeIsDestructive,()=>{e.model.dispatch(`ADD_MERGE`,{sheetId:t,target:n,force:!0})})}let LN={name:j(`Undo`),shortcut:`Ctrl+Z`,execute:e=>e.model.dispatch(`REQUEST_UNDO`),isEnabled:e=>e.model.getters.canUndo(),isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.UNDO`},RN={name:j(`Redo`),shortcut:`Ctrl+Y`,execute:e=>e.model.dispatch(`REQUEST_REDO`),isEnabled:e=>e.model.getters.canRedo(),isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.REDO`},zN={name:j(`Copy`),shortcut:`Ctrl+C`,isReadonlyAllowed:!0,execute:async e=>{e.model.dispatch(`COPY`),await e.clipboard.write(await e.model.getters.getClipboardTextAndImageContent())},isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.CLIPBOARD`},BN={name:j(`Cut`),shortcut:`Ctrl+X`,execute:async e=>{NN(e),await e.clipboard.write(await e.model.getters.getClipboardTextAndImageContent())},icon:`o-spreadsheet-Icon.CUT`},VN={name:j(`Paste`),shortcut:`Ctrl+V`,execute:hE,icon:`o-spreadsheet-Icon.PASTE`},HN={name:j(`Paste special`),isVisible:e=>!e.model.getters.isCutOperation(),icon:`o-spreadsheet-Icon.PASTE`},UN={name:j(`Paste as value`),shortcut:`Ctrl+Shift+V`,execute:gE},WN={name:j(`Paste format only`),execute:vE},GN={name:j(`Find and replace`),shortcut:`Ctrl+H`,isReadonlyAllowed:!0,isEnabledOnLockedSheet:!0,execute:e=>{e.openSidePanel(`FindAndReplace`,{})},isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.SEARCH`},KN={name:j(`Delete values`),execute:e=>e.model.dispatch(`DELETE_UNFILTERED_CONTENT`,{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})},qN={name:CE,execute:wE,isVisible:e=>TE(`ROW`,e)},JN={...qN,isVisible:$E},YN={name:yE,execute:bE},XN={name:EE,execute:OE,isVisible:e=>TE(`COL`,e)},ZN={...XN,isVisible:$E},QN={name:xE,execute:SE},$N={name:j(`Delete cells`),isVisible:$E},eP={name:j(`Delete cell and shift up`),execute:e=>{let t=e.model.getters.getSelectedZone();mw(e,e.model.dispatch(`DELETE_CELL`,{zone:t,shiftDimension:`ROW`}))}},tP={name:j(`Delete cell and shift left`),execute:e=>{let t=e.model.getters.getSelectedZone();mw(e,e.model.dispatch(`DELETE_CELL`,{zone:t,shiftDimension:`COL`}))}},nP={name:j(`Merge cells`),isEnabled:e=>!aP(e),isActive:e=>oP(e),execute:e=>sP(e),icon:`o-spreadsheet-Icon.MERGE_CELL`},rP={name:()=>j(`Edit table`),execute:e=>e.openSidePanel(`TableSidePanel`,{}),icon:`o-spreadsheet-Icon.EDIT_TABLE`},iP={name:()=>j(`Delete table`),execute:QE,icon:`o-spreadsheet-Icon.DELETE_TABLE`};function aP(e){let t=e.model.getters.getSelectedZones(),{sheetId:n}=e.model.getters.getActivePosition(),{xSplit:r,ySplit:i}=e.model.getters.getPaneDivisions(n);return t.every(e=>Xn(e)===1)||Qn(t,r,i)||Pn(t)}function oP(e){if(aP(e))return!1;let t=e.model.getters.getActiveSheetId();return e.model.getters.getSelectedZones().some(n=>e.model.getters.getMergesInZone(t,n).length>0)}function sP(e){if(aP(e))return;let t=e.model.getters.getSelectedZones(),n=e.model.getters.getActiveSheetId();if(oP(e)){let r=t.flatMap(t=>e.model.getters.getMergesInZone(n,t));e.model.dispatch(`REMOVE_MERGE`,{sheetId:n,target:r})}else IN(e,n,t)}let cP={name:j(`See pivot properties`),execute(e){let t=e.model.getters.getActivePosition(),n=e.model.getters.getPivotIdFromPosition(t);e.openSidePanel(`PivotSidePanel`,{pivotId:n})},isVisible:e=>{let t=e.model.getters.getActivePosition(),n=e.model.getters.getPivotIdFromPosition(t);return!e.isSmall&&n&&e.model.getters.isExistingPivot(n)||!1},isReadonlyAllowed:!0,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.PIVOT`},lP={name:j(`Ascending`),execute:e=>xP(e,e.model.getters.getActivePosition(),`asc`),isActive:e=>e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())===`asc`},uP={name:j(`Descending`),execute:e=>xP(e,e.model.getters.getActivePosition(),`desc`),isActive:e=>e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())===`desc`},dP={name:j(`No sorting`),execute:e=>xP(e,e.model.getters.getActivePosition(),`none`),isActive:e=>e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())===`none`},fP={name:j(`Convert to individual formulas`),execute(e){let t=e.model.getters.getActivePosition(),n=e.model.getters.getCorrespondingFormulaCell(t),r=e.model.getters.getPivotIdFromPosition(t);if(!n||!r)return;let{sheetId:i,col:a,row:o}=e.model.getters.getCellPosition(n.id),s=e.model.getters.getPivot(r);s.init(),s.isValid()&&e.model.dispatch(`SPLIT_PIVOT_FORMULA`,{sheetId:i,col:a,row:o,pivotId:r})},isVisible:e=>{let t=e.model.getters.getActivePosition(),n=e.model.getters.getPivotIdFromPosition(t);if(!n)return!1;let r=e.model.getters.getPivot(n),i=e.model.getters.getEvaluatedCell(t);return r.isValid()&&e.model.getters.isSpillPivotFormula(t)&&i.type!==`error`},icon:`o-spreadsheet-Icon.PIVOT`},pP={name:j(`Group pivot dimensions`),execute:e=>{let t=SP(e);if(!t)return;let{pivotId:n,values:r,field:i}=t,a=e.model.getters.getPivot(n),o=x(e.model.getters.getPivotCoreDefinition(n));if(!i.isCustomField)CP(o,r,i,a.getFields());else{let e=(o.customFields||{})[i.name];if(!e)return;wP(e,r)}e.model.dispatch(`UPDATE_PIVOT`,{pivotId:n,pivot:o})},isVisible:e=>{let t=SP(e);if(!t)return!1;let{pivotId:n,values:r,field:i}=t,a=e.model.getters.getPivot(n);return r.length>1&&(i.isCustomField||Uj.get(a.type).canHaveCustomGroup(i))}},mP={name:j(`Group all remaining dimensions`),execute:e=>{let t=SP(e);if(!t)return;let{pivotId:n,field:r}=t,i=e.model.getters.getPivot(n),a=x(e.model.getters.getPivotCoreDefinition(n)),o=r.isCustomField?(a.customFields||{})[r.name]:Vg(a,r,i.getFields());o&&(o.groups.push({name:Ig(j(`Others`),o),values:[],isOtherGroup:!0}),Bg(a,r.name,o.name),e.model.dispatch(`UPDATE_PIVOT`,{pivotId:n,pivot:a}))},isVisible:e=>{let t=SP(e);if(!t)return!1;let{pivotId:n,field:r,values:i}=t;return DP(e,n,i,r)}},hP={name:j(`Ungroup pivot dimensions`),execute:e=>{let t=SP(e);if(!t)return;let{pivotId:n,values:r,field:i}=t,a=e.model.getters.getPivot(n),o=x(e.model.getters.getPivotCoreDefinition(n));TP(o,r,i,a.getFields()),e.model.dispatch(`UPDATE_PIVOT`,{pivotId:n,pivot:o})},isVisible:e=>{let t=SP(e);if(!t)return!1;let{pivotId:n,values:r,field:i}=t,a=e.model.getters.getPivot(n),o=e.model.getters.getPivotCoreDefinition(n);if(!i.isCustomField){let e=Vg(o,i,a.getFields());if(![...o.rows,...o.columns].some(t=>t.fieldName===e.name))return!1}return EP(o,r,i,a.getFields())}},gP={name:e=>{let t=e.model.getters.getActivePosition(),n=yP(e.model.getters,t);return n.isPivotGroup?n.isCollapsed?j(`Expand`):j(`Collapse`):``},execute(e){Hg(e.model.getters.getActivePosition(),e)},isVisible:e=>{let t=e.model.getters.getActivePosition(),n=yP(e.model.getters,t),r=e.model.getters.getPivotStyleAtPosition(t);return n.isPivotGroup&&!r?.pivotStyle.tabularForm}},_P={name:j(`Collapse all`),execute(e){let t=e.model.getters.getActivePosition(),n=yP(e.model.getters,t);if(!n.isPivotGroup)return;let{pivotCell:r,pivotId:i,siblingDomains:a}=n,o=x(e.model.getters.getPivotCoreDefinition(i));o.collapsedDomains=o.collapsedDomains||{COL:[],ROW:[]};let s=[...o.collapsedDomains[r.dimension]||[],...a],c=s.filter((e,t)=>t===s.findIndex(t=>T(t,e)));o.collapsedDomains[r.dimension]=c,e.model.dispatch(`UPDATE_PIVOT`,{pivotId:i,pivot:o})},isVisible:e=>{let t=e.model.getters.getActivePosition(),n=yP(e.model.getters,t),r=e.model.getters.getPivotStyleAtPosition(t);if(!n.isPivotGroup||r?.pivotStyle.tabularForm)return!1;let{pivotCell:i,pivotId:a,siblingDomains:o}=n,s=e.model.getters.getPivotCoreDefinition(a);return!o.every(e=>(s.collapsedDomains?.[i.dimension]||[]).some(t=>T(t,e)))}},vP={name:j(`Expand all`),execute(e){let t=e.model.getters.getActivePosition(),n=yP(e.model.getters,t);if(!n.isPivotGroup)return;let{pivotCell:r,pivotId:i,siblingDomains:a}=n,o=x(e.model.getters.getPivotCoreDefinition(i));o.collapsedDomains=o.collapsedDomains||{COL:[],ROW:[]};let s=(o.collapsedDomains[r.dimension]||[]).filter(e=>!a.find(t=>T(t,e)));o.collapsedDomains[r.dimension]=s,e.model.dispatch(`UPDATE_PIVOT`,{pivotId:i,pivot:o})},isVisible:e=>{let t=e.model.getters.getActivePosition(),n=yP(e.model.getters,t),r=e.model.getters.getPivotStyleAtPosition(t);if(!n.isPivotGroup||r?.pivotStyle.tabularForm)return!1;let{pivotCell:i,pivotId:a,siblingDomains:o}=n;return(e.model.getters.getPivotCoreDefinition(a).collapsedDomains?.[i.dimension]||[]).some(e=>o.some(t=>T(t,e)))}};function yP(e,t){if(!e.isSpillPivotFormula(t))return{isPivotGroup:!1};let n=e.getPivotCellFromPosition(t),r=e.getPivotIdFromPosition(t);if(n.type!==`HEADER`||!r||!n.domain.length)return{isPivotGroup:!1};let i=e.getPivotCoreDefinition(r),a=e.isDashboard(),o=n.dimension===`COL`?i.columns:i.rows;if(!(!a&&n.domain.length!==o.length))return{isPivotGroup:!1};let s=(i.collapsedDomains?.[n.dimension]??[]).some(e=>T(e,n.domain)),c=e.getPivot(r).getExpandedTableStructure(),l=n.domain.length-1;return{isPivotGroup:!0,isCollapsed:s,pivotCell:n,pivotId:r,siblingDomains:n.dimension===`ROW`?c.getRowDomainsAtDepth(l):c.getColumnDomainsAtDepth(l)}}function bP(e,t){let n=e.getPivotIdFromPosition(t);if(!n||!e.isExistingPivot(n)||!e.isSpillPivotFormula(t)||!e.getPivot(n).isValid())return!1;let r=e.getPivotCellFromPosition(t);return r.type===`VALUE`||r.type===`MEASURE_HEADER`}function xP(e,t,n){let r=e.model.getters.getPivotIdFromPosition(t),i=e.model.getters.getPivotCellFromPosition(t);if(i.type===`EMPTY`||i.type===`HEADER`||i.type===`ROW_GROUP_NAME`||!r)return;if(n===`none`){e.model.dispatch(`UPDATE_PIVOT`,{pivotId:r,pivot:{...e.model.getters.getPivotCoreDefinition(r),sortedColumn:void 0}});return}let a=mj(e.model.getters.getPivot(r),i.domain).colDomain;e.model.dispatch(`UPDATE_PIVOT`,{pivotId:r,pivot:{...e.model.getters.getPivotCoreDefinition(r),sortedColumn:{domain:a,order:n,measure:i.measure}}})}function SP(e){let t,n,r=[];for(let i of e.model.getters.getSelectedZones()){let a=e.model.getters.getActiveSheetId();for(let o of Vn(a,i)){let i=e.model.getters.getPivotIdFromPosition(o);if(!t)t=i;else if(i&&t!==i)return;if(!t)continue;let a=e.model.getters.getPivotCellFromPosition(o);if(a.type!==`HEADER`||!e.model.getters.isSpillPivotFormula(o))continue;let s=a.domain.at(-1)?.field;if(!n&&s)n=s;else if(n&&s&&n!==s)return;r.push(a)}}if(!t||!n||r.length===0)return;let i=e.model.getters.getPivot(t).getFields()[n];if(!i)return;let a=r.map(e=>e.domain.at(-1)?.value).filter(e=>e!==void 0);return{pivotId:t,values:a,field:i}}function CP(e,t,n,r){let i=Vg(e,n,r);zg(t,i);let a={name:Ig(j(`Group`),i),values:t};i.groups.push(a),e.customFields||={},e.customFields[i.name]=i,Bg(e,n.name,i.name)}function wP(e,t){let n=new Set,r=[];for(let i of t){let t=e.groups.find(e=>e.name===i);t?(r.push(t),t.values.forEach(e=>n.add(e))):n.add(i)}if(r.some(e=>e.isOtherGroup))e.groups=e.groups.filter(e=>e.isOtherGroup||!r.includes(e));else if(r.length===0){let n={name:Ig(j(`Group`),e),values:t};e.groups.push(n)}else{let t=r.slice(1);e.groups=e.groups.filter(e=>!t.includes(e)),r[0].values=Array.from(n)}}function TP(e,t,n,r){let i;if(!n.isCustomField)i=Vg(e,n,r),i.groups.some(e=>e.isOtherGroup)&&t.some(e=>!i?.groups.some(t=>t.values.includes(e)))&&(i.groups=i.groups.filter(e=>!e.isOtherGroup)),zg(t,i);else{if(i=(e.customFields||{})[n.name],!i)return;i.groups=i.groups.filter(e=>!t.includes(e.name))}i.groups.every(e=>e.values.length===0&&!e.isOtherGroup)&&(OP(e,i.name),delete e.customFields?.[i.name])}function EP(e,t,n,r){if(n.isCustomField){let r=(e.customFields||{})[n.name];return r?r.groups.some(e=>t.includes(e.name)):!1}else return Vg(e,n,r).groups.some(e=>e.isOtherGroup||t.some(t=>e.values.includes(t)))}function DP(e,t,n,r){let i=e.model.getters.getPivot(t),a=e.model.getters.getPivotCoreDefinition(t),o=r.isCustomField?(a.customFields||{})[r.name]:Object.values(a.customFields||{}).find(e=>e.parentField===r.name),s=i.definition.getDimension(r.name);if(!s||!o||EP(a,n,r,i.getFields()))return!1;let c=new Set(i.getPossibleFieldValues(s).map(e=>e.value)),l=r.isCustomField?o.groups.map(e=>e.name):o.groups.flatMap(e=>e.values);for(let e of[...n,...l])c.delete(e);return c.size===0}function OP(e,t){let n=e.customFields?.[t];if(!n)return;let r=[...e.rows,...e.columns].some(e=>e.fieldName===n.parentField);for(let i of[e.rows,e.columns]){let e=i.findIndex(e=>e.fieldName===t);e!==-1&&(r?i.splice(e,1):i.splice(e,1,{fieldName:n.parentField}))}}let kP=new PN;kP.add(`cut`,{...BN,sequence:10}).add(`copy`,{...zN,sequence:20}).add(`paste`,{...VN,sequence:30}).add(`paste_special`,{...HN,sequence:40,separator:!0}).addChild(`paste_value_only`,[`paste_special`],{...UN,sequence:10}).addChild(`paste_format_only`,[`paste_special`],{...WN,sequence:20}).add(`add_row_before`,{...aD,sequence:70}).add(`add_column_before`,{...dD,sequence:90}).add(`insert_cell`,{...mD,sequence:100,separator:!0}).addChild(`insert_cell_down`,[`insert_cell`],{...hD,name:j(`Shift down`),sequence:10}).addChild(`insert_cell_right`,[`insert_cell`],{...gD,name:j(`Shift right`),sequence:20}).add(`delete_row`,{...JN,sequence:110,icon:`o-spreadsheet-Icon.TRASH`}).add(`delete_column`,{...ZN,sequence:120,icon:`o-spreadsheet-Icon.TRASH`}).add(`delete_cell`,{...$N,sequence:130,separator:!0,icon:`o-spreadsheet-Icon.TRASH`}).addChild(`delete_cell_up`,[`delete_cell`],{...eP,name:j(`Shift up`),sequence:10,icon:`o-spreadsheet-Icon.DELETE_CELL_SHIFT_UP`}).addChild(`delete_cell_left`,[`delete_cell`],{...tP,name:j(`Shift left`),sequence:20,icon:`o-spreadsheet-Icon.DELETE_CELL_SHIFT_LEFT`}).add(`edit_table`,{...rP,isVisible:qE,isEnabled:e=>!e.isSmall,sequence:140}).add(`delete_table`,{...iP,isVisible:qE,sequence:145,separator:!0}).add(`insert_link`,{...jD,name:GE,sequence:150,separator:!0}).add(`pivot_headers_group`,{sequence:155,icon:`o-spreadsheet-Icon.PLUS_IN_BOX`,...pP}).add(`pivot_group_remaining`,{sequence:155,icon:`o-spreadsheet-Icon.PLUS_IN_BOX`,...mP}).add(`pivot_headers_ungroup`,{sequence:155,icon:`o-spreadsheet-Icon.MINUS_IN_BOX`,...hP}).add(`collapse_pivot`,{sequence:156,name:j(`Expand/Collapse`),icon:`o-spreadsheet-Icon.COLLAPSE`}).addChild(`toggle_collapse_pivot_cell`,[`collapse_pivot`],{sequence:10,...gP}).addChild(`collapse_all_pivot`,[`collapse_pivot`],{sequence:20,..._P}).addChild(`expand_all_pivot`,[`collapse_pivot`],{sequence:30,...vP}).add(`pivot_sorting`,{name:j(`Sort pivot`),sequence:155,icon:`o-spreadsheet-Icon.SORT_RANGE`,isVisible:e=>{let t=e.model.getters.getActivePosition();return bP(e.model.getters,t)}}).add(`pivot_fix_formulas`,{...fP,sequence:160}).add(`pivot_properties`,{...cP,sequence:170,separator:!0}).addChild(`pivot_sorting_asc`,[`pivot_sorting`],{...lP,sequence:10}).addChild(`pivot_sorting_desc`,[`pivot_sorting`],{...uP,sequence:20}).addChild(`pivot_sorting_none`,[`pivot_sorting`],{...dP,sequence:30});let AP={name:j(`Sort range`),isVisible:$E,icon:`o-spreadsheet-Icon.SORT_RANGE`},jP={name:j(`Ascending (A ⟶ Z)`),execute:e=>{let{anchor:t,zones:n}=e.model.getters.getSelection();xw(e,e.model.getters.getActiveSheetId(),t.cell,n[0],`asc`)},icon:`o-spreadsheet-Icon.SORT_ASCENDING`},MP={name:j(`Data cleanup`),icon:`o-spreadsheet-Icon.DATA_CLEANUP`},NP={name:j(`Remove duplicates`),execute:e=>{Xn(e.model.getters.getSelectedZone())===1&&e.model.selection.selectTableAroundSelection(),e.openSidePanel(`RemoveDuplicates`,{})},isEnabled:e=>!e.isSmall},PP={name:j(`Trim whitespace`),execute:e=>{e.model.dispatch(`TRIM_WHITESPACE`)}},FP={name:j(`Descending (Z ⟶ A)`),execute:e=>{let{anchor:t,zones:n}=e.model.getters.getSelection();xw(e,e.model.getters.getActiveSheetId(),t.cell,n[0],`desc`)},icon:`o-spreadsheet-Icon.SORT_DESCENDING`},IP={...tD},LP={...tD,isActive:e=>KE(e)},RP={name:j(`Split text to columns`),sequence:1,execute:e=>e.openSidePanel(`SplitToColumns`,{}),isEnabled:e=>!e.isSmall&&e.model.getters.isSingleColSelected(),icon:`o-spreadsheet-Icon.SPLIT_TEXT`},zP={name:j(`Column statistics`),execute:e=>e.openSidePanel(`ColumnStats`,{}),icon:`o-spreadsheet-Icon.COLUMN_STATS`},BP={id:`reinsert_dynamic_pivot`,name:j(`Re-insert dynamic pivot`),sequence:60,icon:`o-spreadsheet-Icon.INSERT_PIVOT`,children:[zE],isVisible:e=>e.model.getters.getPivotIds().some(t=>e.model.getters.getPivot(t).isValid())},VP={id:`reinsert_static_pivot`,name:j(`Re-insert static pivot`),sequence:70,icon:`o-spreadsheet-Icon.INSERT_PIVOT`,children:[BE],isVisible:e=>e.model.getters.getPivotIds().some(t=>e.model.getters.getPivot(t).isValid())},HP=new PN;HP.add(`cut`,{...BN,sequence:10}).add(`copy`,{...zN,sequence:20}).add(`paste`,{...VN,sequence:30}).add(`paste_special`,{...HN,sequence:40,separator:!0}).addChild(`paste_value_only`,[`paste_special`],{...UN,sequence:10}).addChild(`paste_format_only`,[`paste_special`],{...WN,sequence:20}).add(`sort_columns`,{...AP,name:e=>e.model.getters.getActiveCols().size>1?j(`Sort columns`):j(`Sort column`),sequence:50,separator:!0}).addChild(`sort_ascending`,[`sort_columns`],{...jP,sequence:10}).addChild(`sort_descending`,[`sort_columns`],{...FP,sequence:20}).add(`column_statistics`,{...zP,sequence:60,separator:!0}).add(`add_column_before`,{...lD,sequence:70}).add(`add_column_after`,{...fD,sequence:80}).add(`delete_column`,{...XN,sequence:90,icon:`o-spreadsheet-Icon.TRASH`}).add(`clear_column`,{...QN,sequence:100,icon:`o-spreadsheet-Icon.CLEAR`}).add(`hide_columns`,{...aN,sequence:105,separator:!0}).add(`unhide_columns`,{...oN,sequence:106,separator:!0}).add(`conditional_formatting`,{...DA,sequence:110,separator:!0}).add(`edit_table`,{...rP,isVisible:qE,sequence:120}).add(`delete_table`,{...iP,isVisible:qE,sequence:125,separator:!0}).add(`group_columns`,{sequence:150,...TN}).add(`ungroup_columns`,{sequence:155,...DN,isVisible:e=>jN(e,`COL`)});let UP={CannotHideAllRows:j(`Cannot hide all the rows of a sheet.`),CannotHideAllColumns:j(`Cannot hide all the columns of a sheet.`)};function WP(e,t,n,r,i){let a=e.model.getters.getHeaderGroup(t,n,r,i);if(!a)return;let o=a.isFolded?`UNFOLD_HEADER_GROUP`:`FOLD_HEADER_GROUP`,s=e.model.dispatch(o,{sheetId:t,dimension:n,start:a.start,end:a.end});if(!s.isSuccessful&&s.isCancelledBecause(`NotEnoughElements`)){let t=n===`ROW`?UP.CannotHideAllRows:UP.CannotHideAllColumns;e.raiseError(t)}}function GP(e,t){return p([{id:`unfold_all`,name:j(t===`ROW`?`Expand all row groups`:`Expand all column groups`),execute:n=>{n.model.dispatch(`UNFOLD_ALL_HEADER_GROUPS`,{sheetId:e,dimension:t})},icon:`o-spreadsheet-Icon.EXPAND`},{id:`fold_all`,name:j(t===`ROW`?`Collapse all row groups`:`Collapse all column groups`),execute:n=>{n.model.dispatch(`FOLD_ALL_HEADER_GROUPS`,{sheetId:e,dimension:t})},icon:`o-spreadsheet-Icon.COLLAPSE`}])}function KP(e,t,n,r){return[...p([{id:`toggle_group`,name:e=>{let i=e.model.getters.getActiveSheetId();return e.model.getters.isGroupFolded(i,t,n,r)?j(t===`ROW`?`Expand row group`:`Expand column group`):j(t===`ROW`?`Collapse row group`:`Collapse column group`)},execute:e=>{WP(e,e.model.getters.getActiveSheetId(),t,n,r)},icon:e=>{let i=e.model.getters.getActiveSheetId();return e.model.getters.isGroupFolded(i,t,n,r)?`o-spreadsheet-Icon.EXPAND`:`o-spreadsheet-Icon.COLLAPSE`}},{id:`remove_group`,name:j(t===`ROW`?`Remove row group`:`Remove column group`),execute:e=>{let i=e.model.getters.getActiveSheetId();e.model.dispatch(`UNGROUP_HEADERS`,{sheetId:i,dimension:t,start:n,end:r})},icon:`o-spreadsheet-Icon.TRASH`,separator:!0}]),...GP(e,t)]}let qP=new PN;qP.add(`group_columns`,{sequence:10,...TN,isVisible:()=>!0,isEnabled:TN.isVisible}).add(`group_rows`,{sequence:20,...EN,isVisible:()=>!0,isEnabled:EN.isVisible});let JP=new PN;JP.add(`ungroup_columns`,{sequence:10,...DN,isEnabled:e=>jN(e,`COL`)}).add(`ungroup_rows`,{sequence:20,...ON,isEnabled:e=>jN(e,`ROW`)});let YP=new PN;YP.add(`cut`,{...BN,sequence:10}).add(`copy`,{...zN,sequence:20}).add(`paste`,{...VN,sequence:30}).add(`paste_special`,{...HN,sequence:40,separator:!0}).addChild(`paste_value_only`,[`paste_special`],{...UN,sequence:10}).addChild(`paste_format_only`,[`paste_special`],{...WN,sequence:20}).add(`add_row_before`,{...rD,sequence:50}).add(`add_row_after`,{...oD,sequence:60}).add(`delete_row`,{...qN,sequence:70,icon:`o-spreadsheet-Icon.TRASH`}).add(`clear_row`,{...YN,sequence:80,icon:`o-spreadsheet-Icon.CLEAR`}).add(`hide_rows`,{...cN,sequence:85,separator:!0}).add(`unhide_rows`,{...lN,sequence:86,separator:!0}).add(`conditional_formatting`,{...DA,sequence:90,separator:!0}).add(`group_rows`,{sequence:100,...EN}).add(`ungroup_rows`,{sequence:110,...ON,isVisible:e=>jN(e,`ROW`)});var XP=class extends wr{highlightStore=this.get(cT);constructor(e){super(e),this.highlightStore.register(this)}get highlights(){let e=this.model.getters.getActivePosition(),t=this.model.getters.getArrayFormulaSpreadingOn(e),n=t?this.model.getters.getSpreadZone(t,{ignoreSpillError:!0}):this.model.getters.getSpreadZone(e,{ignoreSpillError:!0});if(!n)return[];let r=this.getters.getPivotStyleAtPosition(e);if(r?.pivotStyle?.tableStyleId&&r.pivotStyle.tableStyleId!==`None`)return[];let i=this.model.getters.isArrayFormulaSpillBlocked(t??e);return[{range:this.model.getters.getRangeFromZone(e.sheetId,n),dashed:i,color:`#17A2B8`,noFill:!0,thinLine:!0}]}},ZP=class extends wr{mutators=[`focusClient`,`unfocusClient`,`showClientTag`,`hideClientTag`,`jumpToClient`];_showClientTag=!1;clientFocusTimeout={};constructor(e){super(e),this.onDispose(()=>{for(let e in this.clientFocusTimeout)this.unfocusClient(e)})}get focusedClients(){let e=new Set;return this.model.getters.getConnectedClients().forEach(t=>{(this._showClientTag||this.clientFocusTimeout[t.id]!==void 0)&&e.add(t.id)}),e}jumpToClient(e){let t=this.model.getters.getClient(e);this.focusClient(e),t.position&&(this.model.dispatch(`ACTIVATE_SHEET`,{sheetIdTo:t.position.sheetId,sheetIdFrom:this.getters.getActiveSheetId()}),this.model.dispatch(`SCROLL_TO_CELL`,{col:t.position.col,row:t.position.row}))}showClientTag(){this._showClientTag=!0}hideClientTag(){this._showClientTag=!1}focusClient(e){this.clientFocusTimeout[e]&&clearTimeout(this.clientFocusTimeout[e]),this.clientFocusTimeout[e]=setTimeout(()=>this.unfocusClient(e),3e3)}unfocusClient(e){this.clientFocusTimeout[e]&&clearTimeout(this.clientFocusTimeout[e]),this.clientFocusTimeout[e]=void 0}};function QP(e){let n=null,r,i,a,o,s=`all`,c=e.model.getters,l=e=>e.preventDefault(),u=()=>removeEventListener(`keydown`,l,{capture:!0}),d=[],f=()=>{clearTimeout(n),n=null,d.forEach(e=>e()),d=[]},p,m,h=t=>{if(r=t,n)return;let l=c.getActiveSheetId(),u=pm(e.model.getters.getViewportZoomLevel()),d=Pm(e,r,u),{x:f,y:m}=c.getMainViewportCoordinates(),{top:g,left:_,bottom:v,right:y}=c.getActiveMainViewport(),{scrollX:b,scrollY:ee}=c.getActiveSheetScrollInfo(),{xSplit:te,ySplit:ne}=c.getPaneDivisions(l),re=!1,ie=140,ae=d.clientX-u.x,oe=c.getColIndex(ae);if(s!==`vertical`){let t=i.clientX-u.x,n=c.getEdgeScrollCol(ae,t,a);if(n.canEdgeScroll){re=!0,ie=Math.min(ie,n.delay);let t=oe;switch(n.direction){case`reset`:oe=t=te;break;case 1:oe=y,t=_+1;break;case-1:for(oe=_-1;e.model.getters.isColHidden(l,oe);)oe--;t=oe;break}b=c.getColDimensions(l,t).start-f}}let se=d.clientY-u.y,ce=c.getRowIndex(se);if(s!==`horizontal`){let t=i.clientY-u.y,n=c.getEdgeScrollRow(se,t,o);if(n.canEdgeScroll){re=!0,ie=Math.min(ie,n.delay);let t=ce;switch(n.direction){case`reset`:ce=t=ne;break;case 1:ce=v,t=g+1;break;case-1:for(ce=g-1;e.model.getters.isRowHidden(l,ce);)ce--;t=ce;break}ee=e.model.getters.getRowDimensions(l,t).start-m}}re||(oe=$P(oe,ae,c.getNumberCols(l)-1),ce=$P(ce,se,c.getNumberRows(l)-1)),p?.(oe,ce,r),re&&(e.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:b,offsetY:ee}),n=setTimeout(()=>{n=null,h(r)},Math.round(ie))),i={clientX:d.clientX,clientY:d.clientY}},g=()=>{m?.(),f()};return(0,t.onWillUnmount)(()=>{f()}),(0,t.useEffect)(()=>{f()},()=>[c.getActiveSheetId()]),{start:(t,n,r,c=`all`)=>{f();let _=pm(e.model.getters.getViewportZoomLevel());s=c,a=t.clientX-_.x,o=t.clientY-_.y,i={clientX:t.clientX,clientY:t.clientY},p=n,m=r,addEventListener(`keydown`,l,{capture:!0}),d.push(bT(h,g),u)}}}function $P(e,t,n){return e===-1?t<0?0:n:e}var eF=class extends t.Component{static template=`o-spreadsheet-Autofill`;static props={position:Object,isVisible:Boolean};state=(0,t.useState)({position:{x:0,y:0},handler:!1});dragNDropGrid=QP(this.env);get style(){let{x:e,y:t}=this.props.position;return W({top:`${t}px`,left:`${e}px`,visibility:this.props.isVisible?`visible`:`hidden`})}get handlerStyle(){let{x:e,y:t}=this.state.handler?this.state.position:this.props.position;return W({top:`${t}px`,left:`${e}px`})}get styleNextValue(){let{x:e,y:t}=this.state.position;return W({top:`${t+5}px`,left:`${e+15}px`})}getTooltip(){let e=this.env.model.getters.getAutofillTooltip();return e&&!e.component&&(e.component=tF),e}onMouseDown(e){this.state.handler=!0;let t=Pm(this.env,e),n=this.env.model.getters.getViewportZoomLevel(),r,i,a={x:e.clientX/n-this.props.position.x,y:e.clientY/n-this.props.position.y};this.dragNDropGrid.start(t,(e,t,o)=>{if(this.state.position={x:o.clientX/n-a.x,y:o.clientY/n-a.y},r!==e||i!==t){let n=this.env.model.getters.getActiveSheetId(),a=this.env.model.getters.getNumberCols(n),o=this.env.model.getters.getNumberRows(n);r=e===-1?r:S(e,0,a),i=t===-1?i:S(t,0,o),r!==void 0&&i!==void 0&&this.env.model.dispatch(`AUTOFILL_SELECT`,{col:r,row:i})}},()=>{this.state.handler=!1,this.state.position={...this.props.position},this.env.model.dispatch(`AUTOFILL`)})}onDblClick(){this.env.model.dispatch(`AUTOFILL_AUTO`)}},tF=class extends t.Component{static props={content:String};static template=t.xml`
84
+ `}];var qM=class extends t.Component{static template=`o-spreadsheet-SplitIntoColumnsPanel`;static components={ValidationMessages:$D,Section:Z,Checkbox:IT,Select:Ty};static props={onCloseSidePanel:Function};state=(0,t.useState)({separatorValue:`auto`,addNewColumns:!1,customSeparator:``});setup(){let e=O(Er);(0,t.useEffect)(e=>{e!==`inactive`&&this.props.onCloseSidePanel()},()=>[e.focusMode]),(0,t.onMounted)(()=>{e.activeComposer.stopEdition()})}onSeparatorChange(e){this.state.separatorValue=e}updateCustomSeparator(e){e.target&&(this.state.customSeparator=e.target.value)}updateAddNewColumnsCheckbox(e){this.state.addNewColumns=e}confirm(){GM(this.env,this.separatorValue,this.state.addNewColumns).isSuccessful&&this.props.onCloseSidePanel()}get errorMessages(){let e=this.env.model.canDispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!0}).reasons,t=new Set;for(let n of e)switch(n){case`SplitWillOverwriteContent`:case`EmptySplitSeparator`:break;default:t.add(Ry.Errors[n]||Ry.Errors.Unexpected)}return Array.from(t)}get warningMessages(){let e=[];return this.env.model.canDispatch(`SPLIT_TEXT_INTO_COLUMNS`,{separator:this.separatorValue,addNewColumns:this.state.addNewColumns,force:!1}).reasons.includes(`SplitWillOverwriteContent`)&&e.push(Ry.Errors.SplitWillOverwriteContent),e}get separatorValue(){return this.state.separatorValue===`custom`?this.state.customSeparator:this.state.separatorValue===`auto`?this.env.model.getters.getAutomaticSeparator():this.state.separatorValue}get separators(){return KM}get isConfirmDisabled(){return!this.separatorValue||this.errorMessages.length>0}},JM=class extends t.Component{static template=`o-spreadsheet-TablePanel`;static components={TableStylePicker:zM,SelectionInput:jT,ValidationMessages:$D,Checkbox:IT,Section:Z,NumberInput:rO};static props={onCloseSidePanel:Function,table:Object};state;setup(){let e=this.env.model.getters.getActiveSheetId();this.state=(0,t.useState)({tableZoneErrors:[],tableXc:this.env.model.getters.getRangeString(this.props.table.range,e),filtersEnabledIfPossible:this.props.table.config.hasFilters})}updateHasFilters(e){this.state.filtersEnabledIfPossible=e,this.updateTableConfig(`hasFilters`,e)}updateTableConfig(e,t){let n=this.env.model.getters.getActiveSheetId();return this.env.model.dispatch(`UPDATE_TABLE`,{sheetId:n,zone:this.props.table.range.zone,config:{[e]:t}})}updateHasHeaders(e){let t=+!!e;this.updateNumberOfHeaders(t)}updateTableIsDynamic(e){let t=e?`dynamic`:`forceStatic`;if(t===this.props.table.type)return;let n=this.env.model.getters.getTable(wM(this.props.table));if(!n)return;let r=this.env.model.getters.getActiveSheetId(),i=this.env.model.dispatch(`UPDATE_TABLE`,{sheetId:r,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeData(n.range),tableType:t}),a=this.env.model.getters.getCoreTable(wM(this.props.table));if(i.isSuccessful&&a){let e=a.range;this.state.tableXc=this.env.model.getters.getRangeString(e,r),this.state.tableZoneErrors=[]}}onChangeNumberOfHeaders(e){let t=parseInt(e);this.updateNumberOfHeaders(t)}updateNumberOfHeaders(e){let t=e>0&&(this.tableConfig.hasFilters||this.state.filtersEnabledIfPossible);return this.env.model.dispatch(`UPDATE_TABLE`,{sheetId:this.env.model.getters.getActiveSheetId(),zone:this.props.table.range.zone,config:{numberOfHeaders:e,hasFilters:t}})}onRangeChanged(e){let t=this.env.model.getters.getActiveSheetId();this.state.tableXc=e[0];let n=this.env.model.getters.getRangeFromSheetXC(t,this.state.tableXc);this.state.tableZoneErrors=this.env.model.canDispatch(`UPDATE_TABLE`,{sheetId:t,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeDataFromXc(t,this.state.tableXc),tableType:this.getNewTableType(n.zone)}).reasons}onRangeConfirmed(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getRangeFromSheetXC(e,this.state.tableXc);if(Xn(t.zone)===1){let n=this.env.model.getters.getContiguousZone(e,t.zone);t=this.env.model.getters.getRangeFromZone(e,n)}let n=t.zone,r=this.props.table.range.zone,i=n.top===r.top&&n.left===r.left?`RESIZE_TABLE`:`UPDATE_TABLE`,a=this.env.model.dispatch(i,{sheetId:e,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeData(t),tableType:this.getNewTableType(t.zone)}),o={sheetId:e,col:t.zone.left,row:t.zone.top},s=this.env.model.getters.getCoreTable(o);if(a.isSuccessful&&s){let t=wM(s);this.env.model.selection.selectZone({zone:D(t),cell:t});let n=s.range;this.state.tableXc=this.env.model.getters.getRangeString(n,e)}}onStylePicked(e){let t=this.env.model.getters.getActiveSheetId();this.env.model.dispatch(`UPDATE_TABLE`,{sheetId:t,zone:this.props.table.range.zone,config:{styleId:e}})}deleteTable(){let e=this.env.model.getters.getActiveSheetId();this.env.model.dispatch(`REMOVE_TABLE`,{sheetId:e,target:[this.props.table.range.zone]})}getNewTableType(e){if(this.props.table.type===`forceStatic`)return`forceStatic`;let t=this.env.model.getters.getActiveSheetId();return this.env.model.getters.canCreateDynamicTableOnZones(t,[e])?`dynamic`:`static`}get tableConfig(){return this.props.table.config}get errorMessages(){return(this.state.tableZoneErrors||[]).map(e=>Vy.Errors[e]||Vy.Errors.Unexpected)}getCheckboxLabel(e){return Vy.Checkboxes[e]}get canHaveFilters(){return this.tableConfig.numberOfHeaders>0}get hasFilterCheckboxTooltip(){return this.canHaveFilters?void 0:Vy.Tooltips.filterWithoutHeader}get canBeDynamic(){let e=this.env.model.getters.getActiveSheetId();return this.props.table.type===`dynamic`||this.env.model.getters.canCreateDynamicTableOnZones(e,[this.props.table.range.zone])}get dynamicTableTooltip(){return Vy.Tooltips.isDynamic}};let YM=`#3C78D8`;var XM=class extends t.Component{static template=`o-spreadsheet-TableStyleEditorPanel`;static components={Section:Z,RoundColorPicker:ST,TableStylePreview:LM};static props={onCloseSidePanel:Function,onStylePicked:{type:Function,optional:!0},styleId:{type:String,optional:!0}};state=(0,t.useState)(this.getInitialState());setup(){(0,t.useExternalListener)(window,`click`,()=>this.state.pickerOpened=!1)}getInitialState(){let e=this.props.styleId?this.env.model.getters.getTableStyle(this.props.styleId):null;return{pickerOpened:!1,primaryColor:e?.primaryColor||YM,selectedTemplateName:e?.templateName||`lightColoredText`,styleName:e?.displayName||this.env.model.getters.getNewCustomTableStyleName()}}togglePicker(){this.state.pickerOpened=!this.state.pickerOpened}onColorPicked(e){this.state.primaryColor=Pr(e)?e:YM,this.state.pickerOpened=!1}onTemplatePicked(e){this.state.selectedTemplateName=e}onConfirm(){let e=this.props.styleId||this.env.model.uuidGenerator.smallUuid();this.env.model.dispatch(`CREATE_TABLE_STYLE`,{tableStyleId:e,tableStyleName:this.state.styleName,templateName:this.state.selectedTemplateName,primaryColor:this.state.primaryColor}),this.props.onStylePicked?.(e),this.props.onCloseSidePanel()}onCancel(){this.props.onCloseSidePanel()}onDelete(){this.props.styleId&&(this.env.model.dispatch(`REMOVE_TABLE_STYLE`,{tableStyleId:this.props.styleId}),this.props.onCloseSidePanel())}get colorPreviewStyle(){return W({background:this.state.primaryColor})}get tableTemplates(){return Object.keys(nC).filter(e=>e!==`none`)}get previewTableConfig(){return{bandedColumns:!1,bandedRows:!0,firstColumn:!1,lastColumn:!1,numberOfHeaders:1,totalRow:!0,hasFilters:!0,styleId:``}}get selectedStyle(){return this.computeTableStyle(this.state.selectedTemplateName)}computeTableStyle(e){return rC(this.state.styleName,e,this.state.primaryColor)}};let ZM=new A;ZM.add(`ConditionalFormatting`,{title:j(`Conditional formatting`),Body:Ek}),ZM.add(`ConditionalFormattingEditor`,{title:j(`Conditional formatting`),Body:wk,computeState:(e,t)=>({isOpen:!0,props:t,key:`ConditionalFormattingEditor_${t.cf.id}`})}),ZM.add(`ChartPanel`,{title:j(`Chart`),Body:sk,computeState:(e,t)=>{let n=e.getSelectedFigureId(),r=n&&e.getFigureSheetId(n),i=r?e.isSheetLocked(r):!1,a=n?e.getChartIdFromFigureId(n):t.chartId;return!a||!e.isChartDefined(a)||i?{isOpen:!1}:{isOpen:!0,props:{chartId:a}}}}),ZM.add(`FindAndReplace`,{title:j(`Find and Replace`),Body:Mk}),ZM.add(`SplitToColumns`,{title:j(`Split text into columns`),Body:qM}),ZM.add(`Settings`,{title:j(`Spreadsheet settings`),Body:UM}),ZM.add(`RemoveDuplicates`,{title:j(`Remove duplicates`),Body:HM}),ZM.add(`DataValidation`,{title:j(`Data validation`),Body:Ok}),ZM.add(`DataValidationEditor`,{title:j(`Data validation`),Body:kk,computeState:(e,t)=>({isOpen:!0,props:t,key:`DataValidationEditor_${t.ruleId}`})}),ZM.add(`MoreFormats`,{title:j(`More formats`),Body:HA}),ZM.add(`ColumnStats`,{title:j(`Column statistics`),Body:gk}),ZM.add(`TableSidePanel`,{title:j(`Edit table`),Body:JM,computeState:e=>{let t=e.getFirstTableInSelection();return!t||t.isPivotTable?{isOpen:!1}:{isOpen:!0,props:{table:e.getCoreTable(wM(t))},key:t.id}}}),ZM.add(`TableStyleEditorPanel`,{title:j(`Create custom table style`),Body:XM,computeState:(e,t)=>({isOpen:!0,props:{...t},key:t.styleId??`new`})}),ZM.add(`PivotSidePanel`,{title:(e,t)=>j(`Pivot #%s`,e.model.getters.getPivotFormulaId(t.pivotId)),Body:VM,computeState:(e,t)=>({isOpen:e.isExistingPivot(t.pivotId),props:t,key:`pivot_key_${t.pivotId}`})}),ZM.add(`PivotMeasureDisplayPanel`,{title:(e,t)=>j(`Measure "%s" options`,e.model.getters.getPivot(t.pivotId).getMeasure(t.measure.id).displayName),Body:YA,computeState:(e,t)=>{try{return e.getPivot(t.pivotId).getMeasure(t.measure.id),{isOpen:!0,props:t,key:`pivot_measure_display_${t.pivotId}_${t.measure.id}`}}catch{return{isOpen:!1}}}}),ZM.add(`CarouselPanel`,{title:j(`Carousel`),Body:qD,computeState:(e,t)=>{let n=t.figureId||e.getSelectedFigureId(),r=n&&e.getFigureSheetId(n),i=r?e.isSheetLocked(r):!1;return!n||!e.doesCarouselExist(n)||i?{isOpen:!1}:{isOpen:!0,props:{figureId:n}}}}),ZM.add(`NamedRangesPanel`,{title:j(`Named Ranges`),Body:qA});var QM=class{mutators=[`setSmallThreshhold`];_isSmallCallback=()=>!1;get isSmall(){return this._isSmallCallback()}setSmallThreshhold(e){this._isSmallCallback=e}},$M=class extends wr{mutators=[`open`,`replace`,`toggle`,`close`,`changePanelSize`,`resetPanelSize`,`togglePinPanel`,`closeMainPanel`,`changeSpreadsheetWidth`,`toggleCollapsePanel`];mainPanel=void 0;secondaryPanel;availableWidth=0;screenWidthStore=this.get(QM);get isMainPanelOpen(){return this.mainPanel&&this.mainPanel.componentTag?this.computeState(this.mainPanel).isOpen:!1}get isSecondaryPanelOpen(){return this.secondaryPanel&&this.secondaryPanel.componentTag?this.computeState(this.secondaryPanel).isOpen:!1}get mainPanelProps(){return this.mainPanel?this.getPanelProps(this.mainPanel):void 0}get mainPanelKey(){return this.mainPanel?this.getPanelKey(this.mainPanel):void 0}get secondaryPanelProps(){return this.secondaryPanel?this.getPanelProps(this.secondaryPanel):void 0}get secondaryPanelKey(){return this.secondaryPanel?this.getPanelKey(this.secondaryPanel):void 0}get totalPanelSize(){return(this.mainPanel?.size||0)+(this.secondaryPanel?.size??0)}getPanelProps(e){let t=this.computeState(e);return t.isOpen?(e.currentPanelProps=t.props??e.currentPanelProps,t.props??{}):{}}getPanelKey(e){let t=this.computeState(e);if(t.isOpen)return t.key}open(e,t={}){if(this.screenWidthStore.isSmall)return;let n={currentPanelProps:t,componentTag:e,size:350},r=this.computeState(n);if(!r.isOpen)return;if(!this.mainPanel||!this.mainPanel.isPinned||this.mainPanelKey===r.key){this._openPanel(`mainPanel`,n,r);return}let i=this.mainPanel.isCollapsed?350:this.mainPanel.size;if(!this.secondaryPanel&&i+350>this.availableWidth){this.get(lT).notifyUser({sticky:!1,type:`warning`,text:j(`The window is too small to display multiple side panels.`)});return}this._openPanel(`secondaryPanel`,n,r)}replace(e,t,n={}){let r={currentPanelProps:n,componentTag:e,size:350},i=this.computeState(r);if(!i.isOpen)return;let a=()=>{this.mainPanel?.isCollapsed&&this.toggleCollapsePanel(`mainPanel`)},o=this.mainPanelKey===i.key,s=this.secondaryPanelKey===i.key;if(o&&this.secondaryPanel){this.close(),a();return}if(s){this.closeMainPanel(),this.togglePinPanel(),a();return}let c=this.mainPanelKey===t?`mainPanel`:`secondaryPanel`;this._openPanel(c,r,i)}_openPanel(e,t,n){let r=this[e];r&&t.componentTag!==r.componentTag&&r.currentPanelProps?.onCloseSidePanel?.(),this[e]={currentPanelProps:n.props??{},componentTag:t.componentTag,size:r?.size||350,isCollapsed:r?.isCollapsed||!1,isPinned:r&&`isPinned`in r?r.isPinned:!1},this[e].isCollapsed&&this.toggleCollapsePanel(e)}toggle(e,t){let n=this.mainPanel?.isPinned?this.secondaryPanel:this.mainPanel;n&&e===n.componentTag?this.close():this.open(e,t)}close(){if(this.mainPanel?.isPinned){this.secondaryPanel&&=(this.secondaryPanel.currentPanelProps.onCloseSidePanel?.(),void 0);return}this.mainPanel?.currentPanelProps.onCloseSidePanel?.(),this.mainPanel=void 0}closeMainPanel(){this.mainPanel?.currentPanelProps.onCloseSidePanel?.(),this.mainPanel=this.secondaryPanel||void 0,this.secondaryPanel=void 0}changePanelSize(e,t){let n=this[e];if(!n||`isCollapsed`in n&&n.isCollapsed)return;t=Math.max(t,350);let r=e===`mainPanel`?this.secondaryPanel?.size||0:this.mainPanel?.size||0;t>this.availableWidth-r&&(e===`mainPanel`&&this.secondaryPanel&&(this.secondaryPanel.size=Math.max(this.availableWidth-t,350),r=this.secondaryPanel.size),t=Math.max(this.availableWidth-r,350)),n.size=t}resetPanelSize(e){this[e]&&(this[e].size=350)}togglePinPanel(){this.mainPanel&&(this.mainPanel.isPinned=!this.mainPanel.isPinned,!this.mainPanel.isPinned&&this.secondaryPanel&&(this.secondaryPanel?.currentPanelProps.onCloseSidePanel?.(),this.mainPanel=this.secondaryPanel,this.secondaryPanel=void 0))}toggleCollapsePanel(e){let t=this[e];t&&(t.isCollapsed?(t.isCollapsed=!1,this.changePanelSize(e,350)):(t.isCollapsed=!0,t.size=45))}computeState({componentTag:e,currentPanelProps:t}){let n=ZM.get(e).computeState,r=n?n(this.getters,t):{isOpen:!0,props:t};return r.isOpen?{...r,key:r.key||e}:r}changeSpreadsheetWidth(e){this.availableWidth=e-150,this.secondaryPanel&&e-this.totalPanelSize<150&&(this.secondaryPanel?.currentPanelProps.onCloseSidePanel?.(),this.secondaryPanel=void 0),this.mainPanel&&e-this.totalPanelSize<150&&(this.mainPanel.size=Math.max(e-150,350))}};function eN(e,t,n){let r=e.model.getters.getActiveSheetId(),i=t===`COL`?`FREEZE_COLUMNS`:`FREEZE_ROWS`;e.model.dispatch(i,{sheetId:r,quantity:n}).isCancelledBecause(`MergeOverlap`)&&e.raiseError(Iy)}var tN=class{map={};constructor(e=[]){for(let[t,n]of e)this.set(t,n)}set({sheetId:e,col:t,row:n},r){let i=this.map;i[e]||(i[e]={}),i[e][t]||(i[e][t]={}),i[e][t][n]=r}setMany(e){for(let[t,n]of e)this.set(t,n)}get({sheetId:e,col:t,row:n}){return this.map[e]?.[t]?.[n]}getSheet(e){return this.map[e]}clearSheet(e){delete this.map[e]}has({sheetId:e,col:t,row:n}){return this.map[e]?.[t]?.[n]!==void 0}delete({sheetId:e,col:t,row:n}){delete this.map[e]?.[t]?.[n]}keys(){let e=this.map,t=[];for(let n in e)for(let r in e[n])for(let i in e[n][r])t.push({sheetId:n,col:parseInt(r),row:parseInt(i)});return t}keysForSheet(e){let t=this.map[e];if(!t)return[];let n=[];for(let r in t)for(let i in t[r])n.push({sheetId:e,col:parseInt(r),row:parseInt(i)});return n}*entries(){let e=this.map;for(let t of this.keys()){let{sheetId:n,col:r,row:i}=t;yield[t,e[n][r][i]]}}},nN=class extends wr{mutators=[`enable`,`disable`];isInvalidated=!1;fingerprintColors={[iN]:`#D9D9D9`};isEnabled=!1;colors=new tN;handle(e){switch(wu(e)&&this.isEnabled&&(this.isInvalidated=!0),e.type){case`UNDO`:case`REDO`:case`ACTIVATE_SHEET`:this.isEnabled&&(this.isInvalidated=!0);break}}finalize(){this.isInvalidated&&(this.isInvalidated=!1,this.computeFingerprints())}enable(){this.isEnabled=!0,this.computeFingerprints()}disable(){this.isEnabled=!1,this.colors=new tN}computeFingerprints(){this.colors=new tN;let e=new tN,t=new Set,n=this.getters.getActiveSheetId(),r=this.getters.getCells(n);for(let n in r){let i=r[n],a=this.computeFingerprint(i);if(!a)continue;t.add(a);let o=this.getters.getCellPosition(i.id);e.set(o,a)}this.assignColors(t);for(let[t,n]of e.entries()){let e=this.fingerprintColors[n];this.colors.set(t,e),this.colorSpreadZone(t,e)}}colorSpreadZone(e,t){let n=this.getters.getSpreadZone(e);if(!n)return;let r=e.sheetId;for(let e=n.top;e<=n.bottom;e++)for(let i=n.left;i<=n.right;i++){let n={sheetId:r,col:i,row:e};this.colors.set(n,t)}}assignColors(e){let t=new di(e.size);Object.keys(this.fingerprintColors).forEach(()=>t.next());for(let n of e)this.fingerprintColors[n]||(this.fingerprintColors[n]=Yr(t.next(),.8))}computeFingerprint(e){let t=this.getters.getCellPosition(e.id);return e.isFormula?this.computeFormulaFingerprint(t,e):this.getLiteralFingerprint(t)}computeFormulaFingerprint(e,t){let n=t.compiledFormula.rangeDependencies,r=e.col,i=e.row,a=this.getters.getSheetIds().indexOf(e.sheetId),o={dx:0,dy:0,dSheet:0};for(let e of n){let t=e.zone,[n,s]=e.parts;o.dSheet=this.getters.getSheetIds().indexOf(e.sheetId)-a;let c=$s(e)&&!e.unboundedZone.hasHeader,l=Qs(e)&&!e.unboundedZone.hasHeader,u=c||n?.colFixed?0:r,d=l||n?.rowFixed?0:i,f=!s&&n?.colFixed||s?.colFixed,p=!s&&n?.rowFixed||s?.rowFixed,m=e.unboundedZone.right===void 0,h=e.unboundedZone.bottom===void 0,g=m||f?0:r,_=h||p?0:i,v=Hn({top:t.top-d,left:t.left-u,right:t.right-g,bottom:t.bottom-_});for(let e=v.top;e<=v.bottom;e++)for(let t=v.left;t<=v.right;t++)o.dx+=t,o.dy+=e}let s=t.compiledFormula.normalizedFormula;return rN(o)+s}getLiteralFingerprint(e){switch(this.getters.getEvaluatedCell(e).type){case`number`:case`boolean`:return iN;case`text`:case`empty`:case`error`:return}}};function rN(e){return Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>t).join(`,`)}let iN=`DATA_FINGERPRINT`,aN={name:PE,execute:e=>{let t=e.model.getters.getElementsFromSelection(`COL`);e.model.dispatch(`HIDE_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),dimension:`COL`,elements:t})},isVisible:kE,icon:`o-spreadsheet-Icon.HIDE_COL`},oN={name:j(`Unhide columns`),execute:e=>{let t=e.model.getters.getElementsFromSelection(`COL`);e.model.dispatch(`UNHIDE_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),dimension:`COL`,elements:t})},isVisible:e=>{let t=e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection(`COL`).some(e=>t.includes(e))},icon:`o-spreadsheet-Icon.UNHIDE_COL`},sN={name:j(`Unhide all columns`),execute:e=>{let t=e.model.getters.getActiveSheetId();e.model.dispatch(`UNHIDE_COLUMNS_ROWS`,{sheetId:t,dimension:`COL`,elements:Array.from(Array(e.model.getters.getNumberCols(t)).keys())})},isVisible:e=>e.model.getters.getHiddenColsGroups(e.model.getters.getActiveSheetId()).length>0,icon:`o-spreadsheet-Icon.UNHIDE_COL`},cN={name:FE,execute:e=>{let t=e.model.getters.getElementsFromSelection(`ROW`);e.model.dispatch(`HIDE_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),dimension:`ROW`,elements:t})},isVisible:DE,icon:`o-spreadsheet-Icon.HIDE_ROW`},lN={name:j(`Unhide rows`),execute:e=>{let t=e.model.getters.getElementsFromSelection(`ROW`);e.model.dispatch(`UNHIDE_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId(),dimension:`ROW`,elements:t})},isVisible:e=>{let t=e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).flat();return e.model.getters.getElementsFromSelection(`ROW`).some(e=>t.includes(e))},icon:`o-spreadsheet-Icon.UNHIDE_ROW`},uN={name:j(`Unhide all rows`),execute:e=>{let t=e.model.getters.getActiveSheetId();e.model.dispatch(`UNHIDE_COLUMNS_ROWS`,{sheetId:t,dimension:`ROW`,elements:Array.from(Array(e.model.getters.getNumberRows(t)).keys())})},isVisible:e=>e.model.getters.getHiddenRowsGroups(e.model.getters.getActiveSheetId()).length>0,icon:`o-spreadsheet-Icon.UNHIDE_ROW`},dN={name:j(`Unfreeze`),isVisible:e=>{let{xSplit:t,ySplit:n}=e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId());return t+n>0},execute:e=>e.model.dispatch(`UNFREEZE_COLUMNS_ROWS`,{sheetId:e.model.getters.getActiveSheetId()}),icon:`o-spreadsheet-Icon.UNFREEZE`},fN={name:j(`Freeze`),icon:`o-spreadsheet-Icon.FREEZE`},pN={name:j(`No rows`),execute:e=>e.model.dispatch(`UNFREEZE_ROWS`,{sheetId:e.model.getters.getActiveSheetId()}),isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).ySplit},mN={name:j(`1 row`),execute:e=>eN(e,`ROW`,1)},hN={name:j(`2 rows`),execute:e=>eN(e,`ROW`,2)},gN={name:j(`Up to current row`),execute:e=>{let{bottom:t}=e.model.getters.getSelectedZone();eN(e,`ROW`,t+1)}},_N={name:j(`No columns`),execute:e=>e.model.dispatch(`UNFREEZE_COLUMNS`,{sheetId:e.model.getters.getActiveSheetId()}),isVisible:e=>!!e.model.getters.getPaneDivisions(e.model.getters.getActiveSheetId()).xSplit},vN={name:j(`1 column`),execute:e=>eN(e,`COL`,1)},yN={name:j(`2 columns`),execute:e=>eN(e,`COL`,2)},bN={name:j(`Up to current column`),execute:e=>{let{right:t}=e.model.getters.getSelectedZone();eN(e,`COL`,t+1)}},xN={name:j(`Gridlines`),execute:e=>{let t=e.model.getters.getActiveSheetId();e.model.dispatch(`SET_GRID_LINES_VISIBILITY`,{sheetId:t,areGridLinesVisible:!e.model.getters.getGridLinesVisibility(t)})},isActive:e=>{let t=e.model.getters.getActiveSheetId();return e.model.getters.getGridLinesVisibility(t)}},SN={name:j(`Irregularity map`),execute:e=>{let t=e.getStore(nN);t.isEnabled?t.disable():t.enable()},isReadonlyAllowed:!0,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.IRREGULARITY_MAP`};function CN(e){return{name:j(`%(zoom_percentage)s%`,{zoom_percentage:e}),execute:t=>{t.model.dispatch(`SET_ZOOM`,{zoom:e/100})},isActive:t=>t.model.getters.getViewportZoomLevel()===e/100,isReadonlyAllowed:!0,isEnabledOnLockedSheet:!0,sequence:e}}let wN={name:j(`Formulas`),isActive:e=>e.model.getters.shouldShowFormulas(),execute:e=>e.model.dispatch(`SET_FORMULA_VISIBILITY`,{show:!e.model.getters.shouldShowFormulas()}),isReadonlyAllowed:!0,isEnabledOnLockedSheet:!0},TN={name:e=>{let t=e.model.getters.getSelectedZone();return t.left===t.right?j(`Group column %s`,Zt(t.left)):j(`Group columns %s - %s`,Zt(t.left),Zt(t.right))},execute:e=>kN(e,`COL`),isVisible:e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getSelectedZone(),r=e.model.getters.getHeaderGroupsInZone(t,`COL`,n);return $E(e)&&!r.some(e=>e.start===n.left&&e.end===n.right)},icon:`o-spreadsheet-Icon.GROUP_COLUMNS`},EN={name:e=>{let t=e.model.getters.getSelectedZone();return t.top===t.bottom?j(`Group row %s`,String(t.top+1)):j(`Group rows %s - %s`,String(t.top+1),String(t.bottom+1))},execute:e=>kN(e,`ROW`),isVisible:e=>{let t=e.model.getters.getActiveSheetId(),n=e.model.getters.getSelectedZone(),r=e.model.getters.getHeaderGroupsInZone(t,`ROW`,n);return $E(e)&&!r.some(e=>e.start===n.top&&e.end===n.bottom)},icon:`o-spreadsheet-Icon.GROUP_ROWS`},DN={name:e=>{let t=e.model.getters.getSelectedZone();return t.left===t.right?j(`Ungroup column %s`,Zt(t.left)):j(`Ungroup columns %s - %s`,Zt(t.left),Zt(t.right))},execute:e=>AN(e,`COL`),icon:`o-spreadsheet-Icon.UNGROUP_COLUMNS`},ON={name:e=>{let t=e.model.getters.getSelectedZone();return t.top===t.bottom?j(`Ungroup row %s`,String(t.top+1)):j(`Ungroup rows %s - %s`,String(t.top+1),String(t.bottom+1))},execute:e=>AN(e,`ROW`),icon:`o-spreadsheet-Icon.UNGROUP_ROWS`};function kN(e,t){let n=e.model.getters.getSelectedZone(),r=e.model.getters.getActiveSheetId();e.model.dispatch(`GROUP_HEADERS`,{sheetId:r,dimension:t,start:t===`COL`?n.left:n.top,end:t===`COL`?n.right:n.bottom})}function AN(e,t){let n=e.model.getters.getSelectedZone(),r=e.model.getters.getActiveSheetId();e.model.dispatch(`UNGROUP_HEADERS`,{sheetId:r,dimension:t,start:t===`COL`?n.left:n.top,end:t===`COL`?n.right:n.bottom})}function jN(e,t){let n=e.model.getters.getActiveSheetId(),r=e.model.getters.getSelectedZones();return r.length===1&&e.model.getters.getHeaderGroupsInZone(n,t,r[0]).length>0}let MN={name:e=>{let t=e.getStore($M);return t.mainPanel&&t.mainPanel.isPinned?j(`Unpin the side panel`):j(`Pin the side panel`)},isVisible:e=>e.getStore($M).isMainPanelOpen,execute:e=>{e.getStore($M).togglePinPanel()},icon:`o-spreadsheet-Icon.THUMB_TACK`};function NN(e){let t=e.model.dispatch(`CUT`);t.isSuccessful||t.isCancelledBecause(`WrongCutSelection`)&&e.raiseError(j(`This operation is not allowed with multiple selections.`))}var PN=class extends A{replace(e,t){return t.id===void 0&&(t.id=e),this.content[e]=t,this}addChild(e,t,n){return this._replaceChild(e,t,n,{force:!1})}replaceChild(e,t,n){return this._replaceChild(e,t,n,{force:!0})}_replaceChild(e,t,n,r={force:!0}){typeof n!=`function`&&n.id===void 0&&(n.id=e);let i=t.splice(0,1)[0],a=this.content[i];if(!a)throw Error(`Path ${i+`:`+t.join(`:`)} not found`);for(let e of t){let n=a.children;if(!n||typeof n==`function`)throw Error(`${e} is either not a node or it's dynamically computed`);if(a=n.find(t=>t.id===e),!a)throw Error(`Path ${i+`:`+t.join(`:`)} not found`)}a.children||=[];let o=a.children;if(!o||typeof o==`function`)throw Error(`${t} is either not a node or it's dynamically computed`);if(`id`in n){let e=o.findIndex(e=>`id`in e&&e.id===n.id);if(e>-1){if(!r.force)throw Error(`A child with the id "${n.id}" already exists.`);return a.children.splice(e,1,n),this}}return a.children.push(n),this}getMenuItems(){return p(this.getAll())}};let FN={MergeIsDestructive:j(`Merging these cells will only preserve the top-leftmost value. Merge anyway?`),MergeInFilter:j(`You can't merge cells inside of an existing filter.`)};function IN(e,t,n){let r=e.model.dispatch(`ADD_MERGE`,{sheetId:t,target:n});r.isCancelledBecause(`MergeInTable`)?e.raiseError(FN.MergeInFilter):r.isCancelledBecause(`MergeIsDestructive`)&&e.askConfirmation(FN.MergeIsDestructive,()=>{e.model.dispatch(`ADD_MERGE`,{sheetId:t,target:n,force:!0})})}let LN={name:j(`Undo`),shortcut:`Ctrl+Z`,execute:e=>e.model.dispatch(`REQUEST_UNDO`),isEnabled:e=>e.model.getters.canUndo(),isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.UNDO`},RN={name:j(`Redo`),shortcut:`Ctrl+Y`,execute:e=>e.model.dispatch(`REQUEST_REDO`),isEnabled:e=>e.model.getters.canRedo(),isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.REDO`},zN={name:j(`Copy`),shortcut:`Ctrl+C`,isReadonlyAllowed:!0,execute:async e=>{e.model.dispatch(`COPY`),await e.clipboard.write(await e.model.getters.getClipboardTextAndImageContent())},isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.CLIPBOARD`},BN={name:j(`Cut`),shortcut:`Ctrl+X`,execute:async e=>{NN(e),await e.clipboard.write(await e.model.getters.getClipboardTextAndImageContent())},icon:`o-spreadsheet-Icon.CUT`},VN={name:j(`Paste`),shortcut:`Ctrl+V`,execute:hE,icon:`o-spreadsheet-Icon.PASTE`},HN={name:j(`Paste special`),isVisible:e=>!e.model.getters.isCutOperation(),icon:`o-spreadsheet-Icon.PASTE`},UN={name:j(`Paste as value`),shortcut:`Ctrl+Shift+V`,execute:gE},WN={name:j(`Paste format only`),execute:vE},GN={name:j(`Find and replace`),shortcut:`Ctrl+H`,isReadonlyAllowed:!0,isEnabledOnLockedSheet:!0,execute:e=>{e.openSidePanel(`FindAndReplace`,{})},isEnabled:e=>!e.isSmall,icon:`o-spreadsheet-Icon.SEARCH`},KN={name:j(`Delete values`),execute:e=>e.model.dispatch(`DELETE_UNFILTERED_CONTENT`,{sheetId:e.model.getters.getActiveSheetId(),target:e.model.getters.getSelectedZones()})},qN={name:CE,execute:wE,isVisible:e=>TE(`ROW`,e)},JN={...qN,isVisible:$E},YN={name:yE,execute:bE},XN={name:EE,execute:OE,isVisible:e=>TE(`COL`,e)},ZN={...XN,isVisible:$E},QN={name:xE,execute:SE},$N={name:j(`Delete cells`),isVisible:$E},eP={name:j(`Delete cell and shift up`),execute:e=>{let t=e.model.getters.getSelectedZone();mw(e,e.model.dispatch(`DELETE_CELL`,{zone:t,shiftDimension:`ROW`}))}},tP={name:j(`Delete cell and shift left`),execute:e=>{let t=e.model.getters.getSelectedZone();mw(e,e.model.dispatch(`DELETE_CELL`,{zone:t,shiftDimension:`COL`}))}},nP={name:j(`Merge cells`),isEnabled:e=>!aP(e),isActive:e=>oP(e),execute:e=>sP(e),icon:`o-spreadsheet-Icon.MERGE_CELL`},rP={name:()=>j(`Edit table`),execute:e=>e.openSidePanel(`TableSidePanel`,{}),icon:`o-spreadsheet-Icon.EDIT_TABLE`},iP={name:()=>j(`Delete table`),execute:QE,icon:`o-spreadsheet-Icon.DELETE_TABLE`};function aP(e){let t=e.model.getters.getSelectedZones(),{sheetId:n}=e.model.getters.getActivePosition(),{xSplit:r,ySplit:i}=e.model.getters.getPaneDivisions(n);return t.every(e=>Xn(e)===1)||Qn(t,r,i)||Pn(t)}function oP(e){if(aP(e))return!1;let t=e.model.getters.getActiveSheetId();return e.model.getters.getSelectedZones().some(n=>e.model.getters.getMergesInZone(t,n).length>0)}function sP(e){if(aP(e))return;let t=e.model.getters.getSelectedZones(),n=e.model.getters.getActiveSheetId();if(oP(e)){let r=t.flatMap(t=>e.model.getters.getMergesInZone(n,t));e.model.dispatch(`REMOVE_MERGE`,{sheetId:n,target:r})}else IN(e,n,t)}let cP={name:j(`See pivot properties`),execute(e){let t=e.model.getters.getActivePosition(),n=e.model.getters.getPivotIdFromPosition(t);e.openSidePanel(`PivotSidePanel`,{pivotId:n})},isVisible:e=>{let t=e.model.getters.getActivePosition(),n=e.model.getters.getPivotIdFromPosition(t);return!e.isSmall&&n&&e.model.getters.isExistingPivot(n)||!1},isReadonlyAllowed:!0,isEnabledOnLockedSheet:!0,icon:`o-spreadsheet-Icon.PIVOT`},lP={name:j(`Ascending`),execute:e=>xP(e,e.model.getters.getActivePosition(),`asc`),isActive:e=>e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())===`asc`},uP={name:j(`Descending`),execute:e=>xP(e,e.model.getters.getActivePosition(),`desc`),isActive:e=>e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())===`desc`},dP={name:j(`No sorting`),execute:e=>xP(e,e.model.getters.getActivePosition(),`none`),isActive:e=>e.model.getters.getPivotCellSortDirection(e.model.getters.getActivePosition())===`none`},fP={name:j(`Convert to individual formulas`),execute(e){let t=e.model.getters.getActivePosition(),n=e.model.getters.getCorrespondingFormulaCell(t),r=e.model.getters.getPivotIdFromPosition(t);if(!n||!r)return;let{sheetId:i,col:a,row:o}=e.model.getters.getCellPosition(n.id),s=e.model.getters.getPivot(r);s.init(),s.isValid()&&e.model.dispatch(`SPLIT_PIVOT_FORMULA`,{sheetId:i,col:a,row:o,pivotId:r})},isVisible:e=>{let t=e.model.getters.getActivePosition(),n=e.model.getters.getPivotIdFromPosition(t);if(!n)return!1;let r=e.model.getters.getPivot(n),i=e.model.getters.getEvaluatedCell(t);return r.isValid()&&e.model.getters.isSpillPivotFormula(t)&&i.type!==`error`},icon:`o-spreadsheet-Icon.PIVOT`},pP={name:j(`Group pivot dimensions`),execute:e=>{let t=SP(e);if(!t)return;let{pivotId:n,values:r,field:i}=t,a=e.model.getters.getPivot(n),o=x(e.model.getters.getPivotCoreDefinition(n));if(!i.isCustomField)CP(o,r,i,a.getFields());else{let e=(o.customFields||{})[i.name];if(!e)return;wP(e,r)}e.model.dispatch(`UPDATE_PIVOT`,{pivotId:n,pivot:o})},isVisible:e=>{let t=SP(e);if(!t)return!1;let{pivotId:n,values:r,field:i}=t,a=e.model.getters.getPivot(n);return r.length>1&&(i.isCustomField||Uj.get(a.type).canHaveCustomGroup(i))}},mP={name:j(`Group all remaining dimensions`),execute:e=>{let t=SP(e);if(!t)return;let{pivotId:n,field:r}=t,i=e.model.getters.getPivot(n),a=x(e.model.getters.getPivotCoreDefinition(n)),o=r.isCustomField?(a.customFields||{})[r.name]:Vg(a,r,i.getFields());o&&(o.groups.push({name:Ig(j(`Others`),o),values:[],isOtherGroup:!0}),Bg(a,r.name,o.name),e.model.dispatch(`UPDATE_PIVOT`,{pivotId:n,pivot:a}))},isVisible:e=>{let t=SP(e);if(!t)return!1;let{pivotId:n,field:r,values:i}=t;return DP(e,n,i,r)}},hP={name:j(`Ungroup pivot dimensions`),execute:e=>{let t=SP(e);if(!t)return;let{pivotId:n,values:r,field:i}=t,a=e.model.getters.getPivot(n),o=x(e.model.getters.getPivotCoreDefinition(n));TP(o,r,i,a.getFields()),e.model.dispatch(`UPDATE_PIVOT`,{pivotId:n,pivot:o})},isVisible:e=>{let t=SP(e);if(!t)return!1;let{pivotId:n,values:r,field:i}=t,a=e.model.getters.getPivot(n),o=e.model.getters.getPivotCoreDefinition(n);if(!i.isCustomField){let e=Vg(o,i,a.getFields());if(![...o.rows,...o.columns].some(t=>t.fieldName===e.name))return!1}return EP(o,r,i,a.getFields())}},gP={name:e=>{let t=e.model.getters.getActivePosition(),n=yP(e.model.getters,t);return n.isPivotGroup?n.isCollapsed?j(`Expand`):j(`Collapse`):``},execute(e){Hg(e.model.getters.getActivePosition(),e)},isVisible:e=>{let t=e.model.getters.getActivePosition(),n=yP(e.model.getters,t),r=e.model.getters.getPivotStyleAtPosition(t);return n.isPivotGroup&&!r?.pivotStyle.tabularForm}},_P={name:j(`Collapse all`),execute(e){let t=e.model.getters.getActivePosition(),n=yP(e.model.getters,t);if(!n.isPivotGroup)return;let{pivotCell:r,pivotId:i,siblingDomains:a}=n,o=x(e.model.getters.getPivotCoreDefinition(i));o.collapsedDomains=o.collapsedDomains||{COL:[],ROW:[]};let s=[...o.collapsedDomains[r.dimension]||[],...a],c=s.filter((e,t)=>t===s.findIndex(t=>T(t,e)));o.collapsedDomains[r.dimension]=c,e.model.dispatch(`UPDATE_PIVOT`,{pivotId:i,pivot:o})},isVisible:e=>{let t=e.model.getters.getActivePosition(),n=yP(e.model.getters,t),r=e.model.getters.getPivotStyleAtPosition(t);if(!n.isPivotGroup||r?.pivotStyle.tabularForm)return!1;let{pivotCell:i,pivotId:a,siblingDomains:o}=n,s=e.model.getters.getPivotCoreDefinition(a);return!o.every(e=>(s.collapsedDomains?.[i.dimension]||[]).some(t=>T(t,e)))}},vP={name:j(`Expand all`),execute(e){let t=e.model.getters.getActivePosition(),n=yP(e.model.getters,t);if(!n.isPivotGroup)return;let{pivotCell:r,pivotId:i,siblingDomains:a}=n,o=x(e.model.getters.getPivotCoreDefinition(i));o.collapsedDomains=o.collapsedDomains||{COL:[],ROW:[]};let s=(o.collapsedDomains[r.dimension]||[]).filter(e=>!a.find(t=>T(t,e)));o.collapsedDomains[r.dimension]=s,e.model.dispatch(`UPDATE_PIVOT`,{pivotId:i,pivot:o})},isVisible:e=>{let t=e.model.getters.getActivePosition(),n=yP(e.model.getters,t),r=e.model.getters.getPivotStyleAtPosition(t);if(!n.isPivotGroup||r?.pivotStyle.tabularForm)return!1;let{pivotCell:i,pivotId:a,siblingDomains:o}=n;return(e.model.getters.getPivotCoreDefinition(a).collapsedDomains?.[i.dimension]||[]).some(e=>o.some(t=>T(t,e)))}};function yP(e,t){if(!e.isSpillPivotFormula(t))return{isPivotGroup:!1};let n=e.getPivotCellFromPosition(t),r=e.getPivotIdFromPosition(t);if(n.type!==`HEADER`||!r||!n.domain.length)return{isPivotGroup:!1};let i=e.getPivotCoreDefinition(r),a=e.isDashboard(),o=n.dimension===`COL`?i.columns:i.rows;if(!(!a&&n.domain.length!==o.length))return{isPivotGroup:!1};let s=(i.collapsedDomains?.[n.dimension]??[]).some(e=>T(e,n.domain)),c=e.getPivot(r).getExpandedTableStructure(),l=n.domain.length-1;return{isPivotGroup:!0,isCollapsed:s,pivotCell:n,pivotId:r,siblingDomains:n.dimension===`ROW`?c.getRowDomainsAtDepth(l):c.getColumnDomainsAtDepth(l)}}function bP(e,t){let n=e.getPivotIdFromPosition(t);if(!n||!e.isExistingPivot(n)||!e.isSpillPivotFormula(t)||!e.getPivot(n).isValid())return!1;let r=e.getPivotCellFromPosition(t);return r.type===`VALUE`||r.type===`MEASURE_HEADER`}function xP(e,t,n){let r=e.model.getters.getPivotIdFromPosition(t),i=e.model.getters.getPivotCellFromPosition(t);if(i.type===`EMPTY`||i.type===`HEADER`||i.type===`ROW_GROUP_NAME`||!r)return;if(n===`none`){e.model.dispatch(`UPDATE_PIVOT`,{pivotId:r,pivot:{...e.model.getters.getPivotCoreDefinition(r),sortedColumn:void 0}});return}let a=mj(e.model.getters.getPivot(r),i.domain).colDomain;e.model.dispatch(`UPDATE_PIVOT`,{pivotId:r,pivot:{...e.model.getters.getPivotCoreDefinition(r),sortedColumn:{domain:a,order:n,measure:i.measure}}})}function SP(e){let t,n,r=[];for(let i of e.model.getters.getSelectedZones()){let a=e.model.getters.getActiveSheetId();for(let o of Vn(a,i)){let i=e.model.getters.getPivotIdFromPosition(o);if(!t)t=i;else if(i&&t!==i)return;if(!t)continue;let a=e.model.getters.getPivotCellFromPosition(o);if(a.type!==`HEADER`||!e.model.getters.isSpillPivotFormula(o))continue;let s=a.domain.at(-1)?.field;if(!n&&s)n=s;else if(n&&s&&n!==s)return;r.push(a)}}if(!t||!n||r.length===0)return;let i=e.model.getters.getPivot(t).getFields()[n];if(!i)return;let a=r.map(e=>e.domain.at(-1)?.value).filter(e=>e!==void 0);return{pivotId:t,values:a,field:i}}function CP(e,t,n,r){let i=Vg(e,n,r);zg(t,i);let a={name:Ig(j(`Group`),i),values:t};i.groups.push(a),e.customFields||={},e.customFields[i.name]=i,Bg(e,n.name,i.name)}function wP(e,t){let n=new Set,r=[];for(let i of t){let t=e.groups.find(e=>e.name===i);t?(r.push(t),t.values.forEach(e=>n.add(e))):n.add(i)}if(r.some(e=>e.isOtherGroup))e.groups=e.groups.filter(e=>e.isOtherGroup||!r.includes(e));else if(r.length===0){let n={name:Ig(j(`Group`),e),values:t};e.groups.push(n)}else{let t=r.slice(1);e.groups=e.groups.filter(e=>!t.includes(e)),r[0].values=Array.from(n)}}function TP(e,t,n,r){let i;if(!n.isCustomField)i=Vg(e,n,r),i.groups.some(e=>e.isOtherGroup)&&t.some(e=>!i?.groups.some(t=>t.values.includes(e)))&&(i.groups=i.groups.filter(e=>!e.isOtherGroup)),zg(t,i);else{if(i=(e.customFields||{})[n.name],!i)return;i.groups=i.groups.filter(e=>!t.includes(e.name))}i.groups.every(e=>e.values.length===0&&!e.isOtherGroup)&&(OP(e,i.name),delete e.customFields?.[i.name])}function EP(e,t,n,r){if(n.isCustomField){let r=(e.customFields||{})[n.name];return r?r.groups.some(e=>t.includes(e.name)):!1}else return Vg(e,n,r).groups.some(e=>e.isOtherGroup||t.some(t=>e.values.includes(t)))}function DP(e,t,n,r){let i=e.model.getters.getPivot(t),a=e.model.getters.getPivotCoreDefinition(t),o=r.isCustomField?(a.customFields||{})[r.name]:Object.values(a.customFields||{}).find(e=>e.parentField===r.name),s=i.definition.getDimension(r.name);if(!s||!o||EP(a,n,r,i.getFields()))return!1;let c=new Set(i.getPossibleFieldValues(s).map(e=>e.value)),l=r.isCustomField?o.groups.map(e=>e.name):o.groups.flatMap(e=>e.values);for(let e of[...n,...l])c.delete(e);return c.size===0}function OP(e,t){let n=e.customFields?.[t];if(!n)return;let r=[...e.rows,...e.columns].some(e=>e.fieldName===n.parentField);for(let i of[e.rows,e.columns]){let e=i.findIndex(e=>e.fieldName===t);e!==-1&&(r?i.splice(e,1):i.splice(e,1,{fieldName:n.parentField}))}}let kP=new PN;kP.add(`cut`,{...BN,sequence:10}).add(`copy`,{...zN,sequence:20}).add(`paste`,{...VN,sequence:30}).add(`paste_special`,{...HN,sequence:40,separator:!0}).addChild(`paste_value_only`,[`paste_special`],{...UN,sequence:10}).addChild(`paste_format_only`,[`paste_special`],{...WN,sequence:20}).add(`add_row_before`,{...aD,sequence:70}).add(`add_column_before`,{...dD,sequence:90}).add(`insert_cell`,{...mD,sequence:100,separator:!0}).addChild(`insert_cell_down`,[`insert_cell`],{...hD,name:j(`Shift down`),sequence:10}).addChild(`insert_cell_right`,[`insert_cell`],{...gD,name:j(`Shift right`),sequence:20}).add(`delete_row`,{...JN,sequence:110,icon:`o-spreadsheet-Icon.TRASH`}).add(`delete_column`,{...ZN,sequence:120,icon:`o-spreadsheet-Icon.TRASH`}).add(`delete_cell`,{...$N,sequence:130,separator:!0,icon:`o-spreadsheet-Icon.TRASH`}).addChild(`delete_cell_up`,[`delete_cell`],{...eP,name:j(`Shift up`),sequence:10,icon:`o-spreadsheet-Icon.DELETE_CELL_SHIFT_UP`}).addChild(`delete_cell_left`,[`delete_cell`],{...tP,name:j(`Shift left`),sequence:20,icon:`o-spreadsheet-Icon.DELETE_CELL_SHIFT_LEFT`}).add(`edit_table`,{...rP,isVisible:qE,isEnabled:e=>!e.isSmall,sequence:140}).add(`delete_table`,{...iP,isVisible:qE,sequence:145,separator:!0}).add(`insert_link`,{...jD,name:GE,sequence:150,separator:!0}).add(`pivot_headers_group`,{sequence:155,icon:`o-spreadsheet-Icon.PLUS_IN_BOX`,...pP}).add(`pivot_group_remaining`,{sequence:155,icon:`o-spreadsheet-Icon.PLUS_IN_BOX`,...mP}).add(`pivot_headers_ungroup`,{sequence:155,icon:`o-spreadsheet-Icon.MINUS_IN_BOX`,...hP}).add(`collapse_pivot`,{sequence:156,name:j(`Expand/Collapse`),icon:`o-spreadsheet-Icon.COLLAPSE`}).addChild(`toggle_collapse_pivot_cell`,[`collapse_pivot`],{sequence:10,...gP}).addChild(`collapse_all_pivot`,[`collapse_pivot`],{sequence:20,..._P}).addChild(`expand_all_pivot`,[`collapse_pivot`],{sequence:30,...vP}).add(`pivot_sorting`,{name:j(`Sort pivot`),sequence:155,icon:`o-spreadsheet-Icon.SORT_RANGE`,isVisible:e=>{let t=e.model.getters.getActivePosition();return bP(e.model.getters,t)}}).add(`pivot_fix_formulas`,{...fP,sequence:160}).add(`pivot_properties`,{...cP,sequence:170,separator:!0}).addChild(`pivot_sorting_asc`,[`pivot_sorting`],{...lP,sequence:10}).addChild(`pivot_sorting_desc`,[`pivot_sorting`],{...uP,sequence:20}).addChild(`pivot_sorting_none`,[`pivot_sorting`],{...dP,sequence:30});let AP={name:j(`Sort range`),isVisible:$E,icon:`o-spreadsheet-Icon.SORT_RANGE`},jP={name:j(`Ascending (A ⟶ Z)`),execute:e=>{let{anchor:t,zones:n}=e.model.getters.getSelection();xw(e,e.model.getters.getActiveSheetId(),t.cell,n[0],`asc`)},icon:`o-spreadsheet-Icon.SORT_ASCENDING`},MP={name:j(`Data cleanup`),icon:`o-spreadsheet-Icon.DATA_CLEANUP`},NP={name:j(`Remove duplicates`),execute:e=>{Xn(e.model.getters.getSelectedZone())===1&&e.model.selection.selectTableAroundSelection(),e.openSidePanel(`RemoveDuplicates`,{})},isEnabled:e=>!e.isSmall},PP={name:j(`Trim whitespace`),execute:e=>{e.model.dispatch(`TRIM_WHITESPACE`)}},FP={name:j(`Descending (Z ⟶ A)`),execute:e=>{let{anchor:t,zones:n}=e.model.getters.getSelection();xw(e,e.model.getters.getActiveSheetId(),t.cell,n[0],`desc`)},icon:`o-spreadsheet-Icon.SORT_DESCENDING`},IP={...tD},LP={...tD,isActive:e=>KE(e)},RP={name:j(`Split text to columns`),sequence:1,execute:e=>e.openSidePanel(`SplitToColumns`,{}),isEnabled:e=>!e.isSmall&&e.model.getters.isSingleColSelected(),icon:`o-spreadsheet-Icon.SPLIT_TEXT`},zP={name:j(`Column statistics`),execute:e=>e.openSidePanel(`ColumnStats`,{}),icon:`o-spreadsheet-Icon.COLUMN_STATS`},BP={id:`reinsert_dynamic_pivot`,name:j(`Re-insert dynamic pivot`),sequence:60,icon:`o-spreadsheet-Icon.INSERT_PIVOT`,children:[zE],isVisible:e=>e.model.getters.getPivotIds().some(t=>e.model.getters.getPivot(t).isValid())},VP={id:`reinsert_static_pivot`,name:j(`Re-insert static pivot`),sequence:70,icon:`o-spreadsheet-Icon.INSERT_PIVOT`,children:[BE],isVisible:e=>e.model.getters.getPivotIds().some(t=>e.model.getters.getPivot(t).isValid())},HP=new PN;HP.add(`cut`,{...BN,sequence:10}).add(`copy`,{...zN,sequence:20}).add(`paste`,{...VN,sequence:30}).add(`paste_special`,{...HN,sequence:40,separator:!0}).addChild(`paste_value_only`,[`paste_special`],{...UN,sequence:10}).addChild(`paste_format_only`,[`paste_special`],{...WN,sequence:20}).add(`sort_columns`,{...AP,name:e=>e.model.getters.getActiveCols().size>1?j(`Sort columns`):j(`Sort column`),sequence:50,separator:!0}).addChild(`sort_ascending`,[`sort_columns`],{...jP,sequence:10}).addChild(`sort_descending`,[`sort_columns`],{...FP,sequence:20}).add(`column_statistics`,{...zP,sequence:60,separator:!0}).add(`add_column_before`,{...lD,sequence:70}).add(`add_column_after`,{...fD,sequence:80}).add(`delete_column`,{...XN,sequence:90,icon:`o-spreadsheet-Icon.TRASH`}).add(`clear_column`,{...QN,sequence:100,icon:`o-spreadsheet-Icon.CLEAR`}).add(`hide_columns`,{...aN,sequence:105,separator:!0}).add(`unhide_columns`,{...oN,sequence:106,separator:!0}).add(`conditional_formatting`,{...DA,sequence:110,separator:!0}).add(`edit_table`,{...rP,isVisible:qE,sequence:120}).add(`delete_table`,{...iP,isVisible:qE,sequence:125,separator:!0}).add(`group_columns`,{sequence:150,...TN}).add(`ungroup_columns`,{sequence:155,...DN,isVisible:e=>jN(e,`COL`)});let UP={CannotHideAllRows:j(`Cannot hide all the rows of a sheet.`),CannotHideAllColumns:j(`Cannot hide all the columns of a sheet.`)};function WP(e,t,n,r,i){let a=e.model.getters.getHeaderGroup(t,n,r,i);if(!a)return;let o=a.isFolded?`UNFOLD_HEADER_GROUP`:`FOLD_HEADER_GROUP`,s=e.model.dispatch(o,{sheetId:t,dimension:n,start:a.start,end:a.end});if(!s.isSuccessful&&s.isCancelledBecause(`NotEnoughElements`)){let t=n===`ROW`?UP.CannotHideAllRows:UP.CannotHideAllColumns;e.raiseError(t)}}function GP(e,t){return p([{id:`unfold_all`,name:j(t===`ROW`?`Expand all row groups`:`Expand all column groups`),execute:n=>{n.model.dispatch(`UNFOLD_ALL_HEADER_GROUPS`,{sheetId:e,dimension:t})},icon:`o-spreadsheet-Icon.EXPAND`},{id:`fold_all`,name:j(t===`ROW`?`Collapse all row groups`:`Collapse all column groups`),execute:n=>{n.model.dispatch(`FOLD_ALL_HEADER_GROUPS`,{sheetId:e,dimension:t})},icon:`o-spreadsheet-Icon.COLLAPSE`}])}function KP(e,t,n,r){return[...p([{id:`toggle_group`,name:e=>{let i=e.model.getters.getActiveSheetId();return e.model.getters.isGroupFolded(i,t,n,r)?j(t===`ROW`?`Expand row group`:`Expand column group`):j(t===`ROW`?`Collapse row group`:`Collapse column group`)},execute:e=>{WP(e,e.model.getters.getActiveSheetId(),t,n,r)},icon:e=>{let i=e.model.getters.getActiveSheetId();return e.model.getters.isGroupFolded(i,t,n,r)?`o-spreadsheet-Icon.EXPAND`:`o-spreadsheet-Icon.COLLAPSE`}},{id:`remove_group`,name:j(t===`ROW`?`Remove row group`:`Remove column group`),execute:e=>{let i=e.model.getters.getActiveSheetId();e.model.dispatch(`UNGROUP_HEADERS`,{sheetId:i,dimension:t,start:n,end:r})},icon:`o-spreadsheet-Icon.TRASH`,separator:!0}]),...GP(e,t)]}let qP=new PN;qP.add(`group_columns`,{sequence:10,...TN,isVisible:()=>!0,isEnabled:TN.isVisible}).add(`group_rows`,{sequence:20,...EN,isVisible:()=>!0,isEnabled:EN.isVisible});let JP=new PN;JP.add(`ungroup_columns`,{sequence:10,...DN,isEnabled:e=>jN(e,`COL`)}).add(`ungroup_rows`,{sequence:20,...ON,isEnabled:e=>jN(e,`ROW`)});let YP=new PN;YP.add(`cut`,{...BN,sequence:10}).add(`copy`,{...zN,sequence:20}).add(`paste`,{...VN,sequence:30}).add(`paste_special`,{...HN,sequence:40,separator:!0}).addChild(`paste_value_only`,[`paste_special`],{...UN,sequence:10}).addChild(`paste_format_only`,[`paste_special`],{...WN,sequence:20}).add(`add_row_before`,{...rD,sequence:50}).add(`add_row_after`,{...oD,sequence:60}).add(`delete_row`,{...qN,sequence:70,icon:`o-spreadsheet-Icon.TRASH`}).add(`clear_row`,{...YN,sequence:80,icon:`o-spreadsheet-Icon.CLEAR`}).add(`hide_rows`,{...cN,sequence:85,separator:!0}).add(`unhide_rows`,{...lN,sequence:86,separator:!0}).add(`conditional_formatting`,{...DA,sequence:90,separator:!0}).add(`group_rows`,{sequence:100,...EN}).add(`ungroup_rows`,{sequence:110,...ON,isVisible:e=>jN(e,`ROW`)});var XP=class extends wr{highlightStore=this.get(cT);constructor(e){super(e),this.highlightStore.register(this)}get highlights(){let e=this.model.getters.getActivePosition(),t=this.model.getters.getArrayFormulaSpreadingOn(e),n=t?this.model.getters.getSpreadZone(t,{ignoreSpillError:!0}):this.model.getters.getSpreadZone(e,{ignoreSpillError:!0});if(!n)return[];let r=this.getters.getPivotStyleAtPosition(e);if(r?.pivotStyle?.tableStyleId&&r.pivotStyle.tableStyleId!==`None`)return[];let i=this.model.getters.isArrayFormulaSpillBlocked(t??e);return[{range:this.model.getters.getRangeFromZone(e.sheetId,n),dashed:i,color:`#17A2B8`,noFill:!0,thinLine:!0}]}},ZP=class extends wr{mutators=[`focusClient`,`unfocusClient`,`showClientTag`,`hideClientTag`,`jumpToClient`];_showClientTag=!1;clientFocusTimeout={};constructor(e){super(e),this.onDispose(()=>{for(let e in this.clientFocusTimeout)this.unfocusClient(e)})}get focusedClients(){let e=new Set;return this.model.getters.getConnectedClients().forEach(t=>{(this._showClientTag||this.clientFocusTimeout[t.id]!==void 0)&&e.add(t.id)}),e}jumpToClient(e){let t=this.model.getters.getClient(e);this.focusClient(e),t.position&&(this.model.dispatch(`ACTIVATE_SHEET`,{sheetIdTo:t.position.sheetId,sheetIdFrom:this.getters.getActiveSheetId()}),this.model.dispatch(`SCROLL_TO_CELL`,{col:t.position.col,row:t.position.row}))}showClientTag(){this._showClientTag=!0}hideClientTag(){this._showClientTag=!1}focusClient(e){this.clientFocusTimeout[e]&&clearTimeout(this.clientFocusTimeout[e]),this.clientFocusTimeout[e]=setTimeout(()=>this.unfocusClient(e),3e3)}unfocusClient(e){this.clientFocusTimeout[e]&&clearTimeout(this.clientFocusTimeout[e]),this.clientFocusTimeout[e]=void 0}};function QP(e){let n=null,r,i,a,o,s=`all`,c=e.model.getters,l=e=>e.preventDefault(),u=()=>removeEventListener(`keydown`,l,{capture:!0}),d=[],f=()=>{clearTimeout(n),n=null,d.forEach(e=>e()),d=[]},p,m,h=t=>{if(r=t,n)return;let l=c.getActiveSheetId(),u=pm(e.model.getters.getViewportZoomLevel()),d=Pm(e,r,u),{x:f,y:m}=c.getMainViewportCoordinates(),{top:g,left:_,bottom:v,right:y}=c.getActiveMainViewport(),{scrollX:b,scrollY:ee}=c.getActiveSheetScrollInfo(),{xSplit:te,ySplit:ne}=c.getPaneDivisions(l),re=!1,ie=140,ae=d.clientX-u.x,oe=c.getColIndex(ae);if(s!==`vertical`){let t=i.clientX-u.x,n=c.getEdgeScrollCol(ae,t,a);if(n.canEdgeScroll){re=!0,ie=Math.min(ie,n.delay);let t=oe;switch(n.direction){case`reset`:oe=t=te;break;case 1:oe=y,t=_+1;break;case-1:for(oe=_-1;e.model.getters.isColHidden(l,oe);)oe--;t=oe;break}b=c.getColDimensions(l,t).start-f}}let se=d.clientY-u.y,ce=c.getRowIndex(se);if(s!==`horizontal`){let t=i.clientY-u.y,n=c.getEdgeScrollRow(se,t,o);if(n.canEdgeScroll){re=!0,ie=Math.min(ie,n.delay);let t=ce;switch(n.direction){case`reset`:ce=t=ne;break;case 1:ce=v,t=g+1;break;case-1:for(ce=g-1;e.model.getters.isRowHidden(l,ce);)ce--;t=ce;break}ee=e.model.getters.getRowDimensions(l,t).start-m}}re||(oe=$P(oe,ae,c.getNumberCols(l)-1),ce=$P(ce,se,c.getNumberRows(l)-1)),p?.(oe,ce,r),re&&(e.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:b,offsetY:ee}),n=setTimeout(()=>{n=null,h(r)},Math.round(ie))),i={clientX:d.clientX,clientY:d.clientY}},g=()=>{m?.(),f()};return(0,t.onWillUnmount)(()=>{f()}),(0,t.useEffect)(()=>{f()},()=>[c.getActiveSheetId()]),{start:(t,n,r,c=`all`)=>{f();let _=pm(e.model.getters.getViewportZoomLevel());s=c,a=t.clientX-_.x,o=t.clientY-_.y,i={clientX:t.clientX,clientY:t.clientY},p=n,m=r,addEventListener(`keydown`,l,{capture:!0}),d.push(bT(h,g),u)}}}function $P(e,t,n){return e===-1?t<0?0:n:e}var eF=class extends t.Component{static template=`o-spreadsheet-Autofill`;static props={position:Object,isVisible:Boolean};state=(0,t.useState)({position:{x:0,y:0},handler:!1});dragNDropGrid=QP(this.env);get style(){let{x:e,y:t}=this.props.position;return W({top:`${t}px`,left:`${e}px`,visibility:this.props.isVisible?`visible`:`hidden`})}get handlerStyle(){let{x:e,y:t}=this.state.handler?this.state.position:this.props.position;return W({top:`${t}px`,left:`${e}px`,visibility:this.props.isVisible?`visible`:`hidden`})}get styleNextValue(){let{x:e,y:t}=this.state.position;return W({top:`${t+5}px`,left:`${e+15}px`})}getTooltip(){let e=this.env.model.getters.getAutofillTooltip();return e&&!e.component&&(e.component=tF),e}onMouseDown(e){this.state.handler=!0;let t=Pm(this.env,e),n=this.env.model.getters.getViewportZoomLevel(),r,i,a={x:e.clientX/n-this.props.position.x,y:e.clientY/n-this.props.position.y};this.dragNDropGrid.start(t,(e,t,o)=>{if(this.state.position={x:o.clientX/n-a.x,y:o.clientY/n-a.y},r!==e||i!==t){let n=this.env.model.getters.getActiveSheetId(),a=this.env.model.getters.getNumberCols(n),o=this.env.model.getters.getNumberRows(n);r=e===-1?r:S(e,0,a),i=t===-1?i:S(t,0,o),r!==void 0&&i!==void 0&&this.env.model.dispatch(`AUTOFILL_SELECT`,{col:r,row:i})}},()=>{this.state.handler=!1,this.state.position={...this.props.position},this.env.model.dispatch(`AUTOFILL`)})}onDblClick(){this.env.model.dispatch(`AUTOFILL_AUTO`)}},tF=class extends t.Component{static props={content:String};static template=t.xml`
85
85
  <div t-out="props.content"/>
86
86
  `},nF=class extends t.Component{static template=`o-spreadsheet-ClientTag`;static props={active:Boolean,name:String,color:String,col:Number,row:Number};get tagStyle(){let{col:e,row:t,color:n}=this.props,{height:r}=this.env.model.getters.getSheetViewDimensionWithHeaders(),i=this.env.model.getters.isVisibleInViewport({sheetId:this.env.model.getters.getActiveSheetId(),col:e,row:t}),{x:a,y:o}=this.env.model.getters.getVisibleRect({left:e,top:t,right:e,bottom:t});return W({bottom:`${r-o+15}px`,left:`${a-1}px`,border:`1px solid ${n}`,"background-color":n,visibility:i?`visible`:`hidden`})}};let rF=[`*`,`+`,`&`];function iF(e,t=60){return`=`+fF(_F(e),t-1)}function aF(){return{type:`insertLine`}}function oF(e,t){return{type:`nest`,indentLevel:e,doc:t}}function sF(e){return{type:`concat`,docs:e}}function cF(e){return lF(uF(e),e)}function lF(e,t){return{type:`chooseBetween`,doc1:e,doc2:t}}function uF(e){return typeof e==`string`?e:e.type===`chooseBetween`?uF(e.doc1):e.type===`concat`?sF(e.docs.map(uF)):e.type===`nest`?{type:`nest`,indentLevel:e.indentLevel,doc:uF(e.doc)}:e.type===`insertLine`?``:e}let dF=Pt(function(e){return`
87
87
  `+` `.repeat(e)});function fF(e,t){return pF(mF(t,e))}function pF(e){let t=``;for(;e;)t+=e.subString,e=e.next;return t}function mF(e,t){return hF(e,0,{indentLevel:0,doc:t,next:null})}function hF(e,t,n){if(n===null)return null;let{indentLevel:r,doc:i,next:a}=n;if(typeof i==`string`)return{subString:i,next:hF(e,t+i.length,a)};if(i.type===`concat`){let n=a;for(let e=i.docs.length-1;e>=0;e--)n={indentLevel:r,doc:i.docs[e],next:n};return hF(e,t,n)}if(i.type===`nest`)return hF(e,t,{indentLevel:r+i.indentLevel,doc:i.doc,next:a});if(i.type===`insertLine`)return{subString:dF(r),next:hF(e,r,a)};if(i.type===`chooseBetween`){let n=hF(e,t,{indentLevel:r,doc:i.doc1,next:a});return gF(e-t,n)?n:hF(e,t,{indentLevel:r,doc:i.doc2,next:a})}return null}function gF(e,t){for(;t;){if(t.subString[0]===`
88
88
  `)return!0;if(e-=t.subString.length,e<0)return!1;t=t.next}return!0}function _F(e){let t=e.debug?`?`:``;switch(e.type){case`NUMBER`:return t+String(e.value);case`STRING`:return t+`"${e.value}"`;case`BOOLEAN`:return t+(e.value?`TRUE`:`FALSE`);case`FUNCALL`:let n=Fo.get(e.value.toUpperCase()),r=Ci(n,e.args.length),i=[],a=0;for(;a<e.args.length;)if(n.args[r[a].index]?.repeating){let t=e.args.slice(a,a+n.nbrArgRepeating).map(e=>_F(e));i.push(cF(sF(vF(t)))),a+=n.nbrArgRepeating}else i.push(_F(e.args[a])),a++;return yF(sF(vF(i)),t+e.value);case`ARRAY`:return bF(sF(e.value.map(e=>sF(e.map((e,t)=>t===0?_F(e):sF([`, `,aF(),_F(e)])))).map((e,t)=>t===0?cF(e):sF([`; `,aF(),cF(e)]))));case`UNARY_OPERATION`:let o=_F(e.operand),s=(e.postfix?SF(e):CF(e))?yF(o):o;return e.postfix?sF([s,t+e.value]):sF([t+e.value,s]);case`BIN_OPERATION`:{let n=_F(e.left),r=SF(e)?yF(n):n,i=_F(e.right),a=CF(e)?yF(i):i;return cF(sF([r,`${t}${e.value}`,oF(1,sF([aF(),a]))]))}default:return t+e.value}}function vF(e){let t=e.length?[e[0]]:[];for(let n=1;n<e.length;n++)t.push(`, `,aF()),t.push(e[n]);return t}function yF(e,t=void 0){let n=[`(`,oF(1,sF([aF(),e])),aF(),`)`];return t&&n.unshift(t),cF(sF(n))}function bF(e){return cF(sF([`{`,oF(1,sF([aF(),e])),aF(),`}`]))}function xF(e){let t=e.debug?`?`:``;switch(e.type){case`FUNCALL`:let n=e.args.map(e=>xF(e));return`${t}${e.value}(${n.join(`,`)})`;case`NUMBER`:return t+e.value.toString();case`STRING`:return t+`"${e.value}"`;case`BOOLEAN`:return t+(e.value?`TRUE`:`FALSE`);case`UNARY_OPERATION`:if(e.postfix)return(SF(e)?`(${xF(e.operand)})`:xF(e.operand))+t+e.value;let r=CF(e)?`(${xF(e.operand)})`:xF(e.operand);return t+e.value+r;case`ARRAY`:return`{`+t+e.value.map(e=>e.map(e=>xF(e)).join(`,`)).join(`;`)+`}`;case`BIN_OPERATION`:let i=SF(e)?`(${xF(e.left)})`:xF(e.left),a=CF(e)?`(${xF(e.right)})`:xF(e.right);return i+t+e.value+a;default:return t+e.value}}function SF(e){let t=e.value,n=`left`in e?e.left:e.operand,r=n.value;return n.type===`BIN_OPERATION`&&Fs[r]<Fs[t]}function CF(e){let t=e.value,n=`right`in e?e.right:e.operand,r=Fs[n.value],i=Fs[t];return n.type===`BIN_OPERATION`?r<i?!0:r===i&&!rF.includes(t):!1}let wF=j(`The cell you are trying to edit has been deleted.`);var TF=class extends dT{canStopEdition(){return this.editionMode===`inactive`?!0:this.checkDataValidation()}stopEdition(e){if(this.canStopEdition()){let{col:t,row:n}=this.currentEditedCell;this._stopEdition(),e&&(this.getters.isSingleCellOrMerge(this.sheetId,this.getters.getSelectedZone())?(this.model.selection.selectCell(t,n),this.model.selection.moveAnchorCell(e,1)):Fw(this.getters,this.model.selection,e));return}let t=this.currentEditedCell,n=E(t.col,t.row),r=this.getters.getValidationRuleForCell(t);if(!r)return;let i=X.get(r.criterion.type).getErrorString(r.criterion,this.getters,t.sheetId);this.notificationStore.raiseError(j(`The data you entered in %s violates the data validation rule set on the cell:
89
- %s`,n,i)),this.cancelEdition()}handle(e){switch(super.handle(e),e.type){case`SET_FORMATTING`:this.cancelEdition();break;case`ADD_COLUMNS_ROWS`:this.onAddElements(e);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.onColumnsRemoved(e):this.onRowsRemoved(e);break;case`ACTIVATE_SHEET`:if(qt(this._currentContent)||(this._cancelEdition(),this.resetContent()),e.sheetIdFrom!==e.sheetIdTo){let t=this.getters.getActivePosition(),{col:n,row:r}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:t.col,row:t.row}),i=this.getters.expandZone(e.sheetIdTo,D({col:n,row:r}));this.model.selection.resetAnchor(this,{cell:{col:n,row:r},zone:i})}break;case`DELETE_SHEET`:case`UNDO`:case`REDO`:!this.getters.tryGetSheet(this.sheetId)&&this.editionMode!==`inactive`&&(this.sheetId=this.getters.getActiveSheetId(),this.resetContent(),this.cancelEditionAndActivateSheet(),this.notificationStore.raiseError(wF));break}}get placeholder(){let e=this.getters.getActivePosition(),t=this.model.getters.getArrayFormulaSpreadingOn(e);if(t)return this.getters.getCellText(t,{showFormula:!0})}get currentEditedCell(){return{sheetId:this.sheetId,col:this.col,row:this.row}}onColumnsRemoved(e){if(e.elements.includes(this.col)&&this.editionMode!==`inactive`){this.cancelEdition(),this.notificationStore.raiseError(wF);return}let{top:t,left:n}=Dn({left:this.col,right:this.col,top:this.row,bottom:this.row},`left`,[...e.elements]);this.col=n,this.row=t}onRowsRemoved(e){if(e.elements.includes(this.row)&&this.editionMode!==`inactive`){this.cancelEdition(),this.notificationStore.raiseError(wF);return}let{top:t,left:n}=Dn({left:this.col,right:this.col,top:this.row,bottom:this.row},`top`,[...e.elements]);this.col=n,this.row=t}onAddElements(e){let{top:t,left:n}=En({left:this.col,right:this.col,top:this.row,bottom:this.row},e.dimension===`COL`?`left`:`top`,e.base,e.position,e.quantity);this.col=n,this.row=t}confirmEdition(e){let t;if(e){let n={sheetId:this.getters.getActiveSheetId(),col:this.col,row:this.row},r=this.getters.getEvaluatedCell(n);r.link&&!qt(e)&&(e=ut(e,r.link.url));let i=this.getters.getCell(n)?.format,a=i===`@`||i&&Il(i)?void 0:Vl(e,this.getters.getLocale());this.addHeadersForSpreadingFormula(e),t=this.model.dispatch(`UPDATE_CELL`,{...this.currentEditedCell,content:e,format:a})}else t=this.model.dispatch(`UPDATE_CELL`,{...this.currentEditedCell,content:``});t.isSuccessful&&this.model.dispatch(`AUTOFILL_TABLE_COLUMN`,{...this.currentEditedCell}),this.setContent(``)}getComposerContent(e,t){let n=this.getters.getLocale(),r=this.getters.getCell(e);if(r?.isFormula){let e=this.getPrettifiedFormula(r);function i(t){let n=0,r=0;for(;r<t;){n++;let t=e[n];t!==`
89
+ %s`,n,i)),this.cancelEdition()}handle(e){switch(super.handle(e),e.type){case`SET_FORMATTING`:this.cancelEdition();break;case`ADD_COLUMNS_ROWS`:this.onAddElements(e);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.onColumnsRemoved(e):this.onRowsRemoved(e);break;case`ACTIVATE_SHEET`:if(qt(this._currentContent)||(this._cancelEdition(),this.resetContent()),this.model.selection.isListening(this)&&e.sheetIdFrom!==e.sheetIdTo){let t=this.getters.getActivePosition(),{col:n,row:r}=this.getters.getNextVisibleCellPosition({sheetId:e.sheetIdTo,col:t.col,row:t.row}),i=this.getters.expandZone(e.sheetIdTo,D({col:n,row:r}));this.model.selection.resetAnchor(this,{cell:{col:n,row:r},zone:i})}break;case`DELETE_SHEET`:case`UNDO`:case`REDO`:!this.getters.tryGetSheet(this.sheetId)&&this.editionMode!==`inactive`&&(this.sheetId=this.getters.getActiveSheetId(),this.resetContent(),this.cancelEditionAndActivateSheet(),this.notificationStore.raiseError(wF));break}}get placeholder(){let e=this.getters.getActivePosition(),t=this.model.getters.getArrayFormulaSpreadingOn(e);if(t)return this.getters.getCellText(t,{showFormula:!0})}get currentEditedCell(){return{sheetId:this.sheetId,col:this.col,row:this.row}}onColumnsRemoved(e){if(e.elements.includes(this.col)&&this.editionMode!==`inactive`){this.cancelEdition(),this.notificationStore.raiseError(wF);return}let{top:t,left:n}=Dn({left:this.col,right:this.col,top:this.row,bottom:this.row},`left`,[...e.elements]);this.col=n,this.row=t}onRowsRemoved(e){if(e.elements.includes(this.row)&&this.editionMode!==`inactive`){this.cancelEdition(),this.notificationStore.raiseError(wF);return}let{top:t,left:n}=Dn({left:this.col,right:this.col,top:this.row,bottom:this.row},`top`,[...e.elements]);this.col=n,this.row=t}onAddElements(e){let{top:t,left:n}=En({left:this.col,right:this.col,top:this.row,bottom:this.row},e.dimension===`COL`?`left`:`top`,e.base,e.position,e.quantity);this.col=n,this.row=t}confirmEdition(e){let t;if(e){let n={sheetId:this.getters.getActiveSheetId(),col:this.col,row:this.row},r=this.getters.getEvaluatedCell(n);r.link&&!qt(e)&&(e=ut(e,r.link.url));let i=this.getters.getCell(n)?.format,a=i===`@`||i&&Il(i)?void 0:Vl(e,this.getters.getLocale());this.addHeadersForSpreadingFormula(e),t=this.model.dispatch(`UPDATE_CELL`,{...this.currentEditedCell,content:e,format:a})}else t=this.model.dispatch(`UPDATE_CELL`,{...this.currentEditedCell,content:``});t.isSuccessful&&this.model.dispatch(`AUTOFILL_TABLE_COLUMN`,{...this.currentEditedCell}),this.setContent(``)}getComposerContent(e,t){let n=this.getters.getLocale(),r=this.getters.getCell(e);if(r?.isFormula){let e=this.getPrettifiedFormula(r);function i(t){let n=0,r=0;for(;r<t;){n++;let t=e[n];t!==`
90
90
  `&&t!==` `&&r++}return n}let a=t;return t&&(a={start:i(t.start),end:i(t.end)}),{text:Xy(e,n),adjustedSelection:a}}if(this.model.getters.getArrayFormulaSpreadingOn(e))return{text:``};if(r?.content.startsWith(`'`))return{text:r.content};let{format:i,value:a,type:o,formattedValue:s}=this.getters.getEvaluatedCell(e);switch(o){case`empty`:return{text:``};case`text`:case`error`:return{text:a};case`boolean`:return{text:s};case`number`:return i&&Il(i)?ia(s,n)===null?{text:H(a,{locale:n,format:Number.isInteger(a)?n.dateFormat:sb(n)})}:{text:s}:{text:this.numberComposerContent(a,i,n)}}}getPrettifiedFormula(e){if(e.compiledFormula.isBadExpression)return e.compiledFormula.toFormulaString(this.getters);let t=this.editionMode===`inactive`?1/0:80;return iF(e.compiledFormula.getAst(this.getters),t)}numberComposerContent(e,t,n){return t?.includes(`%`)?`${Fl(e*100,n.decimalSeparator)}%`:Fl(e,n.decimalSeparator)}addHeadersForSpreadingFormula(e){let t=Xt(this.getters,this.currentEditedCell,e);t&&(t.missingCols>0&&this.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:this.sheetId,sheetName:this.getters.getSheetName(this.sheetId),dimension:`COL`,base:this.getters.getNumberCols(this.sheetId)-1,position:`after`,quantity:t.missingCols+20}),t.missingRows>0&&this.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:this.sheetId,sheetName:this.getters.getSheetName(this.sheetId),dimension:`ROW`,base:this.getters.getNumberRows(this.sheetId)-1,position:`after`,quantity:t.missingRows+50}))}checkDataValidation(){let e={sheetId:this.sheetId,col:this.col,row:this.row},t=this.getCurrentCanonicalContent(),n=qt(t)?this.getters.evaluateFormula(this.sheetId,t):Hu(t,this.getters.getLocale());if(Sh(n))return!0;let r=this.getters.getValidationResultForCellValue(bh(n),e);return!(!r.isValid&&r.rule.isBlocking)}startEdition(e,t){return this.getters.isCurrentSheetLocked()?(this.model.trigger(`command-rejected`,{result:new Eu(`SheetLocked`),command:{sheetId:this.getters.getActiveSheetId()}}),`NoStateChange`):super.startEdition(e,t)}evaluateCanonicalFormula(e){return this.getters.evaluateFormulaResult(this.sheetId,e,{sheetId:this.sheetId,col:this.col,row:this.row})}};let EF=3*.4*globalThis.devicePixelRatio||1;var DF=class extends t.Component{static template=`o-spreadsheet-GridComposer`;static props={gridDims:Object,onInputContextMenu:Function};static components={Composer:Jw};rect=this.defaultRect;isEditing=!1;isCellReferenceVisible=!1;currentEditedCell={col:0,row:0,sheetId:this.env.model.getters.getActiveSheetId()};composerStore;composerFocusStore;composerInterface;get defaultRect(){return{x:0,y:0,width:0,height:0}}setup(){let e=O(TF);this.composerStore=e,this.composerFocusStore=O(Er),this.composerInterface={id:`gridComposer`,get editionMode(){return e.editionMode},startEdition:this.composerStore.startEdition,setCurrentContent:this.composerStore.setCurrentContent,stopEdition:this.composerStore.stopEdition},this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`inactive`}),(0,t.onWillUpdateProps)(()=>{this.updateComponentPosition(),this.updateCellReferenceVisibility()})}get shouldDisplayCellReference(){return!this.env.isMobile()&&this.isCellReferenceVisible}get cellReference(){let{col:e,row:t,sheetId:n}=this.composerStore.currentEditedCell;return Xo(n===this.env.model.getters.getActiveSheetId()?void 0:this.env.model.getters.getSheetName(n),E(e,t))}get cellReferenceStyle(){let{x:e,y:t}=this.rect;return W({left:`${e-EF}px`,top:`${t-28}px`})}get focus(){return this.composerFocusStore.activeComposer===this.composerInterface?this.composerFocusStore.focusMode:`inactive`}get composerProps(){let{width:e,height:t}=this.env.model.getters.getSheetViewDimensionWithHeaders(),n=this.props.gridDims.height-this.rect.y-2*EF;return{rect:{...this.rect},delimitation:{width:e,height:t},focus:this.focus,isDefaultFocus:!0,onComposerContentFocused:e=>this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`contentFocus`,selection:e}),onComposerCellFocused:e=>this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`cellFocus`,content:e}),onInputContextMenu:this.props.onInputContextMenu,composerStore:this.composerStore,inputStyle:`max-height: ${n}px;`,inputMode:this.composerStore.editionMode===`inactive`?`none`:void 0}}get containerStyle(){if(this.composerStore.editionMode===`inactive`||this.env.isMobile())return`z-index: -1000; opacity: 0;`;let e=qt(this.composerStore.currentContent),t=this.env.model.getters.getActiveCell(),n=this.env.model.getters.getActivePosition(),r=this.env.model.getters.getCellComputedStyle(n),{x:i,y:a,width:o,height:s}=this.rect,c=!e&&r.fillColor||`#ffffff`,l=!e&&r.textColor||`#000000`,u=!e&&r.fontSize||10,d=!e&&r.bold?`bold`:void 0,f=!e&&r.italic?`italic`:`normal`,p=e?`none`:Kv(r),m=`left`;e||(m=r.align||t.defaultAlign);let h=this.props.gridDims.height-this.rect.y,g=this.props.gridDims.width-this.rect.x,_=Math.min(s+1,h),v=Math.min(o+1,g);return W({left:`${i-1}px`,top:`${a}px`,border:`${EF}px solid ${ae}`,"min-width":`${v}px`,"min-height":`${_}px`,"max-width":`${g}px`,"max-height":`${h}px`,background:c,color:l,"font-size":`${Td(u)}px`,"font-weight":d,"font-style":f,"text-decoration":p,"text-align":m})}updateComponentPosition(){let e=this.composerFocusStore.activeComposer.editionMode!==`inactive`;!e&&this.composerFocusStore.activeComposer!==this.composerInterface&&this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`inactive`});let t=!T(this.currentEditedCell,this.composerStore.currentEditedCell);if(this.isEditing!==e){if(this.isEditing=e,!e){this.rect=this.defaultRect;return}this.currentEditedCell=this.composerStore.currentEditedCell,t=!0}if(t){let e=this.env.model.getters.getActivePosition(),t=this.env.model.getters.expandZone(e.sheetId,D(e));this.rect=this.env.model.getters.getVisibleRect(t)}}updateCellReferenceVisibility(){if(this.composerStore.editionMode===`inactive`){this.isCellReferenceVisible=!1;return}if(this.isCellReferenceVisible)return;let e=this.env.model.getters.getActiveSheetId(),t=D(this.env.model.getters.getSelection().anchor.cell);(!T(this.env.model.getters.getVisibleRect(t),this.rect)||e!==this.composerStore.currentEditedCell.sheetId)&&(this.isCellReferenceVisible=!0)}onFocus(){this.composerFocusStore.focusComposer(this.composerInterface,{focusMode:`contentFocus`})}};function OF({x:e,y:t},{x:n,y:r},i,{maxX:a,maxY:o},{scrollX:s,scrollY:c},{scrollX:l,scrollY:u}){let d=e-n+l-s,f=S(i.x+d,0,a-i.width),p=t-r+u-c,m=S(i.y+p,0,o-i.height);return{...i,x:f,y:m}}function kF(e,t,n,{x:r,y:i},{x:a,y:o},s,c,{scrollX:l,scrollY:u},{scrollX:d,scrollY:f},{maxX:p,maxY:m}){let{x:h,y:g,width:_,height:v}=e;if(s&&t!==0&&n!==0){let e=Math.min(t*(a-r+d-l),_-c),s=Math.min(n*(o-i+f-u),v-c),p=Math.min(e/_,s/v);t<0&&(h+=_*p),n<0&&(g+=v*p),_*=1-p,v*=1-p}else{let e=Math.max(t*(r-a+d-l),c-_),s=Math.max(n*(i-o+f-u),c-v);_+=e,v+=s,t<0&&(h-=e),n<0&&(g-=s)}return h+d<=0?(_=_+h+d,h=-d):h+_>p&&(_=p-h),g+f<=0?(v=v+g+f,g=-f):g+v>m&&(v=m-g),{...e,x:h,y:g,width:_,height:v}}function AF(e,t,n){let r=PF(e,t,[`hCenter`,`right`,`left`],n,[`hCenter`,`right`,`left`]),i=PF(e,t,[`vCenter`,`bottom`,`top`],n,[`vCenter`,`bottom`,`top`]),{y:a,x:o}=e.getMainViewportCoordinates(),{scrollY:s,scrollX:c}=e.getActiveSheetScrollInfo();if(i){t.y-=i.snapOffset;let e=t.y<a,n=t.y<a;e&&!n?t.y+=s:!e&&n&&(t.y-=s)}if(r){t.x-=r.snapOffset;let e=t.x<o,n=t.x<o;e&&!n?t.x+=c:!e&&n&&(t.x-=c)}return{snappedFigure:t,verticalSnapLine:r,horizontalSnapLine:i}}function jF(e,t,n,r,i){let a=PF(e,r,[t===-1?`left`:`right`],i,[`right`,`left`]);a&&(t===1?r.width-=a.snapOffset:t===-1&&(r.x-=a.snapOffset,r.width+=a.snapOffset));let o=PF(e,r,[n===-1?`top`:`bottom`],i,[`bottom`,`top`]);return o&&(n===1?r.height-=o.snapOffset:n===-1&&(r.y-=o.snapOffset,r.height+=o.snapOffset)),r.x=Math.round(r.x),r.y=Math.round(r.y),r.height=Math.round(r.height),r.width=Math.round(r.width),{snappedFigure:r,verticalSnapLine:a,horizontalSnapLine:o}}function MF(e,t,n){return n.map(n=>IF(e,t,!1,n)).filter(n=>NF(e,t,n))}function NF(e,t,n){let{x:r,y:i}=e.getMainViewportCoordinates(),a=[];switch(n.axisType){case`top`:case`bottom`:case`vCenter`:if(t.y<i)return!0;a.push({x:t.x,y:n.position}),a.push({x:t.x+t.width,y:n.position});break;case`left`:case`right`:case`hCenter`:if(t.x<r)return!0;a.push({x:n.position,y:t.y}),a.push({x:n.position,y:t.y+t.height});break}return a.some(e.isPixelPositionVisible)}function PF(e,t,n,r,i){let a=n.map(n=>IF(e,t,!0,n)),o;for(let t of r){let n=MF(e,t,i);for(let e of a)for(let r of n){if(!FF(e.position,r.position))continue;let n=e.position-r.position;o&&n===o.snapOffset?o.matchedFigIds.push(t.id):(!o||Math.abs(n)<=Math.abs(o.snapOffset))&&(o={matchedFigIds:[t.id],snapOffset:n,snappedAxisType:e.axisType,position:r.position})}}return o}function FF(e,t){return Math.abs(e-t)<=5}function IF(e,t,n,r){let i=0,{scrollX:a,scrollY:o}=e.getActiveSheetScrollInfo(),{x:s,y:c}=e.getMainViewportCoordinates(),l=!n&&t.y<c?t.y+o:t.y,u=!n&&t.x<s?t.x+a:t.x;switch(r){case`top`:i=l;break;case`bottom`:i=l+t.height-1;break;case`vCenter`:i=l+Math.floor(t.height/2)-1;break;case`left`:i=u;break;case`right`:i=u+t.width-1;break;case`hCenter`:i=u+Math.floor(t.width/2)-1;break}return{position:i,axisType:r}}var LF=class extends t.Component{static template=`o-spreadsheet-FiguresContainer`;static props={};static components={FigureComponent:jy};dnd=(0,t.useState)({draggedFigure:void 0,horizontalSnap:void 0,verticalSnap:void 0,cancelDnd:void 0,overlappingCarousel:void 0});setup(){(0,t.onMounted)(()=>{this.render()}),(0,t.onWillUpdateProps)(()=>{let e=this.env.model.getters.getActiveSheetId(),t=this.dnd.draggedFigure?.id;t&&!this.env.model.getters.getFigure(e,t)&&(this.dnd.cancelDnd&&this.dnd.cancelDnd(),this.dnd.draggedFigure=void 0,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0,this.dnd.overlappingCarousel=void 0,this.dnd.cancelDnd=void 0)})}getVisibleFigures(){let e=this.env.model.getters.getVisibleFigures();return this.dnd.draggedFigure&&!e.some(e=>e.id===this.dnd.draggedFigure?.id)&&this.dnd.draggedFigure&&e.push(this.dnd.draggedFigure),e}get containers(){let e=this.getVisibleFigures(),t=[];for(let n of[`topLeft`,`topRight`,`bottomLeft`,`bottomRight`]){let r=e.filter(e=>this.getFigureContainer(e)===n);r.length>0&&t.push({type:n,figures:r,style:this.getContainerStyle(n),inverseViewportStyle:this.getInverseViewportPositionStyle(n)})}return this.dnd.draggedFigure&&t.push({type:`dnd`,figures:[this.getDndFigure()],style:this.getContainerStyle(`dnd`),inverseViewportStyle:this.getInverseViewportPositionStyle(`dnd`)}),t}getContainerStyle(e){return this.rectToCss(this.getContainerRect(e))}rectToCss(e){return W({left:`${e.x}px`,top:`${e.y}px`,width:`${e.width}px`,height:`${e.height}px`})}getContainerRect(e){let{width:t,height:n}=this.env.model.getters.getSheetViewDimension(),{x:r,y:i}=this.env.model.getters.getMainViewportCoordinates(),a=[`bottomRight`,`topRight`].includes(e)?r:0,o=t-a,s=[`bottomRight`,`bottomLeft`].includes(e)?i:0;return{x:a,y:s,width:o,height:n-s}}getInverseViewportPositionStyle(e){let{scrollX:t,scrollY:n}=this.env.model.getters.getActiveSheetScrollInfo(),{x:r,y:i}=this.env.model.getters.getMainViewportCoordinates(),a=0,o=0;return e===`dnd`&&(a=-t,o=-n),[`bottomRight`,`topRight`].includes(e)&&(a=-t-r),[`bottomRight`,`bottomLeft`].includes(e)&&(o=-n-i),W({left:`${a}px`,top:`${o}px`})}getFigureContainer(e){let{x:t,y:n}=this.env.model.getters.getMainViewportCoordinates();return e.id===this.dnd.draggedFigure?.id?`dnd`:e.x<t&&e.y<n?`topLeft`:e.x<t?`bottomLeft`:e.y<n?`topRight`:`bottomRight`}toBottomRightViewport(e){let t=this.getFigureContainer(e),n=this.env.model.getters.getActiveSheetScrollInfo(),r={...e};return[`bottomLeft`,`topLeft`].includes(t)&&(r.x+=n.scrollX),[`topLeft`,`topRight`].includes(t)&&(r.y+=n.scrollY),r}startDraggingFigure(e,t){if(t.button>0||this.env.model.getters.isReadonly()||!this.env.model.dispatch(`SELECT_FIGURE`,{figureId:e.id}).isSuccessful||this.env.isMobile()||this.env.model.getters.isCurrentSheetLocked())return;let n=this.env.model.getters.getActiveSheetId(),r=this.env.model.getters.getViewportZoomLevel(),i={x:t.clientX/r,y:t.clientY/r},a=this.env.model.getters.getActiveSheetScrollInfo(),o=this.toBottomRightViewport(e),s={maxX:this.env.model.getters.getColDimensions(n,this.env.model.getters.getNumberCols(n)-1).end,maxY:this.env.model.getters.getRowDimensions(n,this.env.model.getters.getNumberRows(n)-1).end},c=!1,l=e=>{let t=this.env.model.getters,n={x:e.clientX/r,y:e.clientY/r},l=Math.abs(n.x-i.x),u=Math.abs(n.y-i.y);if(!c&&l<5&&u<5)return;c=!0;let d=OF(n,i,o,s,a,t.getActiveSheetScrollInfo()),f=this.getOtherFigures(o.id),p=this.getCarouselOverlappingChart(d,f);if(this.dnd.overlappingCarousel=p,p)this.dnd.draggedFigure=d,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0;else{let e=AF(t,d,f);this.dnd.draggedFigure=e.snappedFigure,this.dnd.horizontalSnap=this.getSnap(e.horizontalSnapLine),this.dnd.verticalSnap=this.getSnap(e.verticalSnapLine)}},u=t=>{if(!this.dnd.draggedFigure)return;let{col:r,row:i,offset:a}=this.env.model.getters.getPositionAnchorOffset(this.dnd.draggedFigure);this.dnd.overlappingCarousel?this.env.model.dispatch(`ADD_FIGURE_CHART_TO_CAROUSEL`,{sheetId:n,carouselFigureId:this.dnd.overlappingCarousel.id,chartFigureId:e.id}):this.env.model.dispatch(`UPDATE_FIGURE`,{sheetId:n,figureId:e.id,offset:a,col:r,row:i}),this.dnd.draggedFigure=void 0,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0,this.dnd.overlappingCarousel=void 0};this.dnd.cancelDnd=bT(l,u)}startResize(e,t,n,r){r.stopPropagation();let i=this.env.model.getters.getActiveSheetScrollInfo(),a=Ay.get(e.tag).keepRatio||!1,o=Ay.get(e.tag).minFigSize||80,s=this.env.model.getters.getViewportZoomLevel(),c=this.env.model.getters.getActiveSheetId(),l={x:r.clientX/s,y:r.clientY/s},u={maxX:this.env.model.getters.getColDimensions(c,this.env.model.getters.getNumberCols(c)-1).end,maxY:this.env.model.getters.getRowDimensions(c,this.env.model.getters.getNumberRows(c)-1).end},d=r=>{let c=kF(e,t,n,{x:r.clientX/s,y:r.clientY/s},l,a,o,i,this.env.model.getters.getActiveSheetScrollInfo(),u),d=this.getOtherFigures(e.id),f=jF(this.env.model.getters,t,n,c,d);this.dnd.draggedFigure=f.snappedFigure,this.dnd.horizontalSnap=this.getSnap(f.horizontalSnapLine),this.dnd.verticalSnap=this.getSnap(f.verticalSnapLine)},f=r=>{if(!this.dnd.draggedFigure)return;let i=this.env.model.getters.getPositionAnchorOffset(this.dnd.draggedFigure);t&&(i.width=this.dnd.draggedFigure.width),n&&(i.height=this.dnd.draggedFigure.height),this.env.model.dispatch(`UPDATE_FIGURE`,{sheetId:this.env.model.getters.getActiveSheetId(),figureId:e.id,...i}),this.dnd.draggedFigure=void 0,this.dnd.horizontalSnap=void 0,this.dnd.verticalSnap=void 0,this.dnd.overlappingCarousel=void 0};this.dnd.cancelDnd=bT(d,f)}getOtherFigures(e){return this.getVisibleFigures().filter(t=>t.id!==e)}getDndFigure(){let e=this.dnd.draggedFigure;if(!e)throw Error(`Dnd figure not found`);return e}getFigureStyle(e){return e.id===this.dnd.draggedFigure?.id?W({opacity:this.dnd.overlappingCarousel?.id?`0.6`:`0.9`,cursor:`grabbing`}):``}getFigureClass(e){return e.id===this.dnd.overlappingCarousel?.id?`o-add-to-carousel`:``}getSnap(e){if(!e||!this.dnd.draggedFigure)return;let{scrollX:t,scrollY:n}=this.env.model.getters.getActiveSheetScrollInfo(),r=e.matchedFigIds.map(e=>this.getVisibleFigures().find(t=>t.id===e)).filter(w).map(e=>({x:e.x-t,y:e.y-n,width:e.width,height:e.height})).filter(w),i=my({...this.dnd.draggedFigure,x:this.dnd.draggedFigure.x-t,y:this.dnd.draggedFigure.y-n},...r);return{line:e,containerStyle:this.rectToCss(i),lineStyle:this.getSnapLineStyle(e,i)}}getSnapLineStyle(e,t){if(!e)return``;let{scrollX:n,scrollY:r}=this.env.model.getters.getActiveSheetScrollInfo();return[`top`,`vCenter`,`bottom`].includes(e.snappedAxisType)?W({top:`${e.position-t.y-r}px`,left:`0px`,width:`100%`}):W({top:`0px`,left:`${e.position-t.x-n}px`,height:`100%`})}getCarouselOverlappingChart(e,t){if(e.tag!==`chart`)return;let n=e.x+e.width/2,r=e.y+e.height/2,i,a=1/0;for(let o of t){if(o.tag!==`carousel`)continue;let t=o.x+o.width/2,s=o.y+o.height/2,c=Math.abs(n-t),l=Math.abs(r-s),u=c**2+l**2;c<=e.width/2&&l<=e.height/2&&u<a&&(a=u,i=o)}return i}},RF=class extends t.Component{static template=`o-spreadsheet-GridAddRowsFooter`;static props={};static components={ValidationMessages:$D};DOMFocusableElementStore;inputRef=(0,t.useRef)(`inputRef`);state=(0,t.useState)({inputValue:`100`,errorFlag:!1});setup(){this.DOMFocusableElementStore=O(ly),(0,t.useExternalListener)(window,`click`,this.onExternalClick,{capture:!0})}get addRowsPosition(){let e=this.env.model.getters.getActiveSheetId(),{numberOfRows:t}=this.env.model.getters.getSheetSize(e),{scrollY:n}=this.env.model.getters.getActiveSheetScrollInfo();return W({top:`${this.env.model.getters.getRowDimensions(e,t-1).end-n}px`})}get errorMessages(){return[j(`Please enter a number between 0 and 10000.`)]}onKeydown(e){e.key.toUpperCase()===`ESCAPE`?this.focusDefaultElement():e.key.toUpperCase()===`ENTER`&&this.onConfirm()}onInput(e){let t=e.target.value;this.state.inputValue=t;let n=Number(t);this.state.errorFlag=Number.isNaN(n)||n<=0||n>1e4}onConfirm(){if(this.state.errorFlag)return;let e=Number(this.state.inputValue),t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getNumberRows(t);this.env.model.dispatch(`ADD_COLUMNS_ROWS`,{sheetId:t,sheetName:this.env.model.getters.getSheetName(t),position:`after`,base:n-1,quantity:e,dimension:`ROW`}),this.focusDefaultElement();let{scrollX:r}=this.env.model.getters.getActiveSheetScrollInfo(),{end:i}=this.env.model.getters.getRowDimensions(t,n+e-1);this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:r,offsetY:i})}onExternalClick(e){this.inputRef.el!==document.activeElement||e.target===this.inputRef.el||this.focusDefaultElement()}focusDefaultElement(){document.activeElement===this.inputRef.el&&this.DOMFocusableElementStore.focus()}};let zF={figureHandlers:new A,cellHandlers:new A},BF=[`cell`,`border`,`table`,`conditionalFormat`,`merge`];var VF=class extends wr{mutators=[`activate`,`cancel`,`pasteFormat`];highlightStore=this.get(cT);status=`inactive`;copiedData;constructor(e){super(e),this.highlightStore.register(this),this.onDispose(()=>{this.highlightStore.unRegister(this)})}handle(e){switch(e.type){case`PAINT_FORMAT`:this.paintFormat(e.sheetId,e.target);break}}activate(e){this.copiedData=this.copyFormats(),this.status=e.persistent?`persistent`:`oneOff`}cancel(){this.status=`inactive`,this.copiedData=void 0}pasteFormat(e){this.model.dispatch(`PAINT_FORMAT`,{target:e,sheetId:this.getters.getActiveSheetId()})}get isActive(){return this.status!==`inactive`}get clipboardHandlers(){return BF.map(e=>({handlerName:e,handler:new(zF.cellHandlers.get(e))(this.getters,this.model.dispatch)}))}copyFormats(){let e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZones(),n={zones:t,sheetId:e};for(let{handlerName:r,handler:i}of this.clipboardHandlers){let a=i.copy(GT(e,t),!1);a!==void 0&&(n[r]=a)}return n}paintFormat(e,t){if(!this.copiedData)return;let n={isCutOperation:!1,pasteOption:`onlyFormat`},{target:r,selectedZones:i}=QT(e,t,this.copiedData,this.clipboardHandlers,n);ZT(this.clipboardHandlers,this.copiedData,r,n),$T(this.model.selection,t,i),this.status===`oneOff`&&this.cancel()}get highlights(){let e=this.copiedData;return e?e.zones.map(t=>({range:this.model.getters.getRangeFromZone(e.sheetId,t),color:ae,dashed:!0,sheetId:e.sheetId,noFill:!0,thinLine:!0,interactive:!1})):[]}},HF=class extends wr{mutators=[`clear`,`hover`];col;row;overlayColors=new tN;handle(e){switch(e.type){case`ACTIVATE_SHEET`:this.clear()}}hover(e){if(!this.getters.isDashboard()||e.col===this.col&&e.row===this.row)return`noStateChange`;this.col=e.col,this.row=e.row,this.computeOverlay()}clear(){this.col=void 0,this.row=void 0}computeOverlay(){this.overlayColors=new tN;let{col:e,row:t}=this;if(e===void 0||t===void 0)return;let n=this.getters.getActiveSheetId(),r=this.getters.getTable({sheetId:n,col:e,row:t});if(!r)return;let{left:i,right:a,top:o}=r.range.zone,s=t<o+r.config.numberOfHeaders,c=C(i,a+1).some(e=>!this.getters.isColHidden(n,e)&&this.getters.getEvaluatedCell({sheetId:n,col:e,row:t}).formattedValue);if(!s&&c)for(let e=i;e<=a;e++)this.overlayColors.set({sheetId:n,col:e,row:t},`#017E8414`)}},UF=class extends wr{mutators=[`setHoveredIcon`];hoveredIcon=void 0;setHoveredIcon(e){this.hoveredIcon=e}};function WF(e,n){let r=O(My),i=O(HF),a={col:void 0,row:void 0},{Date:o}=window,s,c,l=0;function u(){return s===void 0||c===void 0?{col:-1,row:-1}:{col:e.model.getters.getColIndex(s),row:e.model.getters.getRowIndex(c)}}function d(e){let t=gm(n.el);return{x:e.clientX-t.x,y:e.clientY-t.y}}let{pause:f,resume:p}=uy(m,200);function m(){let{col:e,row:t}=u(),n=o.now()-l;if(n>300&&(e!==a.col||t!==a.row)&&y(void 0,void 0),n>300){if(e<0||t<0)return;y(e,t)}}function h(e){fm(n.el,e.ev)&&({x:s,y:c}=d(e),l=o.now(),i.hover(u()))}function g(){let{col:e,row:t}=u();(e!==a.col||t!==a.row)&&y(void 0,void 0)}function _(t){let r=Pm(e,t),{x:i,y:a}=d(r),o=gm(n.el);return a<0||a>o.height||i<0||i>o.width?h(r):f()}ck(n,`pointermove`,t=>!e.isMobile()&&h(Pm(e,t))),ck(n,`mouseleave`,_),ck(n,`mouseenter`,p),ck(n,`pointerdown`,g),ck(n,`pointerdown`,t=>e.isMobile()&&h(Pm(e,t))),(0,t.useExternalListener)(window,`click`,v);function v(e){let t=e.target;n.el.contains(t)||y(void 0,void 0)}function y(e,t){(e!==a.col||t!==a.row)&&(a.col=e,a.row=t,r.hover({col:e,row:t}))}return a}var GF=class extends t.Component{static template=`o-spreadsheet-GridOverlay`;static props={onCellDoubleClicked:{type:Function,optional:!0},onCellClicked:{type:Function,optional:!0},onCellRightClicked:{type:Function,optional:!0},onGridResized:{type:Function,optional:!0},onGridMoved:Function,gridOverlayDimensions:String,slots:{type:Object,optional:!0}};static components={FiguresContainer:LF,GridAddRowsFooter:RF};static defaultProps={onCellDoubleClicked:()=>{},onCellClicked:()=>{},onCellRightClicked:()=>{},onGridResized:()=>{}};gridOverlay=(0,t.useRef)(`gridOverlay`);cellPopovers;paintFormatStore;hoveredIconStore;setup(){WF(this.env,this.gridOverlay);let e=new ResizeObserver(()=>{this.props.onGridResized()});(0,t.onMounted)(()=>{e.observe(this.gridOverlayEl)}),(0,t.onWillUnmount)(()=>{e.disconnect()}),this.cellPopovers=O(vw),this.paintFormatStore=O(VF),this.hoveredIconStore=O(UF)}get gridOverlayEl(){if(!this.gridOverlay.el)throw Error(`GridOverlay el is not defined.`);return this.gridOverlay.el}get style(){return this.props.gridOverlayDimensions+W({cursor:this.hoveredIconStore.hoveredIcon?`pointer`:`default`})}get isPaintingFormat(){return this.paintFormatStore.isActive}onPointerMove(e){if(this.env.isMobile())return;let t=this.getInteractiveIconAtEvent(Pm(this.env,e)),n=t?.type?{id:t.type,position:t.position}:void 0;T(n,this.hoveredIconStore.hoveredIcon)||this.hoveredIconStore.setHoveredIcon(n)}onPointerDown(e){e.button>0||this.env.isMobile()||this.onCellClicked(Pm(this.env,e))}onClick(e){e.button>0||!this.env.isMobile()||this.onCellClicked(Pm(this.env,e))}onCellClicked(e){let t=this.cellPopovers.persistentCellPopover,[n,r]=this.getCartesianCoordinates(e),i=this.getInteractiveIconAtEvent(e);if(i&&this.env.model.selection.getBackToDefault(),this.props.onCellClicked(n,r,{expandZone:e.ev.shiftKey,addZone:Tm(e.ev)},e),i?.onClick&&i.onClick(i.position,this.env),e.ev.target===this.gridOverlay.el&&this.cellPopovers.isOpen&&T(t,this.cellPopovers.persistentCellPopover)){this.cellPopovers.close();return}}onDoubleClick(e){let t=Pm(this.env,e);if(this.getInteractiveIconAtEvent(t))return;let[n,r]=this.getCartesianCoordinates(t);this.props.onCellDoubleClicked(n,r)}onContextMenu(e){let[t,n]=this.getCartesianCoordinates(Pm(this.env,e));this.props.onCellRightClicked(t,n,{x:e.clientX,y:e.clientY})}getCartesianCoordinates(e){return[this.env.model.getters.getColIndex(e.offsetX),this.env.model.getters.getRowIndex(e.offsetY)]}getInteractiveIconAtEvent(e){let t=hm(this.gridOverlay),n=this.env.model.getters.getGridOffset(),r=e.clientX-t.x+n.x,i=e.clientY-t.y+n.y,[a,o]=this.getCartesianCoordinates(e),s=this.env.model.getters.getActiveSheetId(),c={col:a,row:o,sheetId:s},l=this.env.model.getters.getMerge(c);l&&(c={col:l.left,row:l.top,sheetId:s});let u=this.env.model.getters.getCellIcons(c).find(e=>{let t=this.env.model.getters.getMerge(c)||D(c),n=this.env.model.getters.getRect(t);return _y(r,i,this.env.model.getters.getCellIconRect(e,n))});return u?.onClick?u:void 0}},KF=class extends t.Component{static template=`o-spreadsheet-GridPopover`;static props={onClosePopover:Function,onMouseWheel:Function,gridRect:Object};static components={Popover:by};cellPopovers;setup(){this.cellPopovers=O(vw)}get cellPopover(){let e=this.cellPopovers.cellPopover;if(!e.isOpen)return{isOpen:!1};let t=Im(this.env.model.getters.getViewportZoomLevel(),e.anchorRect);return{...e,anchorRect:{...t,x:t.x+this.props.gridRect.x,y:t.y+this.props.gridRect.y}}}},qF=class extends t.Component{static template=`o-spreadsheet-UnhideRowHeaders`;static props={headersGroups:Array,headerRange:Object,offset:{type:Number,optional:!0}};static defaultProps={offset:0};get sheetId(){return this.env.model.getters.getActiveSheetId()}getUnhidePreviousButtonStyle(e){let t=this.env.model.getters.getRect(D({col:0,row:e}));return W({top:t.y+t.height-26-this.props.offset+`px`,"margin-right":`1px`})}getUnhideNextButtonStyle(e){return W({top:this.env.model.getters.getRect(D({col:0,row:e})).y-26-this.props.offset+`px`,"margin-right":`1px`})}unhide(e){this.env.model.dispatch(`UNHIDE_COLUMNS_ROWS`,{sheetId:this.sheetId,dimension:`ROW`,elements:e})}isVisible(e){return e>=this.props.headerRange.start&&e<=this.props.headerRange.end}},JF=class extends t.Component{static template=`o-spreadsheet-UnhideColumnHeaders`;static props={headersGroups:Array,headerRange:Object,offset:{type:Number,optional:!0}};static defaultProps={offset:0};get sheetId(){return this.env.model.getters.getActiveSheetId()}getUnhidePreviousButtonStyle(e){let t=this.env.model.getters.getRect(D({col:e,row:0}));return W({left:t.x+t.width-48-this.props.offset+`px`})}getUnhideNextButtonStyle(e){return W({left:this.env.model.getters.getRect(D({col:e,row:0})).x-48-this.props.offset+`px`})}unhide(e){this.env.model.dispatch(`UNHIDE_COLUMNS_ROWS`,{sheetId:this.sheetId,dimension:`COL`,elements:e})}isVisible(e){return e>=this.props.headerRange.start&&e<=this.props.headerRange.end}},YF=class extends t.Component{static props={onOpenContextMenu:Function};composerFocusStore;PADDING=0;MAX_SIZE_MARGIN=0;MIN_ELEMENT_SIZE=0;lastSelectedElementIndex=null;state=(0,t.useState)({resizerIsActive:!1,isResizing:!1,isMoving:!1,isSelecting:!1,waitingForMove:!1,activeElement:0,draggerLinePosition:0,draggerShadowPosition:0,draggerShadowThickness:0,delta:0,base:0,position:`before`});dragNDropGrid=QP(this.env);setup(){this.composerFocusStore=O(Er)}_computeHandleDisplay(e){let t=this._getEvOffset(e),n=this._getElementIndex(t);if(n<0)return;let r=this._getDimensionsInViewport(n);t-r.start<this.PADDING&&n!==this._getViewportOffset()?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=r.start,this.state.activeElement=this._getPreviousVisibleElement(n)):r.end-t<this.PADDING?(this.state.resizerIsActive=!0,this.state.draggerLinePosition=r.end,this.state.activeElement=n):this.state.resizerIsActive=!1}_computeGrabDisplay(e){if(Tm(e.ev)){this.state.waitingForMove=!1;return}let t=this._getElementIndex(this._getEvOffset(e)),n=this._getActiveElements(),r=this._getSelectedZoneStart(),i=this._getSelectedZoneEnd();if(n.has(r)&&r<=t&&t<=i){this.state.waitingForMove=!0;return}this.state.waitingForMove=!1}onMouseMove(e){if(this.env.isMobile()||this.env.model.getters.isReadonly()||this.state.isResizing||this.state.isMoving||this.state.isSelecting)return;let t=Pm(this.env,e);this._computeHandleDisplay(t),this._computeGrabDisplay(t)}onMouseLeave(){this.state.resizerIsActive=this.state.isResizing,this.state.waitingForMove=!1}onDblClick(e){let t=Pm(this.env,e);this._fitElementSize(this.state.activeElement),this.state.isResizing=!1,this._computeHandleDisplay(t),this._computeGrabDisplay(t)}onMouseDown(e){if(e.button!==0)return;this.state.isResizing=!0,this.state.delta=0;let t=Pm(this.env,e),n=this._getClientPosition(t),r=this.state.draggerLinePosition,i=this._getElementSize(this.state.activeElement),a=r-i+this.MIN_ELEMENT_SIZE,o=this._getMaxSize();bT(e=>{this.state.delta=this._getClientPosition(Pm(this.env,e))-n,this.state.draggerLinePosition=r+this.state.delta,this.state.draggerLinePosition<a&&(this.state.draggerLinePosition=a,this.state.delta=this.MIN_ELEMENT_SIZE-i),this.state.draggerLinePosition>o&&(this.state.draggerLinePosition=o,this.state.delta=o-r)},e=>{this.state.isResizing=!1,this.state.delta!==0&&this._updateSize()})}onClick(e){if(!this.env.isMobile()||e.button>0)return;let t=Pm(this.env,e),n=this._getElementIndex(this._getEvOffset(t));this._selectElement(n,!1)}select(e){if(this.env.isMobile()||e.button>0)return;let t=Pm(this.env,e),n=this._getElementIndex(this._getEvOffset(t));if(!(n<0)){if(this.env.model.getters.isReadonly()){this._selectElement(n,!1);return}if(!Tm(e)&&this.state.waitingForMove){this.env.model.getters.isGridSelectionActive()?this.startMovement(e):this._selectElement(n,!1);return}this.composerFocusStore.activeComposer.editionMode===`editing`&&this.env.model.selection.getBackToDefault(),this.startSelection(e,n)}}startMovement(e){this.state.waitingForMove=!1,this.state.isMoving=!0;let t=Pm(this.env,e),n=this._getDimensionsInViewport(this._getSelectedZoneStart()),r=this._getDimensionsInViewport(this._getSelectedZoneEnd()),i=n.start;this.state.draggerLinePosition=i,this.state.base=this._getSelectedZoneStart(),this.state.draggerShadowPosition=i,this.state.draggerShadowThickness=r.end-n.start,this.dragNDropGrid.start(t,(e,t)=>{let r=this._getType()===`COL`?e:t;if(r>=0){let e=this._getDimensionsInViewport(r);r<=this._getSelectedZoneStart()?(this.state.draggerLinePosition=e.start,this.state.draggerShadowPosition=e.start,this.state.base=r,this.state.position=`before`):this._getSelectedZoneEnd()<r?(this.state.draggerLinePosition=e.end,this.state.draggerShadowPosition=e.end-this.state.draggerShadowThickness,this.state.base=r,this.state.position=`after`):(this.state.draggerLinePosition=n.start,this.state.draggerShadowPosition=n.start,this.state.base=this._getSelectedZoneStart())}},()=>{this.state.isMoving=!1,this.state.base!==this._getSelectedZoneStart()&&this._moveElements();let t=Pm(this.env,e);this._computeGrabDisplay(t)})}startSelection(e,t){if(this.env.isMobile())return;this.state.isSelecting=!0,e.shiftKey?this._increaseSelection(t):this._selectElement(t,Tm(e)),this.lastSelectedElementIndex=t;let n=Pm(this.env,e);this.dragNDropGrid.start(n,(e,t)=>{let n=this._getType()===`COL`?e:t;n!==this.lastSelectedElementIndex&&n!==-1&&(this._increaseSelection(n),this.lastSelectedElementIndex=n)},()=>{this.env.model.selection.commitSelection(),this.state.isSelecting=!1,this.lastSelectedElementIndex=null,this._computeGrabDisplay(n)})}onContextMenu(e){e.preventDefault();let t=this._getElementIndex(this._getEvOffset(Pm(this.env,e)));if(t<0)return;this._getActiveElements().has(t)||this._selectElement(t,!1);let n=this._getType();this.props.onOpenContextMenu(n,e.clientX,e.clientY)}},XF=class extends YF{static props={onOpenContextMenu:Function};static template=`o-spreadsheet-ColResizer`;static components={UnhideColumnHeaders:JF};colResizerRef;setup(){super.setup(),this.colResizerRef=(0,t.useRef)(`colResizer`),this.PADDING=15,this.MAX_SIZE_MARGIN=90,this.MIN_ELEMENT_SIZE=5}get sheetId(){return this.env.model.getters.getActiveSheetId()}_getEvOffset(e){return e.offsetX}_getViewportOffset(){return this.env.model.getters.getActiveMainViewport().left}_getClientPosition(e){return e.clientX}_getElementIndex(e){return this.env.model.getters.getColIndex(e)}_getSelectedZoneStart(){return this.env.model.getters.getSelectedZone().left}_getSelectedZoneEnd(){return this.env.model.getters.getSelectedZone().right}_getEdgeScroll(e){return this.env.model.getters.getEdgeScrollCol(e,e,e)}_getDimensionsInViewport(e){return this.env.model.getters.getColDimensionsInViewport(this.sheetId,e)}_getElementSize(e){return this.env.model.getters.getColSize(this.sheetId,e)}_getMaxSize(){return this.colResizerRef.el.clientWidth}_updateSize(){let e=this.state.activeElement,t=this.state.delta+this._getElementSize(e),n=this.env.model.getters.getActiveCols();this.env.model.dispatch(`RESIZE_COLUMNS_ROWS`,{dimension:`COL`,sheetId:this.sheetId,elements:n.has(e)?[...n]:[e],size:t})}_moveElements(){let e=[],t=this._getSelectedZoneStart(),n=this._getSelectedZoneEnd();for(let r=t;r<=n;r++)e.push(r);let r=this.env.model.dispatch(`MOVE_COLUMNS_ROWS`,{sheetId:this.sheetId,sheetName:this.env.model.getters.getActiveSheetName(),dimension:`COL`,base:this.state.base,elements:e,position:this.state.position});!r.isSuccessful&&r.reasons.includes(`WillRemoveExistingMerge`)&&this.env.raiseError(Iy)}_selectElement(e,t){this.env.model.selection.selectColumn(e,t?`newAnchor`:`overrideSelection`)}_increaseSelection(e){this.env.model.selection.selectColumn(e,`updateAnchor`)}_fitElementSize(e){let t=this.env.model.getters.getActiveCols();this.env.model.dispatch(`AUTORESIZE_COLUMNS`,{sheetId:this.sheetId,cols:t.has(e)?[...t]:[e]})}_getType(){return`COL`}_getActiveElements(){return this.env.model.getters.getActiveCols()}_getPreviousVisibleElement(e){let t=this.sheetId,n;for(n=e-1;n>=0&&this.env.model.getters.isColHidden(t,n);n--);return n}unhide(e){this.env.model.dispatch(`UNHIDE_COLUMNS_ROWS`,{sheetId:this.sheetId,elements:e,dimension:`COL`})}get mainUnhideHeadersProps(){let{left:e,right:t}=this.env.model.getters.getActiveMainViewport(),{xSplit:n}=this.env.model.getters.getPaneDivisions(this.sheetId),r=this.env.model.getters.getHiddenColsGroups(this.sheetId),i=r.findIndex(e=>e[0]>=n-1);return{headersGroups:i===-1?[]:r.slice(i),offset:this.env.model.getters.getMainViewportCoordinates().x,headerRange:{start:e,end:t}}}get frozenUnhideHeadersProps(){let{xSplit:e}=this.env.model.getters.getPaneDivisions(this.sheetId),t=this.env.model.getters.getHiddenColsGroups(this.sheetId),n=t.findIndex(t=>t[0]>=e-1);return{headersGroups:n===-1?t:t.slice(0,n+1),headerRange:{start:0,end:e-1}}}get frozenContainerStyle(){return W({width:this.env.model.getters.getMainViewportCoordinates().x+`px`})}get hasFrozenPane(){return this.env.model.getters.getPaneDivisions(this.sheetId).xSplit>0}},ZF=class extends YF{static props={onOpenContextMenu:Function};static template=`o-spreadsheet-RowResizer`;static components={UnhideRowHeaders:qF};setup(){super.setup(),this.rowResizerRef=(0,t.useRef)(`rowResizer`),this.PADDING=5,this.MAX_SIZE_MARGIN=60,this.MIN_ELEMENT_SIZE=10}rowResizerRef;get sheetId(){return this.env.model.getters.getActiveSheetId()}_getEvOffset(e){return e.offsetY}_getViewportOffset(){return this.env.model.getters.getActiveMainViewport().top}_getClientPosition(e){return e.clientY}_getElementIndex(e){return this.env.model.getters.getRowIndex(e)}_getSelectedZoneStart(){return this.env.model.getters.getSelectedZone().top}_getSelectedZoneEnd(){return this.env.model.getters.getSelectedZone().bottom}_getEdgeScroll(e){return this.env.model.getters.getEdgeScrollRow(e,e,e)}_getDimensionsInViewport(e){return this.env.model.getters.getRowDimensionsInViewport(this.sheetId,e)}_getElementSize(e){return this.env.model.getters.getRowSize(this.sheetId,e)}_getMaxSize(){return this.rowResizerRef.el.clientHeight}_updateSize(){let e=this.state.activeElement,t=this.state.delta+this._getElementSize(e),n=this.env.model.getters.getActiveRows();this.env.model.dispatch(`RESIZE_COLUMNS_ROWS`,{dimension:`ROW`,sheetId:this.sheetId,elements:n.has(e)?[...n]:[e],size:t})}_moveElements(){let e=[],t=this._getSelectedZoneStart(),n=this._getSelectedZoneEnd();for(let r=t;r<=n;r++)e.push(r);let r=this.env.model.dispatch(`MOVE_COLUMNS_ROWS`,{sheetId:this.sheetId,sheetName:this.env.model.getters.getActiveSheetName(),dimension:`ROW`,base:this.state.base,elements:e,position:this.state.position});r.isSuccessful||(r.reasons.includes(`WillRemoveExistingMerge`)?this.env.raiseError(Iy):r.reasons.includes(`CannotMoveTableHeader`)&&this.env.raiseError(Ly))}_selectElement(e,t){this.env.model.selection.selectRow(e,t?`newAnchor`:`overrideSelection`)}_increaseSelection(e){this.env.model.selection.selectRow(e,`updateAnchor`)}_fitElementSize(e){let t=this.env.model.getters.getActiveRows();this.env.model.dispatch(`AUTORESIZE_ROWS`,{sheetId:this.sheetId,rows:t.has(e)?[...t]:[e]})}_getType(){return`ROW`}_getActiveElements(){return this.env.model.getters.getActiveRows()}_getPreviousVisibleElement(e){let t=this.sheetId,n;for(n=e-1;n>=0&&this.env.model.getters.isRowHidden(t,n);n--);return n}get mainUnhideHeadersProps(){let{top:e,bottom:t}=this.env.model.getters.getActiveMainViewport(),{ySplit:n}=this.env.model.getters.getPaneDivisions(this.sheetId),r=this.env.model.getters.getHiddenRowsGroups(this.sheetId),i=r.findIndex(e=>e[0]>=n-1);return{headersGroups:i===-1?[]:r.slice(i),offset:this.env.model.getters.getMainViewportCoordinates().y,headerRange:{start:e,end:t}}}get frozenUnhideHeadersProps(){let{ySplit:e}=this.env.model.getters.getPaneDivisions(this.sheetId),t=this.env.model.getters.getHiddenRowsGroups(this.sheetId),n=t.findIndex(t=>t[0]>=e-1);return{headersGroups:n===-1?t:t.slice(0,n+1),headerRange:{start:0,end:e-1}}}get frozenContainerStyle(){return W({height:this.env.model.getters.getMainViewportCoordinates().y+`px`})}get hasFrozenPane(){return this.env.model.getters.getPaneDivisions(this.sheetId).ySplit>0}},QF=class extends t.Component{static props={onOpenContextMenu:Function};static template=`o-spreadsheet-HeadersOverlay`;static components={ColResizer:XF,RowResizer:ZF};selectAll(){this.env.model.selection.selectAll()}},$F=class extends pr{renderer;fingerprints;hoveredTables;hoveredIcon;lastRenderSheetId=void 0;lastRenderBoxes=new Map;preventNewAnimationsInNextFrame=!1;zonesWithPreventedAnimationsInNextFrame={};animations=new Map;getters;constructor(e,t=e(Cr)){super(e),this.renderer=t;let n=e(yr);this.getters=n.getters,this.fingerprints=e(nN),this.hoveredTables=e(HF),this.hoveredIcon=e(UF),n.on(`command-dispatched`,this,this.handle),n.on(`command-finalized`,this,this.finalize),this.renderer.register(this),this.onDispose(()=>{n.off(`command-dispatched`,this),n.off(`command-finalized`,this),this.renderer.unRegister(this)})}handle(e){switch(e.type){case`START`:case`ACTIVATE_SHEET`:case`ADD_COLUMNS_ROWS`:case`REMOVE_COLUMNS_ROWS`:this.animations.clear(),this.preventNewAnimationsInNextFrame=!0;break;case`RESIZE_COLUMNS_ROWS`:this.preventNewAnimationsInNextFrame=!0;break;case`REDO`:this.zonesWithPreventedAnimationsInNextFrame={};break;case`UNDO`:for(let t of e.commands)if(t.type===`ADD_COLUMNS_ROWS`||t.type===`REMOVE_COLUMNS_ROWS`||t.type===`RESIZE_COLUMNS_ROWS`){this.animations.clear(),this.preventNewAnimationsInNextFrame=!0;break}break;case`PASTE`:this.preventNewAnimationsInNextFrame=!0;break;case`UPDATE_CELL`:let t=this.getters.getCommandZones(e);this.zonesWithPreventedAnimationsInNextFrame[e.sheetId]||(this.zonesWithPreventedAnimationsInNextFrame[e.sheetId]=[]),this.zonesWithPreventedAnimationsInNextFrame[e.sheetId].push(...t);break}}finalize(){for(let e in this.zonesWithPreventedAnimationsInNextFrame)this.zonesWithPreventedAnimationsInNextFrame[e]=cn(this.zonesWithPreventedAnimationsInNextFrame[e])}get renderingLayers(){return[`Background`,`Headers`]}drawLayer(e,t,n){switch(t){case`Background`:this.drawGlobalBackground(e);let t=e.sheetId===this.lastRenderSheetId?this.lastRenderBoxes:new Map;this.lastRenderSheetId=e.sheetId,this.lastRenderBoxes=new Map;let{sheetId:r,viewports:i}=e;for(let{zone:a,rect:o}of i.getAllSheetViewportsZonesAndRect(r)){let{ctx:s}=e;s.save(),s.beginPath(),s.rect(o.x,o.y,o.width,o.height),s.clip();let c=this.getGridBoxes(i,r,a),l=this.getBoxesWithAnimations(c,t,n);this.drawBackground(e,l),this.drawOverflowingCellBackground(e,l),this.drawCellBackground(e,l),this.drawBorders(e,l),this.drawTexts(e,l),this.drawIcon(e,l),s.restore()}this.drawFrozenPanes(e),this.preventNewAnimationsInNextFrame=!1,this.zonesWithPreventedAnimationsInNextFrame={};break;case`Headers`:this.drawHeaders(e),this.drawFrozenPanesHeaders(e);break}}drawGlobalBackground(e){let{ctx:t,viewports:n}=e,{width:r,height:i}=n.getSheetViewDimensionWithHeaders();t.fillStyle=`#ffffff`,t.fillRect(0,0,r+b,i+b)}drawBackground(e,t){let{ctx:n,thinLineWidth:r}=e,i=!e.hideGridLines&&this.getters.getGridLinesVisibility(e.sheetId),a=i?.1*r:0;if(i)for(let e of t)e.style.hideGridLines||(n.strokeStyle=`#E2E3E3`,n.lineWidth=r,n.strokeRect(e.x+a,e.y+a,e.width-2*a,e.height-2*a))}drawCellBackground(e,t){let{ctx:n}=e;for(let e of t){let t=e.style;if(t.fillColor&&t.fillColor!==`#ffffff`&&(n.fillStyle=t.fillColor||`#ffffff`,n.fillRect(e.x-b,e.y-b,e.width+b*2,e.height+b*2)),e.dataBarFill){n.fillStyle=e.dataBarFill.color;let t=e.dataBarFill.percentage,r=e.width*(t/100);n.fillRect(e.x,e.y,r,e.height)}if(e.overlayColor&&(n.fillStyle=Kr(t.fillColor||`#ffffff`,e.overlayColor),n.fillRect(e.x-b,e.y-b,e.width+b*2,e.height+b*2)),e?.chip){n.save(),n.beginPath(),n.rect(e.x,e.y,e.width,e.height),n.clip();let t=e.chip;n.fillStyle=e.overlayColor?Kr(t.color,e.overlayColor):t.color,n.beginPath(),n.roundRect(t.x,t.y,t.width,t.height,10),n.fill(),n.restore()}e.isError&&(n.fillStyle=`red`,n.beginPath(),n.moveTo(e.x+e.width-5,e.y),n.lineTo(e.x+e.width,e.y),n.lineTo(e.x+e.width,e.y+5),n.fill())}}drawOverflowingCellBackground(e,t){let{ctx:n,thinLineWidth:r}=e;for(let e of t)if(e.content&&e.isOverflow){let t=e.content.align||`left`,i,a,o=e.y+r/2,s=e.height-r,c=Math.min(e.clipRect?.width||1/0,e.content.width);t===`left`?(i=e.x+r/2,a=c-2*r):t===`right`?(i=e.x+e.width-r/2,a=-c+2*r):(i=(e.clipRect?.x||e.x+e.width/2-e.content.width/2)+r/2,a=c-2*r),n.fillStyle=`#ffffff`,n.fillRect(i,o,a,s)}}drawBorders(e,t){let{ctx:n}=e;for(let e of t){let t=e.border;if(t){let{x:n,y:i,width:a,height:o}=e;t.left&&r(t.left,n,i,n,i+o),t.top&&r(t.top,n,i,n+a,i),t.right&&r(t.right,n+a,i,n+a,i+o),t.bottom&&r(t.bottom,n,i+o,n+a,i+o)}}function r({color:e,style:t,opacity:r},i,a,o,s){switch(n.globalAlpha=r??1,n.strokeStyle=e,t){case`medium`:n.lineWidth=2,i+=a===s?-.5:.5,o+=a===s?1.5:.5,a+=i===o?-.5:.5,s+=i===o?1.5:.5;break;case`thick`:n.lineWidth=3,a===s&&(i--,o++),i===o&&(a--,s++);break;case`dashed`:n.lineWidth=1,n.setLineDash([1,3]);break;case`dotted`:n.lineWidth=1,a===s&&(i+=.5,o+=.5),i===o&&(a+=.5,s+=.5),n.setLineDash([1,1]);break;default:n.lineWidth=1;break}n.beginPath(),n.moveTo(i,a),n.lineTo(o,s),n.stroke(),n.lineWidth=1,n.setLineDash([]),n.globalAlpha=1}}drawTexts(e,t){let{ctx:n}=e;n.textBaseline=`top`;let r;for(let e of t)if(e.content){n.globalAlpha=e.textOpacity??1;let t=e.content.align||`left`,i=e.chip?0:e.style.rotation,a={...e.style,align:t,rotation:i},o=Ed(a);if(o!==r&&(r=o,n.font=o),n.fillStyle=a.textColor||`#000`,n.textAlign=t,e.clipRect){n.save(),n.beginPath();let{x:t,y:r,width:i,height:a}=e.clipRect;n.rect(t,r,i,a),n.clip()}let s=e.content.x,c=e.content.y;a.rotation&&(n.save(),n.rotate(a.rotation),{x:s,y:c}=Ld(e.content,a));for(let t of e.content.textLines)Fd(n,t,{x:s,y:c},a.underline,a.strikethrough),c+=4+e.content.fontSizePx;a.rotation&&n.restore(),e.clipRect&&n.restore(),n.globalAlpha=1}}drawIcon(e,t){let{ctx:n}=e;for(let e of t)for(let t of Object.values(e.icons)){if(!t)continue;let r=T({id:t.type,position:t.position},this.hoveredIcon.hoveredIcon)&&t.hoverSvg||t.svg;if(!r)continue;n.save(),n.globalAlpha=t.opacity??1,n.beginPath();let i=t.clipRect||e;n.rect(i.x,i.y,i.width,i.height),n.clip();let a=t.size,{x:o,y:s}=this.getters.getCellIconRect(t,e);n.translate(o,s),n.scale(a/r.width,a/r.height);for(let e of r.paths)n.fillStyle=e.fillColor,n.fill(Mb(e.path));n.restore()}}drawHeaders(e){let{ctx:t,thinLineWidth:n,viewports:r,sheetId:i}=e,a=r.getSheetViewVisibleCols(i),o=a[0],s=r.getSheetViewVisibleRows(i),c=s[0],{width:l,height:u}=r.getSheetViewDimensionWithHeaders(),d=e.selectedZones,f=tr(d),p=rr(d),m=this.getters.getNumberCols(i),h=this.getters.getNumberRows(i),g=e.activeCols,_=e.activeRows;t.font=`400 11px ${De}`,t.textAlign=`center`,t.textBaseline=`middle`,t.lineWidth=n,t.strokeStyle=`#333`;for(let e of a){let n={left:e,right:e,top:0,bottom:h-1},{x:a,width:o}=r.getVisibleRect(i,n),s=g.has(e),c=f.has(e);s?t.fillStyle=re:c?t.fillStyle=ne:t.fillStyle=te,t.fillRect(a,0,o,26)}for(let e of s){let n={top:e,bottom:e,left:0,right:m-1},{y:a,height:o}=r.getVisibleRect(i,n),s=_.has(e),c=p.has(e);s?t.fillStyle=re:c?t.fillStyle=ne:t.fillStyle=te,t.fillRect(0,a,48,o)}t.beginPath(),t.moveTo(48,0),t.lineTo(48,u),t.moveTo(0,26),t.lineTo(l,26),t.strokeStyle=`#C0C0C0`,t.stroke();for(let e of a){let n=Zt(e);t.fillStyle=g.has(e)?`#fff`:ie;let a={left:e,right:e,top:c,bottom:c},{x:o,width:s}=r.getRect(i,a),{x:l,width:u}=r.getVisibleRect(i,a);t.save(),t.beginPath(),t.rect(l,0,u,26),t.clip(),t.fillText(n,o+s/2,26/2),t.restore(),t.beginPath(),t.moveTo(o+s,0),t.lineTo(o+s,26),t.stroke()}for(let e of s){t.fillStyle=_.has(e)?`#fff`:ie;let n={top:e,bottom:e,left:o,right:o},{y:a,height:s}=r.getRect(i,n),{y:c,height:l}=r.getVisibleRect(i,n);t.save(),t.beginPath(),t.rect(0,c,48,l),t.clip(),t.fillText(String(e+1),48/2,a+s/2),t.restore(),t.beginPath(),t.moveTo(0,a+s),t.lineTo(48,a+s),t.stroke()}}drawFrozenPanesHeaders(e){let{ctx:t,thinLineWidth:n,sheetId:r,viewports:i}=e,{x:a,y:o}=i.getMainViewportCoordinates(r),s=i.getGridOffsetX(),c=i.getGridOffsetY();t.lineWidth=6*n,t.strokeStyle=`#BCBCBC`,t.beginPath(),a&&(t.moveTo(s+a,0),t.lineTo(s+a,c)),o&&(t.moveTo(0,c+o),t.lineTo(s,c+o)),t.stroke()}drawFrozenPanes(e){let{ctx:t,thinLineWidth:n,sheetId:r,viewports:i}=e,{x:a,y:o}=i.getMainViewportCoordinates(r),s=i.getSheetViewVisibleCols(r),c=s[0],l=s[s.length-1],u=i.getSheetViewVisibleRows(r),d={left:c,right:l,top:u[0],bottom:u[u.length-1]},f=e.viewports.getVisibleRect(e.sheetId,d),p=i.getGridOffsetX(),m=i.getGridOffsetY();t.lineWidth=6*n,t.strokeStyle=`#DADFE8`,t.beginPath(),a&&(t.moveTo(p+a,m),t.lineTo(p+a,f.height+m)),o&&(t.moveTo(p,m+o),t.lineTo(f.width+p,m+o)),t.stroke()}findNextEmptyCol(e,t,n,r){let i=t;for(;i<n;){let t={sheetId:e,col:i+1,row:r},n=this.getters.getEvaluatedCell(t),a=this.getters.getCellComputedBorder(t),o=this.getters.doesCellHaveGridIcon(t);if(n.type!==`empty`||this.getters.isInMerge(t)||a?.left||o)return i;i++}return i}findPreviousEmptyCol(e,t,n,r){let i=t;for(;i>n;){let t={sheetId:e,col:i-1,row:r},n=this.getters.getEvaluatedCell(t),a=this.getters.getCellComputedBorder(t),o=this.getters.doesCellHaveGridIcon(t);if(n.type!==`empty`||this.getters.isInMerge(t)||a?.right||o)return i;i--}return i}computeCellAlignment(e,t){if(this.getters.getCell(e)?.isFormula&&this.getters.shouldShowFormulas())return`left`;let{align:n}=this.getters.getCellStyle(e),r=this.getters.getEvaluatedCell(e);return!n&&au(r.value,r.format)?`left`:t&&r.type===`number`?n===`center`?n:`left`:n||r.defaultAlign}createZoneBox(e,t,n,r){let{left:i,right:a}=r,o=n.left,s=n.top,c={sheetId:t,col:o,row:s},l=this.getters.getEvaluatedCell(c),u=this.getters.shouldShowFormulas(),{x:d,y:f,width:p,height:m}=e.getRect(t,n),h=this.getters.getDataValidationChipStyle(c),g=this.getters.getCellComputedStyle(c);if(this.fingerprints.isEnabled){let e=this.fingerprints.colors.get(c);g={...g,fillColor:e}}h?.textColor&&(g={...g,textColor:h.textColor});let _=this.fingerprints.isEnabled?void 0:this.getters.getConditionalDataBar(c),v=this.getters.getCellIcons(c),y={left:v.find(e=>e?.horizontalAlign===`left`),right:v.find(e=>e?.horizontalAlign===`right`),center:v.find(e=>e?.horizontalAlign===`center`)},b={id:wn(n),x:d,y:f,width:p,height:m,border:this.getters.getCellComputedBorder(c)||void 0,style:g,dataBarFill:_,overlayColor:this.hoveredTables.overlayColors.get(c),isError:l.type===`error`&&!!l.message||this.getters.isDataValidationInvalid(c),icons:y,disabledAnimation:this.zonesWithPreventedAnimationsInNextFrame[t]?.some(e=>In(n,e)||Nn(n,e))},ee=Dd(b.style);if(l.type===`empty`||b.icons.center)return b;let te=g.wrapping||`overflow`,ne=te===`wrap`&&!u,re=p-8,ie=g.align?0:re,ae=ne?re:void 0,oe=this.getters.getCellMultiLineText(c,{maxWidth:ie,wrapWidth:ae}),se={...g,align:`left`,rotation:0},ce=Math.max(...oe.map(e=>this.getters.getTextWidth(e,se)))+4,le=this.getters.getMultilineTextSize(oe,g),ue=h?5:0,de=(b.icons.left?b.icons.left.size+b.icons.left.margin:0)+ue,fe=(b.icons.right?b.icons.right.size+b.icons.right.margin:0)+ue,pe=de+le.width+fe+4,me=this.computeCellAlignment(c,pe>p),he=oe.length,ge=Math.round(this.getters.computeTextYCoordinate(b,ee,g.verticalAlign,he)),_e=b.x;me===`left`?_e+=4+de:me===`right`?_e+=b.width-4-fe:_e+=b.width/2,_e=Math.round(_e);let ve=md(ee,he);if(b.content={textLines:oe,width:te===`overflow`?ce:p,textHeight:ve,textWidth:ce,align:me,x:_e,y:ge,fontSizePx:ee},h?.fillColor){let e=de;b.chip={color:h.fillColor,width:b.width-e-5,height:ve+2,x:b.x+e,y:ge-2}}let ye=pe>p||le.height>m;if(b.icons.left||b.icons.right||b.chip)b.clipRect={x:b.x+de,y:b.y,width:Math.max(0,p-de-fe),height:m};else if(ye&&te===`overflow`){let r,l;switch(this.getters.isInMerge(c)?(r=this.getters.getMerge(c).right,l=o):(r=b.border?.right?n.right:this.findNextEmptyCol(t,o,a,s),l=b.border?.left?n.left:this.findPreviousEmptyCol(t,o,i,s),b.isOverflow=!0),me){case`left`:{let i=D({col:r,row:s}),{x:a,y:o,width:c,height:l}=e.getVisibleRect(t,kn(n,i));(c<pe||ee>l||oe.length>1)&&(b.clipRect={x:a,y:o,width:c,height:l});break}case`right`:{let r=D({col:l,row:s}),{x:i,y:a,width:o,height:c}=e.getVisibleRect(t,kn(n,r));(o<pe||ee>c||oe.length>1)&&(b.clipRect={x:i,y:a,width:o,height:c});break}case`center`:{let i={...n,left:l,right:r},{x:a,y:o,height:s,width:c}=e.getVisibleRect(t,i),u=pe/2,d=b.x+b.width/2;if(a+c<d+u||a>d-u||ee>s||oe.length>1){let e=a>d-u?a:d-u;b.clipRect={x:e,y:o,width:a+c-e,height:s}}break}}}else(te===`clip`||te===`wrap`||oe.length>1)&&(b.clipRect={x:b.x,y:b.y,width:p,height:m});return b}getGridBoxes(e,t,n){let r=[],i=e.getSheetViewVisibleCols(t).filter(e=>e>=n.left&&e<=n.right),a=i[0],o=i[i.length-1],s=e.getSheetViewVisibleRows(t).filter(e=>e>=n.top&&e<=n.bottom),c={left:a,right:o,top:s[0],bottom:s[s.length-1]};for(let n of s)for(let a of i){let i={sheetId:t,col:a,row:n};this.getters.isInMerge(i)||r.push(this.createZoneBox(e,t,D(i),c))}for(let n of this.getters.getMerges(t))if(!this.getters.isMergeHidden(t,n)&&Nn(n,c)){let i=this.createZoneBox(e,t,n,c),a=this.getters.getCellComputedBorder({sheetId:t,col:n.right,row:n.bottom});i.border={...i.border,bottom:a?a.bottom:void 0,right:a?a.right:void 0},i.isMerge=!0,r.push(i)}return r}getBoxesWithAnimations(e,t,n){return this.updateAnimationsProgress(n),this.addNewAnimations(e,t,n),this.animations.size>0?(this.renderer.startAnimation(`grid_renderer_animation`),this.updateBoxesWithAnimations(e)):(this.renderer.stopAnimation(`grid_renderer_animation`),e)}updateBoxesWithAnimations(e){let t=[];for(let n of e){let e=this.animations.get(n.id);if(!e){t.push(n);continue}let r=x(n);t.push(r);for(let i of e.animationTypes){let a=ey.get(i).updateAnimation(e.progress,r,e.oldBox,n);a&&t.push(...a.newBoxes)}}return t}updateAnimationsProgress(e){if(e!==void 0)for(let t of this.animations.keys()){let n=this.animations.get(t);if(n.startTime===void 0){n.startTime=e;continue}let r=e-n.startTime,i=Math.min(1,r/200);i>=1&&this.animations.delete(t),n.progress=i}}addNewAnimations(e,t,n){for(let r of e){this.lastRenderBoxes.set(r.id,r);let e=t.get(r.id);if(this.preventNewAnimationsInNextFrame||!e||r.disabledAnimation)continue;let i=[];for(let t of ey.getAll())t.hasAnimation(e,r)&&i.push(t.id);let a=i.length>0?{animationTypes:i,oldBox:e,progress:0,startTime:n}:void 0;a&&this.animations.set(r.id,a)}}};function eI({refName:e,renderingCtx:n,rendererStore:r,changeCanvasSizeOnZoom:i}){let a=(0,t.useRef)(e);(0,t.useEffect)(s);let o=r||O(Cr);hr($F,o);function s(){let e=a.el,t=e.getContext(`2d`,{alpha:!1}),r={ctx:t,thinLineWidth:.4,...n()},s=r.dpr,c=r.viewports.getZoomLevel();i||(c=Math.max(c,1));let{width:l,height:u}=r.viewports.getSheetViewDimensionWithHeaders();e.width=l*s*c,e.height=u*s*c;let d=W({width:i?`${l*c}px`:`${l}px`,height:i?`${u*c}px`:`${u}px`});e.setAttribute(`style`,d),!(l===0||u===0)&&(t.translate(-.5,-.5),t.scale(s*c,s*c),o.draw(r))}}let tI=.95;function nI(e,{updateScroll:n,canMoveUp:r,canMoveDown:i,getZoom:a,setZoom:o}){let s=0,c=0,l=0,u=0,d=!1,f=0,p=null,m=!1,h=[],g=-1;ck(e,`touchstart`,_,{capture:!1}),ck(e,`touchmove`,v,{capture:!1}),ck(e,`touchend`,y,{capture:!1}),ck(e,`pointerdown`,ee,{passive:!1,capture:!1}),ck(e,`pointermove`,ne,{passive:!1,capture:!1}),(0,t.useExternalListener)(window,`pointerup`,te,{passive:!1,capture:!0}),ck(e,`pointercancel`,te,{passive:!1});function _(e){d=!0,{clientX:s,clientY:c}=e.touches[0],l=0,u=0}function v(e){if(!d||m){e.cancelable&&e.preventDefault(),e.stopPropagation();return}p&&=(clearTimeout(p),null);let t=Date.now(),{clientX:a,clientY:o}=e.touches[0],h=s-a,g=c-o,_=t-f;_&&(l=h/_,u=g/_,s=a,c=o,f=t,(g<0&&r()||g>0&&i())&&(e.cancelable&&e.preventDefault(),e.stopPropagation()),p=setTimeout(()=>{l=0,u=0},100),n(h*1,g*1))}function y(e){d=!1,s=c=0,p&&clearTimeout(p),l*=1.2,u*=1.2,requestAnimationFrame(b)}function b(){if(Math.abs(l)<.05&&(l=0),Math.abs(u)<.05&&(u=0),!l&&!u)return;let e=Date.now(),t=Math.abs(e-f),r=l*t,i=u*t;n(r*1,i*1),f=e,l*=tI,u*=tI,requestAnimationFrame(b)}function ee(e){e.button===0&&h.findIndex(t=>t.pointerId===e.pointerId)===-1&&(h.push(e),h.length<2?g=-1/0:h.length===2&&(g=rI(h[0],h[1])))}function te(e){let t=h.findIndex(t=>t.pointerId===e.pointerId);t!==-1&&(h.splice(t,1),h.length<2&&(g=-1/0,m=!1))}function ne(e){let t=h.findIndex(t=>t.pointerId===e.pointerId);if(t!==-1&&(h[t]=e,h.length===2)){let e=rI(h[0],h[1]);if(!m&&Math.abs(e-g)>=30&&(m=!0,g=e),m){let t=(e/g)**.5;o(Math.round(a()*t*1e3)/1e3),g=e}}}}function rI(e,t){let n=e.clientX-t.clientX,r=e.clientY-t.clientY;return Math.sqrt(n*n+r*r)}function iI(e){function t(e,t){return e*(t===0?1:23)}return n=>{e(t(n.shiftKey&&!wm()?n.deltaY:n.deltaX,n.deltaMode),t(n.shiftKey&&!wm()?n.deltaX:n.deltaY,n.deltaMode))}}var aI=class extends t.Component{static template=`o-spreadsheet-Border`;static props={zone:Object,orientation:String,isMoving:Boolean,onMoveHighlight:Function};get style(){let e=[`n`,`w`,`e`].includes(this.props.orientation),t=[`n`,`w`,`s`].includes(this.props.orientation),n=[`n`,`s`].includes(this.props.orientation),r=[`w`,`e`].includes(this.props.orientation),i=this.props.zone,a=this.env.model.getters.getVisibleRect(i),o=a.x,s=a.x+a.width-4,c=a.y,l=a.y+a.height-4,u=t?o:s,d=e?c:l,f=n?s-o:4,p=r?l-c:4;return W({left:`${u}px`,top:`${d}px`,width:`${f}px`,height:`${p}px`})}onMouseDown(e){this.props.onMoveHighlight(e)}},oI=class extends t.Component{static template=`o-spreadsheet-Corner`;static props={zone:Object,color:String,orientation:String,isResizing:Boolean,onResizeHighlight:Function};dirX;dirY;setup(){let{dirX:e,dirY:t}=sI(this.props.orientation);this.dirX=e,this.dirY=t}get handlerStyle(){let e=this.props.zone,t=this.env.model.getters.getVisibleRect({left:this.dirX===1?e.right:e.left,right:this.dirX===-1?e.left:e.right,top:this.dirY===1?e.bottom:e.top,bottom:this.dirY===-1?e.top:e.bottom});if(t.width*t.height===0)return`display: none !important;`;let n=t.x+t.width/2+this.dirX*t.width/2,r=t.y+t.height/2+this.dirY*t.height/2,i=this.getHandlerEdgeLength(),a={left:`${n-i/2}px`,top:`${r-i/2}px`,height:`${i}px`,width:`${i}px`};return this.env.isMobile()&&(a[`border-radius`]=`${i/2}px`),W(a)}getHandlerEdgeLength(){return this.env.isMobile()?40:8}get buttonLook(){let e={"background-color":this.props.color,cursor:`${this.props.orientation}-resize`};return this.env.isMobile()&&(e[`border-radius`]=`${8/2}px`),W(e)}onMouseDown(e){this.props.onResizeHighlight(e,this.dirX,this.dirY)}};function sI(e){return{dirX:e.includes(`w`)?-1:+!!e.includes(`e`),dirY:e.includes(`n`)?-1:+!!e.includes(`s`)}}var cI=class extends t.Component{static template=`o-spreadsheet-Highlight`;static props={range:Object,color:String};static components={Corner:oI,Border:aI};highlightState=(0,t.useState)({shiftingMode:`none`});dragNDropGrid=QP(this.env);get cornerOrientations(){if(!this.env.isMobile())return[`nw`,`ne`,`sw`,`se`];let e=this.props.range.unboundedZone;return e.bottom===void 0?[`w`,`e`]:e.right===void 0?[`n`,`s`]:[`nw`,`se`]}onResizeHighlight(e,t,n){let r=this.env.model.getters.getActiveSheetId(),i=Pm(this.env,e);this.highlightState.shiftingMode=`isResizing`;let a=this.props.range.zone,o=t===1?a.left:a.right,s=n===1?a.top:a.bottom,c=t===1?a.right:a.left,l=n===1?a.bottom:a.top,u=a,d=`all`;this.env.isMobile()&&(d=t===0?`vertical`:n===0?`horizontal`:`all`),this.env.model.dispatch(`START_CHANGE_HIGHLIGHT`,{zone:u}),this.dragNDropGrid.start(i,(e,t)=>{if(c!==e||l!==t){let{left:n,right:i,top:a,bottom:f}=u;d!==`horizontal`&&(l=l=S(t===-1?l:t,0,this.env.model.getters.getNumberRows(r)-1),a=Math.min(s,l),f=Math.max(s,l)),d!==`vertical`&&(c=S(e===-1?c:e,0,this.env.model.getters.getNumberCols(r)-1),n=Math.min(o,c),i=Math.max(o,c));let p={left:n,right:i,top:a,bottom:f};Mn(p,u)||(this.env.model.selection.selectZone({cell:{col:p.left,row:p.top},zone:p},{unbounded:!0}),u=p)}},()=>{this.highlightState.shiftingMode=`none`},d)}onMoveHighlight(e){this.highlightState.shiftingMode=`isMoving`;let t=this.props.range.zone,n=pm(this.env.model.getters.getViewportZoomLevel()),r=Pm(this.env,e,n),i=this.env.model.getters.getActiveSheetId(),a=this.env.model.getters.getColIndex(r.clientX-n.x),o=this.env.model.getters.getRowIndex(r.clientY-n.y),s=-t.left,c=this.env.model.getters.getNumberCols(i)-t.right-1,l=-t.top,u=this.env.model.getters.getNumberRows(i)-t.bottom-1,d=t;this.env.model.dispatch(`START_CHANGE_HIGHLIGHT`,{zone:d});let f=a,p=o;this.dragNDropGrid.start(r,(e,n)=>{if(f!==e||p!==n){f=e===-1?f:e,p=n===-1?p:n;let r=S(f-a,s,c),i=S(p-o,l,u),m={left:t.left+r,top:t.top+i,right:t.right+r,bottom:t.bottom+i};Mn(m,d)||(this.env.model.selection.selectZone({cell:{col:m.left,row:m.top},zone:m},{unbounded:!0}),d=m)}},()=>{this.highlightState.shiftingMode=`none`})}},lI=class{direction;el;constructor(e,t){this.el=e,this.direction=t}get scroll(){return this.direction===`horizontal`?this.el.scrollLeft:this.el.scrollTop}set scroll(e){this.direction===`horizontal`?this.el.scrollLeft=e:this.el.scrollTop=e}},uI=class extends t.Component{static props={width:{type:Number,optional:!0},height:{type:Number,optional:!0},direction:String,position:Object,offset:Number,onScroll:Function};static template=t.xml`
91
91
  <div
92
92
  t-attf-class="o-scrollbar {{props.direction}}"
@@ -111,10 +111,10 @@ stores.inject(MyMetaStore, storeInstance);
111
111
  offset="offset"
112
112
  direction="'vertical'"
113
113
  onScroll.bind="onScroll"
114
- />`;static defaultProps={topOffset:0};get offset(){return this.env.model.getters.getActiveSheetScrollInfo().scrollY}get height(){return this.env.model.getters.getMainViewportRect().height}get isDisplayed(){let{yRatio:e}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());return e<1}get position(){let{y:e}=this.env.model.getters.getMainViewportRect(),t=this.env.model.getters.getScrollBarWidth();return{top:`${this.props.topOffset+e}px`,right:`0px`,width:`${t}px`,bottom:Om()?`${t}px`:`0`}}onScroll(e){let{scrollX:t}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:t,offsetY:e})}},pI=class extends t.Component{static template=`o-spreadsheet-Selection`;static props={};static components={Highlight:cI};get highlightProps(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getUnboundedZone(e,this.env.model.getters.getSelectedZone());return{range:this.env.model.getters.getRangeFromZone(e,t),color:ae}}},mI=class extends t.Component{static template=`o-spreadsheet-TableResizer`;static props={table:Object};state=(0,t.useState)({highlightZone:void 0});dragNDropGrid=QP(this.env);setup(){dk(this)}get containerStyle(){let e=this.props.table.range.zone,t=this.props.table.range.sheetId;if(this.env.model.getters.isReadonly()||this.env.model.getters.isSheetLocked(t))return W({display:`none`});let n={...e,left:e.right,top:e.bottom},r=this.env.model.getters.getVisibleRect(n);return r.height===0||r.width===0?W({display:`none`}):W({top:`${r.y+r.height-6}px`,left:`${r.x+r.width-6}px`})}onMouseDown(e){let t=this.props.table.range.zone,n={col:t.left,row:t.top};document.body.style.cursor=`nwse-resize`;let r=Pm(this.env,e);this.dragNDropGrid.start(r,(e,t,r)=>{this.state.highlightZone={left:n.col,top:n.row,right:Math.max(e,n.col),bottom:Math.max(t,n.row)}},()=>{document.body.style.cursor=``;let e=this.state.highlightZone;if(!e)return;let t=this.props.table.range.sheetId;this.env.model.dispatch(`RESIZE_TABLE`,{sheetId:t,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeDataFromZone(t,e)}),this.state.highlightZone=void 0})}get highlights(){return this.state.highlightZone?[{range:this.env.model.getters.getRangeFromZone(this.props.table.range.sheetId,this.state.highlightZone),color:`#777`,noFill:!0}]:[]}};let hI={ROW:YP,COL:HP,CELL:kP,GROUP_HEADERS:qP,UNGROUP_HEADERS:JP};var gI=class extends t.Component{static template=`o-spreadsheet-Grid`;static props={exposeFocus:Function,getGridSize:Function};static components={GridComposer:DF,GridOverlay:GF,GridPopover:KF,HeadersOverlay:QF,MenuPopover:wy,Autofill:eF,ClientTag:nF,Highlight:cI,Popover:by,VerticalScrollBar:fI,HorizontalScrollBar:dI,TableResizer:mI,Selection:pI};HEADER_HEIGHT=26;HEADER_WIDTH=48;menuState;gridRef;highlightStore;cellPopovers;composerFocusStore;DOMFocusableElementStore;paintFormatStore;clientFocusStore;dragNDropGrid=QP(this.env);onMouseWheel;hoveredCell;sidePanel;setup(){this.highlightStore=O(cT),this.menuState=(0,t.useState)({isOpen:!1,anchorRect:null,menuItems:[]}),this.gridRef=(0,t.useRef)(`grid`),this.hoveredCell=O(My),this.composerFocusStore=O(Er),this.DOMFocusableElementStore=O(ly),this.sidePanel=O($M),this.paintFormatStore=O(VF),this.clientFocusStore=O(ZP),O(XP),(0,t.useChildSubEnv)({getPopoverContainerRect:()=>this.getGridRect()}),(0,t.useExternalListener)(document.body,`cut`,this.copy.bind(this,!0)),(0,t.useExternalListener)(document.body,`copy`,this.copy.bind(this,!1)),(0,t.useExternalListener)(document.body,`paste`,this.paste),(0,t.onMounted)(()=>this.focusDefaultElement()),this.props.exposeFocus(()=>this.focusDefaultElement()),eI({refName:`canvas`,renderingCtx:()=>({dpr:window.devicePixelRatio||1,viewports:this.env.model.getters.getViewportCollection(),...this.env.model.getters.getSelectionState()})}),this.onMouseWheel=iI((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=O(vw),(0,t.useEffect)((e,t)=>{!e&&!t&&this.DOMFocusableElementStore.focus()},()=>[this.sidePanel.isMainPanelOpen,this.sidePanel.isSecondaryPanelOpen]),nI(this.gridRef,{updateScroll:this.moveCanvas.bind(this),canMoveUp:()=>{let{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0},canMoveDown:()=>{let{maxOffsetY:e}=this.env.model.getters.getMaximumSheetOffset(),{scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo();return t<e},getZoom:()=>this.env.model.getters.getViewportZoomLevel(),setZoom:e=>this.env.model.dispatch(`SET_ZOOM`,{zoom:e})})}get highlights(){return this.highlightStore.highlights}get gridOverlayDimensions(){let e=this.env.model.getters.getScrollBarWidth();return W({top:`26px`,left:`48px`,height:`calc(100% - ${26+e}px)`,width:`calc(100% - ${48+e}px)`})}onClosePopover(){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.focusDefaultElement()}keyDownMapping={Enter:()=>this.editOrMoveInSelection(`down`),"Shift+Enter":()=>this.editOrMoveInSelection(`up`),Tab:()=>this.moveInSelection(`right`),"Shift+Tab":()=>this.moveInSelection(`left`),F2:()=>{this.focusComposerFromActiveCell()},Delete:()=>{this.env.model.dispatch(`DELETE_UNFILTERED_CONTENT`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Backspace:()=>{this.env.model.dispatch(`DELETE_UNFILTERED_CONTENT`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Escape:()=>{this.cellPopovers.isOpen?this.cellPopovers.close():this.menuState.isOpen?this.closeMenu():this.paintFormatStore.isActive?this.paintFormatStore.cancel():this.env.model.dispatch(`CLEAN_CLIPBOARD_HIGHLIGHT`)},"Ctrl+A":()=>this.env.model.selection.loopSelection(),"Ctrl+Z":()=>this.env.model.dispatch(`REQUEST_UNDO`),"Ctrl+Y":()=>this.env.model.dispatch(`REQUEST_REDO`),F4:()=>this.env.model.dispatch(`REQUEST_REDO`),"Ctrl+B":()=>this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{bold:!this.env.model.getters.getCurrentStyle().bold}}),"Ctrl+I":()=>this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{italic:!this.env.model.getters.getCurrentStyle().italic}}),"Ctrl+U":()=>this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{underline:!this.env.model.getters.getCurrentStyle().underline}}),"Ctrl+O":()=>VE(this.env),"Alt+=":()=>{let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone(),{anchor:n}=this.env.model.getters.getSelection(),r=this.env.model.getters.getAutomaticSums(e,t,n.cell);if(this.env.model.getters.isSingleCellOrMerge(e,t)||this.env.model.getters.isEmpty(e,t)&&r.length<=1){let t=r[0]?.zone?this.env.model.getters.zoneToXC(e,r[0].zone):``,n=`=SUM(${t})`;this.onComposerCellFocused(n,{start:5,end:5+t.length})}else this.env.model.dispatch(`SUM_SELECTION`)},"Alt+Enter":()=>{let e=this.env.model.getters.getActiveCell();e.link&&Fu(e.link,this.env)},"Ctrl+Home":()=>{let e=this.env.model.getters.getActiveSheetId(),{col:t,row:n}=this.env.model.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0});this.env.model.selection.selectCell(t,n)},"Ctrl+End":()=>{let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.findVisibleHeader(e,`COL`,this.env.model.getters.getNumberCols(e)-1,0),n=this.env.model.getters.findVisibleHeader(e,`ROW`,this.env.model.getters.getNumberRows(e)-1,0);this.env.model.selection.selectCell(t,n)},"Shift+ ":()=>{let e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),left:0,right:this.env.model.getters.getNumberCols(e)-1},n=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:n,zone:t})},"Ctrl+ ":()=>{let e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),top:0,bottom:this.env.model.getters.getNumberRows(e)-1},n=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:n,zone:t})},"Ctrl+D":()=>{fw(this.env,{type:`COPY_PASTE_CELLS_ABOVE`})},"Ctrl+R":()=>{fw(this.env,{type:`COPY_PASTE_CELLS_ON_LEFT`})},"Ctrl+Enter":()=>{fw(this.env,{type:`COPY_PASTE_CELLS_ON_ZONE`})},"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":()=>gE(this.env),"Ctrl+Shift+<":()=>this.clearFormatting(),"Ctrl+<":()=>this.clearFormatting(),"Ctrl+Shift+ ":()=>{this.env.model.selection.selectAll()},"Ctrl+Alt+=":()=>{let e=this.env.model.getters.getActiveCols(),t=this.env.model.getters.getActiveRows(),n=this.env.model.getters.getSelectedZones().length===1,r=e.size>0&&n,i=t.size>0&&n;r&&!i?ME(this.env):i&&!r&&AE(this.env)},"Ctrl+Alt+-":()=>{let e=[...this.env.model.getters.getActiveCols()],t=[...this.env.model.getters.getActiveRows()];e.length>0&&t.length===0?this.env.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:this.env.model.getters.getActiveSheetId(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:`COL`,elements:e}):t.length>0&&e.length===0&&this.env.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:this.env.model.getters.getActiveSheetId(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:`ROW`,elements:t})},"Shift+PageDown":()=>{this.env.model.dispatch(`ACTIVATE_NEXT_SHEET`)},"Shift+PageUp":()=>{this.env.model.dispatch(`ACTIVATE_PREVIOUS_SHEET`)},"Shift+F11":()=>{PD.execute?.(this.env)},"Alt+T":()=>{xD.execute?.(this.env)},PageDown:()=>this.env.model.dispatch(`SHIFT_VIEWPORT_DOWN`),PageUp:()=>this.env.model.dispatch(`SHIFT_VIEWPORT_UP`),"Ctrl+K":()=>{this.closeMenu(),WE(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`)};focusComposerFromActiveCell(){this.env.model.getters.getActiveCell().type===`empty`?this.onComposerCellFocused():this.onComposerContentFocused()}editOrMoveInSelection(e){if(this.isSingleCellOrMergeSelection()){this.focusComposerFromActiveCell();return}Fw(this.env.model.getters,this.env.model.selection,e)}moveInSelection(e){if(this.isSingleCellOrMergeSelection()){this.env.model.selection.moveAnchorCell(e,1);return}Fw(this.env.model.getters,this.env.model.selection,e)}isSingleCellOrMergeSelection(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone();return this.env.model.getters.isSingleCellOrMerge(e,t)}focusDefaultElement(){!this.env.model.getters.getSelectedFigureId()&&this.composerFocusStore.activeComposer.editionMode===`inactive`&&this.DOMFocusableElementStore.focus()}get gridEl(){if(!this.gridRef.el)throw Error(`Grid el is not defined.`);return this.gridRef.el}getAutofillPosition(){let e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect(e);return{x:t.x+t.width-8/2,y:t.y+t.height-8/2}}get isAutofillVisible(){if(this.env.model.getters.isCurrentSheetLocked())return!1;let e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect({left:e.right,right:e.right,top:e.bottom,bottom:e.bottom});return!(t.width===0||t.height===0)}onGridResized(){let{height:e,width:t}=this.props.getGridSize();this.env.model.dispatch(`RESIZE_SHEETVIEW`,{width:t-48,height:e-26,gridOffsetX:48,gridOffsetY:26})}moveCanvas(e,t){let{scrollX:n,scrollY:r}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:n+e,offsetY:r+t})}processSpaceKey(e){this.env.model.getters.hasBooleanValidationInZones(this.env.model.getters.getSelectedZones())&&(e.preventDefault(),e.stopPropagation(),this.env.model.dispatch(`TOGGLE_CHECKBOX`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()}))}getClientPositionKey(e){return`${e.id}-${e.position?.sheetId}-${e.position?.col}-${e.position?.row}`}isCellHovered(e,t){return this.hoveredCell.col===e&&this.hoveredCell.row===t}get focusedClients(){return this.clientFocusStore.focusedClients}getGridRect(){let e=this.env.model.getters.getViewportZoomLevel(),{width:t,height:n}=this.env.model.getters.getSheetViewDimensionWithHeaders();return{...hm(this.gridRef),width:t*e,height:n*e}}onCellClicked(e,t,n,r){if(r.ev.preventDefault(),this.composerFocusStore.activeComposer.editionMode===`editing`&&this.composerFocusStore.activeComposer.stopEdition(),n.expandZone?this.env.model.selection.setAnchorCorner(e,t):n.addZone?this.env.model.selection.addCellToSelection(e,t):this.env.model.selection.selectCell(e,t),this.env.isMobile())return;let i=e,a=t;this.dragNDropGrid.start(r,(e,t,n)=>{n.preventDefault(),(e!==i&&e!==-1||t!==a&&t!==-1)&&(i=e===-1?i:e,a=t===-1?a:t,this.env.model.selection.setAnchorCorner(i,a))},()=>{this.env.model.selection.commitSelection(),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())})}onCellDoubleClicked(e,t){let n=this.env.model.getters.getActiveSheetId();({col:e,row:t}=this.env.model.getters.getMainCellPosition({sheetId:n,col:e,row:t})),this.env.model.getters.getEvaluatedCell({sheetId:n,col:e,row:t}).type===`empty`?this.onComposerCellFocused():this.onComposerContentFocused()}processArrows(e){e.preventDefault(),e.stopPropagation(),this.cellPopovers.isOpen&&this.cellPopovers.close(),Pw(e,this.env.model.selection),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())}onKeydown(e){let t=Cm(e),n=this.keyDownMapping[t];if(n){e.preventDefault(),e.stopPropagation(),n();return}if(t===` `){this.processSpaceKey(e);return}if(e.key.startsWith(`Arrow`)){this.processArrows(e);return}}onInputContextMenu(e){e.preventDefault();let t=this.env.model.getters.getSelectedZone(),{left:n,top:r}=t,i=`CELL`;this.composerFocusStore.activeComposer.stopEdition(),this.env.model.getters.getActiveCols().has(n)?i=`COL`:this.env.model.getters.getActiveRows().has(r)&&(i=`ROW`);let{x:a,y:o,width:s}=this.env.model.getters.getVisibleRectWithZoom(t),c=this.getGridRect();this.toggleContextMenu(i,c.x+a+s,c.y+o)}onCellRightClicked(e,t,{x:n,y:r}){let i=this.env.model.getters.getSelectedZones(),a=i[i.length-1],o=`CELL`;Fn(e,t,a)?this.env.model.getters.getActiveCols().has(e)?o=`COL`:this.env.model.getters.getActiveRows().has(t)&&(o=`ROW`):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(o,n,r)}toggleContextMenu(e,t,n){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.menuState.isOpen=!0,this.menuState.anchorRect={x:t,y:n,width:0,height:0},this.menuState.menuItems=hI[e].getMenuItems()}async copy(e,t){if(!this.gridEl.contains(document.activeElement)||this.composerFocusStore.activeComposer.editionMode!==`inactive`)return;e?NN(this.env):this.env.model.dispatch(`COPY`);let n=await this.env.model.getters.getClipboardTextAndImageContent();await this.env.clipboard.write(n),t.preventDefault()}async paste(e){if(!this.gridEl.contains(document.activeElement))return;e.preventDefault();let t=e.clipboardData;if(!t)return;let n=[...t.files].find(e=>WT.includes(e.type)),r={content:{"text/plain":t?.getData(`text/plain`),"text/html":t?.getData(`text/html`)}};n&&(r.content[n.type]=n);let i=this.env.model.getters.getSelectedZones(),a=this.env.model.getters.isCutOperation();if(this.env.model.getters.getClipboardId()===YT(r.content[`text/html`]))hw(this.env,i);else{let e=JT(r.content);await gw(this.env,i,e)}a&&await this.env.clipboard.write({"text/plain":``})}clearFormatting(){this.env.model.dispatch(`CLEAR_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}setHorizontalAlign(e){this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{align:e}})}closeMenu(){this.menuState.isOpen=!1,this.focusDefaultElement()}processHeaderGroupingKey(e){if(this.env.model.getters.getSelectedZones().length!==1)return;let t=this.env.model.getters.getActiveRows().size>0,n=this.env.model.getters.getActiveCols().size>0;n&&t?this.processHeaderGroupingEventOnWholeSheet(e):n?this.processHeaderGroupingEventOnHeaders(e,`COL`):t?this.processHeaderGroupingEventOnHeaders(e,`ROW`):this.processHeaderGroupingEventOnGrid(e)}processHeaderGroupingEventOnHeaders(e,t){let n=this.env.model.getters.getActiveSheetId(),r=this.env.model.getters.getSelectedZone(),i=t===`COL`?r.left:r.top,a=t===`COL`?r.right:r.bottom;switch(e){case`right`:this.env.model.dispatch(`GROUP_HEADERS`,{sheetId:n,dimension:t,start:i,end:a});break;case`left`:this.env.model.dispatch(`UNGROUP_HEADERS`,{sheetId:n,dimension:t,start:i,end:a});break;case`down`:this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:n,dimension:t,zone:r});break;case`up`:this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:n,dimension:t,zone:r});break}}processHeaderGroupingEventOnWholeSheet(e){let t=this.env.model.getters.getActiveSheetId();e===`up`?(this.env.model.dispatch(`FOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`ROW`}),this.env.model.dispatch(`FOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`COL`})):e===`down`&&(this.env.model.dispatch(`UNFOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`ROW`}),this.env.model.dispatch(`UNFOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`COL`}))}processHeaderGroupingEventOnGrid(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getSelectedZone();switch(e){case`down`:this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`ROW`,zone:n}),this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`COL`,zone:n});break;case`up`:this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`ROW`,zone:n}),this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`COL`,zone:n});break;case`right`:{let{x:e,y:t,width:r}=this.env.model.getters.getVisibleRectWithZoom(n),i=this.getGridRect();this.toggleContextMenu(`GROUP_HEADERS`,e+r+i.x,t+i.y);break}case`left`:{if(!jN(this.env,`COL`)&&!jN(this.env,`ROW`))return;let{x:e,y:t,width:r}=this.env.model.getters.getVisibleRectWithZoom(n),i=this.getGridRect();this.toggleContextMenu(`UNGROUP_HEADERS`,e+r+i.x,t+i.y);break}}}onComposerCellFocused(e,t){this.composerFocusStore.focusActiveComposer({content:e,selection:t,focusMode:`cellFocus`})}onComposerContentFocused(){this.composerFocusStore.focusActiveComposer({focusMode:`contentFocus`})}get staticTables(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getCoreTables(e).filter(EM)}get displaySelectionHandler(){return this.env.isMobile()&&this.composerFocusStore.activeComposer.editionMode===`inactive`}};let _I=new A;_I.add(`SPREADSHEET`,!1);var vI=class extends t.Component{static template=`o-spreadsheet-ClickableCellSortIcon`;static props={position:Object,sortDirection:String};hoveredTableStore;setup(){this.hoveredTableStore=O(HF)}get style(){let e=this.env.model.getters.getCellComputedStyle(this.props.position),t=Dd(e);return W({height:`${t}px`,width:`${t}px`,color:e.textColor||`#374151C2`,"background-color":this.getBackgroundColor(e)})}get verticalJustifyClass(){switch(this.env.model.getters.getCellComputedStyle(this.props.position).verticalAlign){case`top`:return`justify-content-start`;case`middle`:return`justify-content-center`;default:return`justify-content-end`}}getBackgroundColor(e){let t=this.hoveredTableStore.overlayColors.get(this.props.position);return t?Kr(e.fillColor||`#FFFFFF`,t):e.fillColor||`#FFFFFF`}},yI=class extends t.Component{static template=`o-spreadsheet-FullScreenFigure`;static props={};static components={ChartFigure:Oy};fullScreenFigureStore;ref=(0,t.useRef)(`fullScreenFigure`);spreadsheetRect=vy();figureRegistry=Ay;setup(){this.fullScreenFigureStore=O(cy);let e=O(Ud),n;(0,t.onWillUpdateProps)(()=>{n!==this.figureUI?.id&&e.enableAnimationForChart(this.chartId+`-fullscreen`),n=this.figureUI?.id}),(0,t.useEffect)(e=>e?.focus(),()=>[this.ref.el])}get figureUI(){return this.fullScreenFigureStore.fullScreenFigure}get chartId(){if(this.figureUI)return this.env.model.getters.getChartIdFromFigureId(this.figureUI?.id)}exitFullScreen(){this.figureUI&&this.fullScreenFigureStore.toggleFullScreenFigure(this.figureUI.id)}onKeyDown(e){e.key===`Escape`&&this.exitFullScreen()}get figureComponent(){if(this.figureUI)return Ay.get(this.figureUI.tag).Component}},bI=class extends t.Component{static template=`o_spreadsheet.PivotHTMLRenderer`;static components={Checkbox:IT};static props={pivotId:String,onCellClicked:Function};pivot=this.env.model.getters.getPivot(this.props.pivotId);data={columns:[],rows:[],values:[]};state=(0,t.useState)({showMissingValuesOnly:!1});setup(){let e=this.pivot.getExpandedTableStructure(),t=this.env.model.getters.getPivotFormulaId(this.props.pivotId);this.data={columns:this._buildColHeaders(t,e),rows:this._buildRowHeaders(t,e),values:this._buildValues(t,e)}}get tracker(){return this.env.model.getters.getPivotPresenceTracker(this.props.pivotId)}getTableData(){if(!this.state.showMissingValuesOnly)return this.data;let e=this.getColumnsIndexes(),t=this.getRowsIndexes();return{columns:this.buildColumnsMissing(e),rows:this.buildRowsMissing(t),values:this.buildValuesMissing(e,t)}}addRecursiveRow(e){let t=this.pivot.getExpandedTableStructure().rows,n=[...t[e].values];if(n.length<=1)return[e];n.pop();let r=t.findIndex(e=>JSON.stringify(e.values)===JSON.stringify(n));return[e].concat(this.addRecursiveRow(r))}buildColumnsMissing(e){let t=[];for(let e of this.data.columns){let n=[];for(let t in e)for(let r=0;r<e[t].span;r++)n.push(parseInt(t,10));t.push(n)}for(let n=t[t.length-1].length;n>=0;n--)if(!e.includes(n))for(let e of t)e.splice(n,1);let n=[];for(let e in t){let r=[],i,a=1;for(let n=0;n<t[e].length;n++)i===t[e][n]?a++:(i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),i=t[e][n],a=1);i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),n.push(r)}return n}buildRowsMissing(e){return e.map(e=>this.data.rows[e])}buildValuesMissing(e,t){let n=e.map(()=>[]);for(let r of t)for(let t in e)n[t].push(this.data.values[e[t]][r]);return n}getColumnsIndexes(){let e=new Set;for(let t=0;t<this.data.columns.length;t++){let n=[];for(let e=0;e<this.data.columns[t].length;e++)for(let r=0;r<this.data.columns[t][e].span;r++)n.push(this.data.columns[t][e]);for(let t=0;t<n.length;t++)n[t].isMissing&&e.add(t)}for(let t=0;t<this.data.columns[this.data.columns.length-1].length;t++)this.data.values[t].find(e=>e.isMissing)&&e.add(t);return Array.from(e).sort((e,t)=>e-t)}getRowsIndexes(){let e=new Set;for(let t=0;t<this.data.rows.length;t++){this.data.rows[t].isMissing&&e.add(t);for(let n of this.data.values)n[t].isMissing&&this.addRecursiveRow(t).forEach(t=>e.add(t))}return Array.from(e).sort((e,t)=>e-t)}_buildColHeaders(e,t){let n=[];for(let r of t.columns){let t=[];for(let n of r){let r=[];for(let e=0;e<n.fields.length;e++)r.push({value:n.fields[e]},{value:n.values[e]});let i=this.pivot.parseArgsToPivotDomain(r),a=this.env.model.getters.getLocale();if(i.at(-1)?.field===`measure`){let{value:r,format:o}=this.pivot.getPivotMeasureValue(L(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${wg(e,i).join(`,`)})`,value:H(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}else{let{value:r,format:o}=this.pivot.getPivotHeaderValueAndFormat(i);t.push({formula:`=PIVOT.HEADER(${wg(e,i).join(`,`)})`,value:H(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}}n.push(t)}let r=n[n.length-1];return n[n.length-1]=r.map(e=>(e.isMissing||(e.style=`color: #756f6f;`),e)),n}_buildRowHeaders(e,t){let n=[];for(let r of t.rows){let t=[];for(let e=0;e<r.fields.length;e++)t.push({value:r.fields[e]},{value:r.values[e]});let i=this.pivot.parseArgsToPivotDomain(t),{value:a,format:o}=this.pivot.getPivotHeaderValueAndFormat(i),s=this.env.model.getters.getLocale(),c={formula:`=PIVOT.HEADER(${wg(e,i).join(`,`)})`,value:H(a,{format:o,locale:s}),isMissing:!this.tracker?.isHeaderPresent(i)};r.indent>1&&(c.style=`padding-left: ${r.indent-10}px`),n.push(c)}return n}_buildValues(e,t){let n=[];for(let r of t.columns.at(-1)||[]){let i=[],a=L(r.values[r.values.length-1]);for(let n of t.rows){let t=[];for(let e=0;e<n.fields.length;e++)t.push({value:n.fields[e]},{value:n.values[e]});for(let e=0;e<r.fields.length-1;e++)t.push({value:r.fields[e]},{value:r.values[e]});let o=this.pivot.parseArgsToPivotDomain(t),{value:s,format:c}=this.pivot.getPivotCellValueAndFormat(a,o),l=this.env.model.getters.getLocale();i.push({formula:`=PIVOT.VALUE(${wg(e,o,a).join(`,`)})`,value:H(s,{format:c,locale:l}),isMissing:!this.tracker?.isValuePresent(a,o)})}n.push(i)}return n}},xI=class{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(let n of e){let e=n.call(this,t);Array.isArray(e)||(e=[e]);let r=e.filter(e=>e!==`Success`);if(r.length)return r}return`Success`}}checkValidations(e,...t){return this.batchValidations(...t)(e)}},SI=class extends xI{getters;dispatch;canDispatch;constructor({getters:e,stateObserver:t,range:n,dispatch:r,canDispatch:i}){super(t),n.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.dispatch=r,this.canDispatch=i}import(e){}export(e,t){}adaptRanges(e){}},CI=class extends SI{static getters=[`getCellBorder`,`getBordersColors`];borders={};allowDispatch(e){switch(e.type){case`SET_BORDER`:return this.checkBordersUnchanged(e);default:return`Success`}}handle(e){switch(e.type){case`ADD_MERGE`:for(let t of e.target)this.addBordersToMerge(e.sheetId,t);break;case`DUPLICATE_SHEET`:let t=this.borders[e.sheetId];if(t){let n=t.slice().map(e=>e?.slice().map(e=>x(e)));this.history.update(`borders`,e.sheetIdTo,n)}break;case`DELETE_SHEET`:let n={...this.borders};delete n[e.sheetId],this.history.update(`borders`,n);break;case`SET_BORDER`:this.setBorder(e.sheetId,e.col,e.row,e.border);break;case`SET_BORDERS_ON_TARGET`:for(let t of e.target)for(let n=t.top;n<=t.bottom;n++)for(let r=t.left;r<=t.right;r++)this.setBorder(e.sheetId,r,n,e.border);break;case`SET_ZONE_BORDERS`:if(e.border){let t=e.target.map(t=>this.getters.expandZone(e.sheetId,t));this.setBorders(e.sheetId,t,e.border.position,e.border.color===``?void 0:{style:e.border.style||Oe.style,color:e.border.color||Oe.color})}break;case`CLEAR_FORMATTING`:this.clearBorders(e.sheetId,e.target);break;case`REMOVE_COLUMNS_ROWS`:let r=[...e.elements].sort((e,t)=>t-e);for(let t of rt(r))if(e.dimension===`COL`){let n=this.getters.getColsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersHorizontally(e.sheetId,t[0]+1,-t.length)}else{let n=this.getters.getRowsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersVertically(e.sheetId,t[0]+1,-t.length)}break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumns(e):this.handleAddRows(e);break}}handleAddColumns(e){let t,n;e.position===`before`?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity),t=e.base,n=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,n)}handleAddRows(e){let t,n;e.position===`before`?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity),t=e.base,n=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,n)}getCellBorder({sheetId:e,col:t,row:n}){let r=this.borders[e]?.[t]?.[n];return r?.top||r?.bottom||r?.left||r?.right?x(r):null}getBordersColors(e){let t=[],n=this.borders[e];if(n){for(let e of n.filter(w))for(let n of e)if(n)for(let e of[`top`,`bottom`,`left`,`right`]){let r=n[e]?.color;r&&t.push(r)}}return t}ensureColumnBorderContinuity(e,t,n){let r=C(t+1,n);for(let i=0;i<this.getters.getNumberRows(e);i++){let a=this.getCellBorder({sheetId:e,col:t,row:i}),o=this.getCellBorder({sheetId:e,col:n,row:i});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,n,i,t)}}}ensureRowBorderContinuity(e,t,n){let r=C(t+1,n);for(let i=0;i<this.getters.getNumberCols(e);i++){let a=this.getCellBorder({sheetId:e,col:i,row:t}),o=this.getCellBorder({sheetId:e,col:i,row:n});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,i,n,t)}}}getCommonSides(e,t){let n={};for(let r of[`top`,`bottom`,`left`,`right`])e[r]&&T(e[r],t[r])&&(n[r]=e[r]);return n}getColumnsWithBorders(e){let t=this.borders[e];return t?Object.keys(t).map(e=>parseInt(e,10)):[]}getRowsWithBorders(e){let t=this.borders[e]?.filter(w);if(!t)return[];let n=new Set;for(let e of t)for(let t in e)n.add(parseInt(t,10));return Array.from(n)}getRowsRange(e){return this.borders[e]?C(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,n){this.borders[e]&&this.getColumnsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(t=>{this.moveBordersOfColumn(e,t,n)})}shiftBordersVertically(e,t,n){this.borders[e]&&(n<0&&this.moveBordersOfRow(e,t,n,{destructive:!1}),this.getRowsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(t=>{this.moveBordersOfRow(e,t,n)}))}moveBordersOfRow(e,t,n,{destructive:r}={destructive:!0}){let i=this.borders[e];i&&this.getColumnsWithBorders(e).forEach(a=>{let o=i[a]?.[t+n],s=i[a]?.[t];this.history.update(`borders`,e,a,t+n,r?s:s||o),this.history.update(`borders`,e,a,t,void 0)})}moveBordersOfColumn(e,t,n,{destructive:r}={destructive:!0}){let i=this.borders[e];i&&this.getRowsRange(e).forEach(a=>{let o=i[t+n]?.[a],s=i[t]?.[a];this.history.update(`borders`,e,t+n,a,r?s:s||o),r&&this.history.update(`borders`,e,t,a,void 0)})}setBorder(e,t,n,r,i=!0){let a=this.getters.getNumberCols(e)-1,o=this.getters.getNumberRows(e)-1;(i||!this.borders[e]?.[t]?.[n]?.left)&&(this.history.update(`borders`,e,t,n,`left`,r?.left),r?.left&&t>0&&!T(this.borders[e]?.[t-1]?.[n]?.right,r?.left)&&this.history.update(`borders`,e,t-1,n,`right`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.top)&&(this.history.update(`borders`,e,t,n,`top`,r?.top),r?.top&&n>0&&!T(this.borders[e]?.[t]?.[n-1]?.bottom,r?.top)&&this.history.update(`borders`,e,t,n-1,`bottom`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.right)&&(this.history.update(`borders`,e,t,n,`right`,r?.right),r?.right&&t<a&&!T(this.borders[e]?.[t+1]?.[n]?.left,r?.right)&&this.history.update(`borders`,e,t+1,n,`left`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.bottom)&&(this.history.update(`borders`,e,t,n,`bottom`,r?.bottom),r?.bottom&&n<o&&!T(this.borders[e]?.[t]?.[n+1]?.top,r?.bottom)&&this.history.update(`borders`,e,t,n+1,`top`,void 0))}clearBorders(e,t,n=!1){let r=this.getters.getNumberCols(e)-1,i=this.getters.getNumberRows(e)-1;for(let a of cn(t))for(let t=a.top;t<=a.bottom;t++){n&&(a.left>0&&this.history.update(`borders`,e,a.left-1,t,`right`,void 0),a.right<r&&this.history.update(`borders`,e,a.right+1,t,`left`,void 0));for(let r=a.left;r<=a.right;r++)this.history.update(`borders`,e,r,t,void 0),n&&(a.top>0&&this.history.update(`borders`,e,r,a.top-1,`bottom`,void 0),a.bottom<i&&this.history.update(`borders`,e,r,a.bottom+1,`top`,void 0))}}clearInsideBorders(e,t){for(let n of t)for(let t=n.top;t<=n.bottom;t++)for(let r=n.left;r<=n.right;r++)this.history.update(`borders`,e,r,t,void 0)}addBorder(e,t,n,r){this.setBorder(e,t,n,{...this.getCellBorder({sheetId:e,col:t,row:n}),...r})}setBorders(e,t,n,r){if(n===`clear`)return this.clearBorders(e,t,!0);for(let i of cn(t)){if(n===`all`)for(let t=i.top;t<=i.bottom;t++)for(let n=i.left;n<=i.right;n++)this.addBorder(e,n,t,{top:r,right:r,bottom:r,left:r});if(n===`h`||n===`hv`){if(i.top===i.bottom)continue;for(let t=i.left;t<=i.right;t++){this.addBorder(e,t,i.top,{bottom:r});for(let n=i.top+1;n<i.bottom;n++)this.addBorder(e,t,n,{top:r,bottom:r});this.addBorder(e,t,i.bottom,{top:r})}}if(n===`v`||n===`hv`){if(i.left===i.right)continue;for(let t=i.top;t<=i.bottom;t++){this.addBorder(e,i.left,t,{right:r});for(let n=i.left+1;n<i.right;n++)this.addBorder(e,n,t,{left:r,right:r});this.addBorder(e,i.right,t,{left:r})}}if(n===`left`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.left,t,{left:r});if(n===`right`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.right,t,{right:r});if(n===`top`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.top,{top:r});if(n===`bottom`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.bottom,{bottom:r})}}addBordersToMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t,o=this.getCellBorder({sheetId:e,col:n,row:i}),s=this.getCellBorder({sheetId:e,col:r,row:a});this.clearBorders(e,[t]),o?.top&&this.setBorders(e,[{...t,bottom:i}],`top`,o.top),o?.left&&this.setBorders(e,[{...t,right:n}],`left`,o.left),s?.bottom?this.setBorders(e,[{...t,top:a}],`bottom`,s.bottom):o?.bottom&&this.setBorders(e,[{...t,top:a}],`bottom`,o.bottom),s?.right?this.setBorders(e,[{...t,left:r}],`right`,s.right):o?.right&&this.setBorders(e,[{...t,left:r}],`right`,o.right)}checkBordersUnchanged(e){let t=this.getCellBorder(e),n=!e.border?.bottom&&!e.border?.left&&!e.border?.right&&!e.border?.top;return!t&&n||T(t,e.border)?`NoChanges`:`Success`}import(e){if(Object.keys(e.borders||{}).length)for(let t of e.sheets)for(let[n,r]of cd(t.id,t.borders)){let{sheetId:t,col:i,row:a}=n,o=e.borders[r];this.setBorder(t,i,a,o,!1)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,yn(e))}export(e){let t={};for(let n of e.sheets){let e={};for(let r=0;r<n.colNumber;r++)for(let i=0;i<n.rowNumber;i++){let a=this.getCellBorder({sheetId:n.id,col:r,row:i});if(a){let o=od(a,t),s={sheetId:n.id,col:r,row:i};e[o]??=[],e[o].push(s)}}n.borders=sd(e)}e.borders=t}exportForExcel(e){this.export(e)}},wI=class extends SI{static getters=[`getCarousel`,`doesCarouselExist`];carousels={};allowDispatch(e){switch(e.type){case`CREATE_CAROUSEL`:return this.getters.getFigure(e.sheetId,e.figureId)?`DuplicatedFigureId`:`Success`;case`UPDATE_CAROUSEL`:return this.carousels[e.sheetId]?.[e.figureId]?`Success`:`InvalidFigureId`}return`Success`}handle(e){switch(e.type){case`CREATE_CAROUSEL`:this.getters.getFigure(e.sheetId,e.figureId)||this.dispatch(`CREATE_FIGURE`,{...e,tag:`carousel`}),this.history.update(`carousels`,e.sheetId,e.figureId,e.definition);break;case`UPDATE_CAROUSEL`:this.removeDeletedCharts(e,this.getters.getCarousel(e.figureId).items),this.history.update(`carousels`,e.sheetId,e.figureId,e.definition);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`carousel`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.getCarousel(n.id);if(i){let t={width:n.width,height:n.height};this.dispatch(`CREATE_CAROUSEL`,{sheetId:e.sheetIdTo,figureId:r,offset:n.offset,col:n.col,row:n.row,size:t,definition:{items:i.items.map(t=>{if(t.type===`carouselDataView`)return{...t};let n=t.chartId.split(`??`).pop(),r=`${e.sheetIdTo}??${n}`;return{...t,chartId:r}})}})}}break}case`DELETE_FIGURE`:this.history.update(`carousels`,e.sheetId,e.figureId,void 0);break;case`DELETE_SHEET`:this.history.update(`carousels`,e.sheetId,void 0);break}}doesCarouselExist(e){for(let t in this.carousels)if(this.carousels[t]?.[e])return!0;return!1}getCarousel(e){for(let t in this.carousels)if(this.carousels[t]?.[e])return this.carousels[t][e];throw Error(`There is no carousel with the given figureId: ${e}`)}removeDeletedCharts(e,t){let n=new Set(e.definition.items.filter(e=>e.type===`chart`).map(e=>e.chartId));for(let r of t)r.type===`chart`&&!n.has(r.chartId)&&this.dispatch(`DELETE_CHART`,{chartId:r.chartId,sheetId:e.sheetId})}import(e){for(let t of e.sheets){let e=(t.figures||[]).filter(e=>e.tag===`carousel`);for(let n of e)this.history.update(`carousels`,t.id,n.id,{items:n.data.items,title:n.data.title})}}export(e){for(let t of e.sheets){let e=t.figures.filter(e=>e.tag===`carousel`);for(let n of e)this.carousels[t.id]?.[n.id]&&(n.data={...n.data,...this.carousels[t.id]?.[n.id]})}}},TI=class{getters;baseFormula;alreadyAppliedNumberOffsets=[];previousStrings=[];baseFormulaWasTransformed=!1;rangeToStringOptions={doNotSimplifyRange:!0};baseNumber=void 0;constructor(e){this.getters=e}buildResult(e,t,n){let r={};if(e.length&&(r.N=e.join(`|`)),t.length&&(r.S=t),n.length){let e;e=n.some(e=>e.includes(`|`))?n:n.join(`|`),r.R=e}return r}resetBaseTo(e){this.baseFormula=Rc.CopyWithDependenciesAndLiteral(e,e.sheetId,x(e.rangeDependencies),e.literalValues.numbers,e.literalValues.strings),this.alreadyAppliedNumberOffsets=e.literalValues.numbers.map(e=>0),this.previousStrings=e.literalValues.strings.map(e=>e.value),this.baseFormulaWasTransformed=!1,this.baseNumber=void 0}resetBaseFormula(){this.baseFormula&&(this.baseFormula=void 0,this.alreadyAppliedNumberOffsets=[],this.previousStrings=[],this.baseFormulaWasTransformed=!1)}squish(e,t){if(e.isFormula){let n=[],r=[],i=[];return!this.baseFormula||this.baseFormula.normalizedFormula!==e.compiledFormula.normalizedFormula?(this.resetBaseTo(e.compiledFormula),e.compiledFormula.toFormulaString(this.getters,this.rangeToStringOptions)):!this.baseFormulaWasTransformed&&T(e.compiledFormula.literalValues,this.baseFormula.literalValues)&&T(e.compiledFormula.rangeDependencies,this.baseFormula.rangeDependencies)?e.compiledFormula.toFormulaString(this.getters,this.rangeToStringOptions):(n=this.squishNumbers(e.compiledFormula.literalValues.numbers),r=this.squishStrings(e.compiledFormula.literalValues.strings),i=this.squishReferences(e.compiledFormula.rangeDependencies,t),this.baseFormulaWasTransformed=!0,this.buildResult(n,r,i))}if(typeof e.parsedValue==`number`&&e.parsedValue%1==0){this.resetBaseFormula();let t=e.parsedValue;if(this.baseNumber===void 0)return this.baseNumber=t,e.content;let n=t-this.baseNumber;return n===0?e.content:(this.baseNumber=t,{N:(n>0?`+`:``)+n.toString()})}return this.resetBaseFormula(),this.baseNumber=void 0,e.content}squishCommand(e){if(e.content){let t=Ru(this.getters,-1,e.content,e.format,e.style??void 0,e.sheetId),n=this.squish(t,e.sheetId);return typeof n==`string`?e.content:n}return e.content}squishSheet(e,t){let n=Object.keys(e),r={};for(let i=0;i<n.length;i++){let a=sn(n[i]),o=0;for(o=0;o+i+1<n.length;o++){let t=sn(n[o+i+1]);if(t.col!==a.col||t.row!==a.row+o+1||!T(e[n[o+i+1]],e[n[i]]))break}if(o>0){let t=`${n[i]}:${E(a.col,a.row+o)}`;r[t]=e[n[i]],i+=o}else{let o=this.getters.getCell({sheetId:t,col:a.col,row:a.row});!o?.isFormula&&typeof o?.parsedValue==`number`?r[n[i]]=o.content:r[n[i]]=e[n[i]]}}return r}squishReferences(e,t){if(!this.baseFormula)throw Error(`No previous cell to squish against`);return e.map((e,n)=>this.squishOneReference(e,this.baseFormula.rangeDependencies,n,t))}squishOneReference(e,t,n,r){let i=t[n];if(T(i,e))return`=`;if(i.sheetId!==e.sheetId||i.prefixSheet!==e.prefixSheet||i.invalidSheetName!==e.invalidSheetName||i.invalidXc!==e.invalidXc||i.parts.length!==e.parts.length||i.unboundedZone.bottom===void 0||i.unboundedZone.right===void 0||e.unboundedZone.bottom===void 0||e.unboundedZone.right===void 0)return t[n]=x(e),ec(e,r,this.getters.getSheetName,this.rangeToStringOptions);for(let a=0;a<e.parts.length;a++)if(i.parts[a].colFixed!==e.parts[a].colFixed||i.parts[a].rowFixed!==e.parts[a].rowFixed)return t[n]=x(e),ec(e,r,this.getters.getSheetName,this.rangeToStringOptions);let a=e.zone,o=i.zone;if(a.top!==a.bottom||a.left!==a.right||o.top!==o.bottom||o.left!==o.right)return t[n]=x(e),ec(e,r,this.getters.getSheetName,this.rangeToStringOptions);let s=e.zone.left-i.zone.left,c=e.zone.top-i.zone.top;return i.zone=x(e.zone),i.unboundedZone=x(e.unboundedZone),s!==0&&c===0?`${s>0?`+`:`-`}C${Math.abs(s)}`:c!==0&&s===0?`${c>0?`+`:`-`}R${Math.abs(c)}`:ec(e,r,this.getters.getSheetName,this.rangeToStringOptions)}squishNumbers(e){let t=e.map(e=>`=`);for(let n=0;n<e.length;n++){let r=this.baseFormula.literalValues.numbers[n].value,i=e[n].value,a=this.alreadyAppliedNumberOffsets[n]||0,o=i-(r+a);o!==0&&(t[n]=`+`+o.toString(),this.alreadyAppliedNumberOffsets[n]=a+o)}return t}squishStrings(e){let t=e.map(e=>`=`);for(let n=0;n<e.length;n++){let r=e[n].value;r!==this.previousStrings[n]&&(t[n]=r,this.previousStrings[n]=r)}return t}};function EI(e){return[sn(e)]}function*DI(e,t){let n=sn(e),r=sn(t);for(let e=Math.min(n.col,r.col);e<=Math.max(n.col,r.col);e++)for(let t=Math.min(n.row,r.row);t<=Math.max(n.row,r.row);t++)yield{col:e,row:t}}var OI=class{previousFormula;alreadyAppliedNumberOffset=[];previousString=[];alreadyAppliedReferenceOffset=[];previousOffset=void 0;previousNumber=void 0;previousNumberFormat;rebase(){this.previousFormula=void 0,this.alreadyAppliedNumberOffset=[],this.previousString=[],this.alreadyAppliedReferenceOffset=[],this.previousOffset=void 0,this.previousNumber=void 0,this.previousNumberFormat=void 0}*unsquishCommands(e,t){let n;for(let r of e){if(r.type!==`UPDATE_CELL`&&r.type!==`SQUISHED_UPDATE_CELL`){yield r;continue}let e=r.content;n=e==null||e===``?`NOT_A_FORMULA`:this.chooseStrategy(e,n,r.sheetId,t);let i;if(r.type===`SQUISHED_UPDATE_CELL`&&`targetRange`in r){let[e,t]=r.targetRange.split(`:`);i=DI(e,t)}else i=[{row:r.row,col:r.col}];for(let{position:a,compiled:o,content:s}of this.applyStrategy(n,i,e,r.sheetId,t)){let e=o?o.toFormulaString(t):s,n={type:`UPDATE_CELL`,sheetId:r.sheetId,row:a.row,col:a.col};(`content`in r||o)&&(n.content=e),`style`in r&&(n.style=r.style),`format`in r&&(n.format=r.format),yield n}}}*unsquishSheet(e,t,n){let r=Object.keys(e).map(e=>({cartesian:sn(e.split(`:`)[0]),key:e})).sort((e,t)=>e.cartesian.col===t.cartesian.col?e.cartesian.row-t.cartesian.row:e.cartesian.col-t.cartesian.col),i;for(let{key:a}of r){let r=e[a];if(r==null||r===``)continue;i=this.chooseStrategy(r,i,t,n);let o=a.split(`:`),s=o.length===1?EI(a):DI(o[0],o[1]);yield*this.applyStrategy(i,s,r,t,n)}}chooseStrategy(e,t,n,r){let i=t;if(typeof e==`string`)if(e.startsWith(`=`)){i=`NEW_FORMULA`;let t=Rc.Compile(e,n,r);this.previousFormula=t,this.alreadyAppliedNumberOffset=t.literalValues.numbers.map(e=>e.value),this.previousString=t.literalValues.strings.map(e=>e.value),this.alreadyAppliedReferenceOffset=[...t.rangeDependencies],this.previousOffset=void 0,this.previousNumber=void 0,this.previousNumberFormat=void 0}else{let t=this.parseSquishableLiteral(e,r);t?(i=`NEW_NUMBER`,this.rebase(),this.previousNumber=t.value,this.previousNumberFormat=t.format):(this.rebase(),i=`NOT_A_FORMULA`)}else if(e.N||e.S||e.R){if(!i)throw Error(`Incorrect order of commands, cannot unsquish`);switch(i){case`NEW_FORMULA`:i=`FIRST_OFFSET`;break;case`NEW_NUMBER`:if(e.R||e.S)throw Error(`Invalid squished format: cannot have string or reference offsets for a number`);i=`OFFSET_NUMBER`;break;case`FIRST_OFFSET`:i=`COMBINE_OFFSET`;break}}return i}*applyStrategy(e,t,n,r,i){let a=n;switch(e){case`NEW_FORMULA`:for(let e of t)yield{position:e,compiled:this.previousFormula};break;case`NOT_A_FORMULA`:for(let e of t)yield{position:e,content:a};break;case`FIRST_OFFSET`:{let e=a;this.previousOffset=e;for(let n of t){let t=this.unsquishFormula(e,r,i);if(t.areRangeShapesInLineWithNormalizedFormula())yield{position:n,compiled:t};else{let e=t.toFormulaString(i);yield{position:n,compiled:Rc.Compile(e,r,i)}}}break}case`COMBINE_OFFSET`:{if(!this.previousOffset)throw Error(`No previous offset to combine with`);let e=a;this.previousOffset.N=e.N??this.previousOffset.N,this.previousOffset.S=e.S??this.previousOffset.S,this.previousOffset.R=e.R??this.previousOffset.R;for(let e of t){let t=this.unsquishFormula(this.previousOffset,r,i);if(t.areRangeShapesInLineWithNormalizedFormula())yield{position:e,compiled:t};else{let n=t.toFormulaString(i);yield{position:e,compiled:Rc.Compile(n,r,i)}}}break}case`NEW_NUMBER`:for(let e of t)yield{position:e,content:a};break;case`OFFSET_NUMBER`:{let e=a.N;if(e===void 0||this.previousNumber===void 0)throw Error(`No ${e} provided for OFFSET_NUMBER strategy, previous ${this.previousNumber} for ${r}!${JSON.stringify(a)} `);let n=parseFloat(e),o={format:this.previousNumberFormat,locale:i.getLocale()};for(let e of t)this.previousNumber+=n,yield{position:e,content:H(this.previousNumber,o)};break}}}parseSquishableLiteral(e,t){let n=zu(t,-1,e,void 0,void 0);if(!(typeof n.parsedValue!=`number`||n.parsedValue%1!=0))return{value:n.parsedValue,format:n.format}}unsquishFormula(e,t,n){if(typeof e==`object`&&this.previousFormula){let r={numbers:[],strings:[],dependencies:[]};if(e.N!==void 0&&e.N.length>0?r.numbers=e.N.split(`|`).map(this.adjustNumbers):r.numbers=this.previousFormula.literalValues.numbers,e.S!==void 0&&e.S.length>0?r.strings=e.S.map(this.adjustStrings):r.strings=this.previousFormula.literalValues.strings,e.R!==void 0&&this.previousFormula){let i;i=typeof e.R==`string`?e.R.split(`|`):e.R,r.dependencies=i.map((e,r)=>{if(e===`=`)return{...this.alreadyAppliedReferenceOffset[r]};if(e.startsWith(`+`)||e.startsWith(`-`)){let t=parseInt(e.slice(2),10),n=e[0]===`+`?1:-1;if(e[1]===`R`){let e=this.alreadyAppliedReferenceOffset[r].zone.top+t*n,i={...this.alreadyAppliedReferenceOffset[r]};return i.zone=i.unboundedZone={...i.zone,top:e,bottom:e},this.alreadyAppliedReferenceOffset[r]=i,i}else if(e[1]===`C`){let e=this.alreadyAppliedReferenceOffset[r].zone.left+t*n,i=Object.assign({},this.alreadyAppliedReferenceOffset[r]);return i.zone=i.unboundedZone=Object.assign({},i.zone,{left:e,right:e}),this.alreadyAppliedReferenceOffset[r]=i,i}else throw Error(`Invalid reference offset format: ${e}`)}else{let i=n.getRangeFromSheetXC(t,e);return this.alreadyAppliedReferenceOffset[r]=i,i}})}else r.dependencies=this.previousFormula.rangeDependencies;return Rc.CopyWithDependenciesAndLiteral(this.previousFormula,t,r.dependencies,r.numbers,r.strings)}throw Error(`Invalid squished element or no previous cell to unsquish against`)}adjustStrings=(e,t)=>e===`=`?{value:this.previousString[t]}:(this.previousString[t]=e,{value:e});adjustNumbers=(e,t)=>{if(e===`=`)return{value:this.alreadyAppliedNumberOffset[t]};{let n=parseFloat(e.slice(1)),r=(this.alreadyAppliedNumberOffset[t]||0)+n;return this.alreadyAppliedNumberOffset[t]=r,{value:r}}}},kI=class extends SI{static getters=[`zoneToXC`,`getCells`,`getTranslatedCellFormula`,`getCellStyle`,`getCellById`,`getFormulaString`,`getFormulaMovedInSheet`];nextId=1;cells={};adaptRanges(e){for(let t of Object.keys(this.cells))for(let n of Object.values(this.cells[t]||{}))if(n.isFormula){let r=e.adaptCompiledFormula(n.compiledFormula);r!==n.compiledFormula&&this.history.update(`cells`,t,n.id,`compiledFormula`,r)}}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`;case`SET_FORMATTING`:return this.checkUselessSetFormatting(e);default:return`Success`}}handle(e){switch(e.type){case`SET_FORMATTING`:this.setStyleFormat(e.sheetId,e.target,e.style,e.format);break;case`CLEAR_FORMATTING`:this.clearFormatting(e.sheetId,e.target);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case`UPDATE_CELL`:this.updateCell(e.sheetId,e.col,e.row,e);break;case`CLEAR_CELL`:this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col,row:e.row,content:``,style:null,format:``});break;case`CLEAR_CELLS`:this.clearCells(e.sheetId,e.target);break;case`DELETE_CONTENT`:this.clearZones(e.sheetId,e.target);break;case`DELETE_SHEET`:this.history.update(`cells`,e.sheetId,void 0)}}clearZones(e,t){for(let n of cn(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++){let n=this.getters.getCell({sheetId:e,col:t,row:r});(n?.isFormula||n?.content)&&this.dispatch(`UPDATE_CELL`,{sheetId:e,content:``,col:t,row:r})}}clearFormatting(e,t){for(let n of cn(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,style:null,format:``})}clearCells(e,t){for(let n of t)for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,content:``,style:null,format:``})}handleAddColumnsRows(e,t){let n,r;e.position===`before`?(n=C(e.base,e.base+e.quantity),r=e.base+e.quantity):(n=C(e.base+1,e.base+e.quantity+1),r=e.base),t(e.sheetId,r,n)}import(e){let t=performance.now();for(let t of e.sheets){let n=t.id,r=new tN,i=new OI;for(let e of i.unsquishSheet(t.cells,t.id,this.getters))if(e.content||e.compiled){let n={sheetId:t.id,col:e.position.col,row:e.position.row};e.compiled?r.set(n,{compiledFormula:e.compiled}):r.set(n,{content:e.content})}for(let[e,n]of[[`style`,t.styles],[`format`,t.formats]])for(let[i,a]of cd(t.id,n)){let t=r.get(i);t?t[e]=a:r.set(i,{[e]:a})}for(let i of r.keysForSheet(n)){let n=r.get(i);if(n?.content||n?.format||n?.style||n?.compiledFormula){let r=this.importCell(t.id,n?.content,n?.style?e.styles[n?.style]:void 0,n?.format?e.formats[n?.format]:void 0,n?.compiledFormula);this.history.update(`cells`,t.id,r.id,r),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:r.id,...i})}}}console.debug(`cells imported in`,performance.now()-t,`ms`)}export(e,t){let n={},r={};for(let i of e.sheets){let e=new TI(this.getters),a=[],o=[],s={},c=Object.values(this.cells[i.id]||{}).map(e=>this.getters.getCellPosition(e.id)).sort((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col);for(let l of c){let c=this.getters.getCell(l),u=this.extractCustomStyle(c);if(Object.keys(u).length){let e=od(u,n);a[e]??=[],a[e].push(l)}if(c.format){let e=od(c.format,r);o[e]??=[],o[e].push(l)}let d=E(l.col,l.row);c.isFormula?s[d]=t?e.squish(c,i.id):c.compiledFormula.toFormulaString(this.getters):c.content&&(s[d]=t?e.squish(c,i.id):c.content)}i.styles=sd(a),i.formats=sd(o),i.cells=t?e.squishSheet(s,i.id):s}e.styles=n,e.formats=r}importCell(e,t,n,r,i){let a=this.getNextCellId();return i?Vu(a,i,r,n):Ru(this.getters,a,t||``,r,n,e,{avoidAutomaticDateFormat:!0})}exportForExcel(e){this.export(e,!1);let t=[];for(let n in e.formats||[])ru(e.formats[n])||(t.push(Number(n)),delete e.formats[n]);if(t.length)for(let n of e.sheets)for(let e in n.formats){let r=n.formats[e];r&&t.includes(r)&&delete n.formats[e]}}extractCustomStyle(e){let t={...e.style},n=!e.isFormula&&Pa(e.content,V)?Ce:xe;for(let r in t)(r!==`align`||!e.isFormula)&&t[r]===n[r]&&delete t[r];return t}getCells(e){return Object.values(this.cells[e]||{})}getCellById(e){let t=this.getters.getCellPosition(e);return this.cells[t.sheetId][e]}getFormulaString(e,t,n,r=!1){return Rc.CopyWithDependencies(t,e,n).toFormulaString(this.getters,{useBoundedReference:r})}getTranslatedCellFormula(e,t,n,r){r instanceof Rc||(r=Rc.CompileForSerializedFormula(e,r));let i=this.getters.createAdaptedRanges(r.rangeDependencies,t,n,e);return this.getFormulaString(e,r,i)}getFormulaMovedInSheet(e,t){let n=this.getters.removeRangesSheetPrefix(e,t.rangeDependencies);return Rc.CopyWithDependencies(t,e,n).toFormulaString(this.getters)}getCellStyle(e){return this.getters.getCell(e)?.style||{}}zoneToXC(e,t,n=[{colFixed:!1,rowFixed:!1}]){t=this.getters.expandZone(e,t);let r=E(t.left,t.top,n[0]),i=E(t.right,t.bottom,n.length>1?n[1]:n[0]),a=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),o=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),s=a.col===o.col&&a.row===o.row;return r!==i&&!s?r+`:`+i:r}setStyleFormat(e,t,n,r){if(!(n===void 0&&r===void 0))for(let i of cn(t))for(let t=i.left;t<=i.right;t++)for(let a=i.top;a<=i.bottom;a++){let i=this.getters.getCell({sheetId:e,col:t,row:a});this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:a,style:n?{...i?.style,...n}:void 0,format:r})}}copyColumnStyle(e,t,n){for(let r=0;r<this.getters.getNumberRows(e);r++){let i=this.getFormat(e,t,r);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,...i})}}copyRowStyle(e,t,n){for(let r=0;r<this.getters.getNumberCols(e);r++){let i=this.getFormat(e,r,t);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:r,row:t,...i})}}getFormat(e,t,n){let r={},i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.getters.getCell(i);return a&&(a.style&&(r.style=a.style),a.format&&(r.format=a.format)),r}getNextCellId(){let e=this.nextId;return this.history.update(`nextId`,this.nextId+1),e}updateCell(e,t,n,r){let i=this.getters.getCell({sheetId:e,col:t,row:n}),a=r.content!==void 0||`formula`in r,o;o=a?Mt(r?.content):i?.isFormula?i.compiledFormula.toFormulaString(this.getters):i?.content||``;let s;s=r.style===void 0?i?i.style:void 0:r.style||void 0;let c=r.format===void 0?i&&i.format:r.format;if((a&&!o&&!r.formula||!a&&(!i||!i.isFormula&&i.content===``))&&!s&&!c){i&&(this.history.update(`cells`,e,i.id,void 0),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:void 0,col:t,row:n,sheetId:e}));return}let l=i?.id||this.getNextCellId(),u=Ru(this.getters,l,o,c,s,e);this.history.update(`cells`,e,u.id,u),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:u.id,col:t,row:n,sheetId:e})}checkCellOutOfSheet(e){let{sheetId:t,col:n,row:r}=e;return this.getters.tryGetSheet(t)?Fn(n,r,this.getters.getSheetZone(t))?`Success`:`TargetOutOfSheet`:`InvalidSheetId`}checkUselessClearCell(e){let t=this.getters.getCell(e);return!t||!t.isFormula&&!t.content&&!t.style&&!t.format?`NoChanges`:`Success`}checkUselessUpdateCell(e){let t=this.getters.getCell(e),n=`content`in e||`formula`in e,r=`style`in e,i=`format`in e;return(!n||t?.isFormula&&t.compiledFormula.toFormulaString(this.getters)===e.content||!t?.isFormula&&t?.content===e.content)&&(!r||T(t?.style,e.style))&&(!i||t?.format===e.format)?`NoChanges`:`Success`}checkUselessSetFormatting(e){let{sheetId:t,target:n}=e,r=`style`in e,i=`format`in e;if(!r&&!i)return`NoChanges`;for(let a of cn(n))for(let n=a.left;n<=a.right;n++)for(let o=a.top;o<=a.bottom;o++){let a={sheetId:t,col:n,row:o},s=this.getters.getCell(a);if(r&&!T(s?.style,e.style)||i&&s?.format!==e.format)return`Success`}return`NoChanges`}},AI=class extends SI{static getters=[`isChartDefined`,`getChartDefinition`,`getChartType`,`getChartIds`,`getChart`,`getFigureIdFromChartId`,`getContextCreationChart`];charts={};adaptRanges(e){for(let[t,n]of Object.entries(this.charts)){if(!n)continue;let r=yO.fromDefinition(this.getters,n.chart.sheetId,n.chart.updateRanges(e));this.history.update(`charts`,t,r?{figureId:n.figureId,chart:r}:void 0)}}allowDispatch(e){switch(e.type){case`CREATE_CHART`:return this.checkValidations(e,this.chainValidations(this.checkFigureArguments,this.checkChartDefinition,this.checkChartDuplicate));case`UPDATE_CHART`:return this.checkValidations(e,this.chainValidations(this.checkChartDefinition,this.checkChartExists,this.checkChartChanged));case`DELETE_CHART`:return`SubCommandOnly`;default:return`Success`}}handle(e){switch(e.type){case`CREATE_CHART`:let{col:t,row:n,offset:r,size:i,sheetId:a,figureId:o}=e;!this.getters.getFigure(a,o)&&r!==void 0&&t!==void 0&&n!==void 0&&this.addFigure(o,a,t,n,r,i),this.addChart(e.figureId,e.chartId,e.definition);break;case`UPDATE_CHART`:this.addChart(e.figureId,e.chartId,e.definition);break;case`DUPLICATE_SHEET`:for(let t of this.getChartIds(e.sheetId)){let{chart:n,figureId:r}=this.charts[t]||{};if(!n||!r)continue;let i=this.getters.getFigure(e.sheetId,r);if(!i)continue;let a=r.split(`??`).pop(),o=`${e.sheetIdTo}??${a}`,s=t.split(`??`).pop(),c=`${e.sheetIdTo}??${s}`,l=n.duplicateInDuplicatedSheet(e.sheetId,e.sheetIdTo);this.dispatch(`CREATE_CHART`,{figureId:o,chartId:c,col:i.col,row:i.row,offset:i.offset,size:{width:i.width,height:i.height},definition:l,sheetId:e.sheetIdTo})}break;case`DELETE_FIGURE`:for(let t in this.charts)this.charts[t]?.figureId===e.figureId&&this.dispatch(`DELETE_CHART`,{chartId:t,sheetId:e.sheetId});break;case`DELETE_CHART`:this.isChartDefined(e.chartId)&&this.history.update(`charts`,e.chartId,void 0);break;case`DELETE_SHEET`:for(let t of this.getChartIds(e.sheetId))this.history.update(`charts`,t,void 0);break}}getContextCreationChart(e){return this.charts[e]?.chart.getContextCreation()}getChart(e){return this.charts[e]?.chart}getFigureIdFromChartId(e){if(!this.charts[e])throw Error(`Chart with id ${e} does not exist.`);return this.charts[e].figureId}getChartType(e){let t=this.charts[e]?.chart.getRangeDefinition().type;if(!t)throw Error(`Chart not defined.`);return t}isChartDefined(e){return e in this.charts&&this.charts!==void 0}getChartIds(e){return Object.entries(this.charts).filter(([,t])=>t?.chart.sheetId===e).map(([e])=>e)}getChartDefinition(e){let t=this.charts[e]?.chart.getDefinition();if(!t)throw Error(`There is no chart with the given id: ${e}`);return t}import(e){for(let t of e.sheets)if(t.figures){for(let e of t.figures)if(e.tag===`chart`){let n=e.data.chartId,r={...e.data};delete r.chartId;let i=yO.fromStrDefinition(this.getters,t.id,r);this.charts[n]={chart:i,figureId:e.id}}else if(e.tag===`carousel`)for(let n in e.data.chartDefinitions||{}){let r=e.data.chartDefinitions[n],i=yO.fromStrDefinition(this.getters,t.id,r);this.charts[n]={chart:i,figureId:e.id}}}}export(e){if(e.sheets)for(let t of e.sheets){let e=this.getters.getFigures(t.id),n=[];for(let t of e){let e=t,r=Object.keys(this.charts).find(e=>this.charts[e]?.figureId===t.id);if(e&&e.tag===`chart`&&r){let t=this.charts[r]?.chart.getDefinition();t&&(e.data={...t,chartId:r},n.push(e))}else if(e&&e.tag===`carousel`){let r=Object.keys(this.charts).filter(e=>this.charts[e]?.figureId===t.id),i={};for(let e of r)i[e]=this.charts[e]?.chart.getDefinition();e.data={chartDefinitions:i},n.push(e)}else n.push(e)}t.figures=n}}addFigure(e,t,n,r,i,a={width:536,height:335}){this.dispatch(`CREATE_FIGURE`,{sheetId:t,figureId:e,col:n,row:r,offset:i,size:a,tag:`chart`})}addChart(e,t,n){let r=this.getters.getFigureSheetId(e);if(r){let i=yO.fromStrDefinition(this.getters,r,n);this.history.update(`charts`,t,{figureId:e,chart:i})}}checkChartDuplicate(e){return this.isChartDefined(e.chartId)?`DuplicatedChartId`:`Success`}checkChartDefinition(e){return yO.validate(this,e.definition)}checkChartExists(e){return this.isChartDefined(e.chartId)?`Success`:`ChartDoesNotExist`}checkChartChanged(e){return e.figureId===this.charts[e.chartId]?.figureId&&T(this.getChartDefinition(e.chartId),e.definition)?`NoChanges`:`Success`}checkFigureArguments(e){return this.getters.getFigure(e.sheetId,e.figureId)||e.offset!==void 0&&e.col!==void 0&&e.row!==void 0?`Success`:`MissingFigureArguments`}};function jI(e){return e===``?NaN:Number(e)}var MI=class extends SI{static getters=[`getConditionalFormats`,`getRulesSelection`,`getRulesByCell`,`getAdaptedCfRanges`];cfRules={};adaptCFFormulas({applyChange:e,adaptFormulaString:t}){for(let n in this.cfRules)for(let r of this.cfRules[n])if(r.rule.type===`DataBarRule`&&r.rule.rangeValues){let t=e(r.rule.rangeValues);switch(t.changeType){case`REMOVE`:this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`rangeValues`,void 0);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`rangeValues`,t.range);break}}else if(r.rule.type===`CellIsRule`)for(let e=0;e<r.rule.values.length;e++)this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`values`,e,t(n,r.rule.values[e]));else if(r.rule.type===`IconSetRule`)for(let e of[`lowerInflectionPoint`,`upperInflectionPoint`])r.rule[e].type===`formula`&&this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,e,`value`,t(n,r.rule[e].value));else if(r.rule.type===`ColorScaleRule`)for(let e of[`minimum`,`maximum`,`midpoint`]){let i=r.rule[e];i?.type===`formula`&&i?.value&&this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,e,`value`,t(n,i.value))}}adaptCFRanges(e,{applyChange:t}){for(let n of this.cfRules[e])for(let r of n.ranges){let i=t(r);switch(i.changeType){case`REMOVE`:let t=n.ranges.slice();t.splice(n.ranges.indexOf(r),1),t.length>=1?this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,t):this.removeConditionalFormatting(n.id,e);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,n.ranges.indexOf(r),i.range);break}}}adaptRanges(e){for(let t of Object.keys(this.cfRules))this.adaptCFRanges(t,e);this.adaptCFFormulas(e)}allowDispatch(e){switch(e.type){case`ADD_CONDITIONAL_FORMAT`:return e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkValidations(e,this.checkCFRule,this.checkEmptyRange,this.checkCFHasChanged);case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:return this.checkValidPriorityChange(e.cfId,e.delta,e.sheetId)}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.cfRules[e.sheetId]=[];break;case`DUPLICATE_SHEET`:this.history.update(`cfRules`,e.sheetIdTo,[]);for(let t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case`DELETE_SHEET`:let t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update(`cfRules`,t);break;case`ADD_CONDITIONAL_FORMAT`:let n={...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))};this.addConditionalFormatting(n,e.sheetId);break;case`REMOVE_CONDITIONAL_FORMAT`:this.removeConditionalFormatting(e.id,e.sheetId);break;case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:this.changeCFPriority(e.cfId,e.delta,e.sheetId);break}}import(e){for(let t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map(e=>this.mapToConditionalFormatInternal(t.id,e))}export(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e)))}exportForExcel(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e,{useBoundedReference:!0})))}getConditionalFormats(e){return this.cfRules[e]?.map(t=>this.mapToConditionalFormat(e,t))||[]}getRulesSelection(e,t){let n=new Set;return t.forEach(t=>{this.getRulesByZone(e,t).forEach(e=>{n.add(e)})}),Array.from(n)}getRulesByZone(e,t){let n=new Set;for(let r=t.top;r<=t.bottom;r++)for(let i=t.left;i<=t.right;i++)this.getRulesByCell(e,i,r).forEach(e=>{n.add(e.id)});return n}getRulesByCell(e,t,n){let r=[];for(let i of this.cfRules[e])for(let e of i.ranges)Fn(t,n,e.zone)&&r.push(i);return new Set(r.map(t=>this.mapToConditionalFormat(e,t)))}getAdaptedCfRanges(e,t,n,r){if(n.length===0&&r.length===0)return;let i=this.getters.getConditionalFormats(e),a=i.findIndex(e=>e.id===t.id),o=[];a>-1&&(o=i[a].ranges.map(vn));let s=cn(o,r);return cn([...n,...s],[]).map(t=>this.getters.getRangeDataFromZone(e,t))}mapToConditionalFormat(e,t,{useBoundedReference:n}={useBoundedReference:!1}){let r=t.ranges.map(t=>this.getters.getRangeString(t,e,{useBoundedReference:n}));return t.rule.type===`DataBarRule`?{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues&&this.getters.getRangeString(t.rule.rangeValues,e,{useBoundedReference:n})},ranges:r}:{...t,rule:{...t.rule},ranges:r}}mapToConditionalFormatInternal(e,t){let n=t.ranges.map(t=>this.getters.getRangeFromSheetXC(e,t));return t.rule.type===`DataBarRule`?{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues?this.getters.getRangeFromSheetXC(e,t.rule.rangeValues):void 0},ranges:n}:{...t,rule:{...t.rule},ranges:n}}addConditionalFormatting(e,t){let n=this.cfRules[t].slice(),r=n.findIndex(t=>t.id===e.id),i=this.mapToConditionalFormatInternal(t,e);r>-1?n.splice(r,1,i):n.push(i),this.history.update(`cfRules`,t,n)}checkValidPriorityChange(e,t,n){if(!this.cfRules[n])return`InvalidSheetId`;let r=this.cfRules[n].findIndex(t=>t.id===e);if(r===-1)return`InvalidConditionalFormatId`;let i=r-t;return i<0||i>=this.cfRules[n].length?`InvalidConditionalFormatId`:`Success`}checkEmptyRange(e){return e.ranges.length?`Success`:`EmptyRange`}checkCFRule(e){let t=e.cf.rule;switch(t.type){case`CellIsRule`:return Vh.has(t.operator)?this.checkValidations(t,this.checkOperatorArgsNumber,this.checkCFValues):`InvalidConditionalFormatType`;case`ColorScaleRule`:return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case`IconSetRule`:return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)));case`DataBarRule`:return`Success`}return`InvalidConditionalFormatType`}checkCFHasChanged(e){let t=this.mapToConditionalFormatInternal(e.sheetId,{...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))}),n=this.cfRules[e.sheetId]?.find(t=>t.id===e.cf.id);return n&&T(t,n)?`NoChanges`:`Success`}checkOperatorArgsNumber(e){let t=X.get(e.operator).numberOfValues({type:e.operator,values:e.values});if(t===void 0||t>2)throw Error(`Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.`);let n=[],r=e=>e===void 0||e===``;return t>=1&&r(e.values[0])&&n.push(`FirstArgMissing`),t>=2&&r(e.values[1])&&n.push(`SecondArgMissing`),n.length?n:`Success`}checkNaN(e,t){if([`number`,`percentage`,`percentile`].includes(e.type)&&(e.value===``||isNaN(e.value)))switch(t){case`min`:return`MinNaN`;case`max`:return`MaxNaN`;case`mid`:return`MidNaN`;case`upperInflectionPoint`:return`ValueUpperInflectionNaN`;case`lowerInflectionPoint`:return`ValueLowerInflectionNaN`}return`Success`}checkFormulaCompilation(e,t){if(e.type!==`formula`)return`Success`;if(Rc.IsBadExpression(e.value||``))switch(t){case`min`:return`MinInvalidFormula`;case`max`:return`MaxInvalidFormula`;case`mid`:return`MidInvalidFormula`;case`upperInflectionPoint`:return`ValueUpperInvalidFormula`;case`lowerInflectionPoint`:return`ValueLowerInvalidFormula`}return`Success`}checkThresholds(e){return this.batchValidations(t=>e(t.minimum,`min`),t=>e(t.maximum,`max`),t=>t.midpoint?e(t.midpoint,`mid`):`Success`)}checkInflectionPoints(e){return this.batchValidations(t=>e(t.lowerInflectionPoint,`lowerInflectionPoint`),t=>e(t.upperInflectionPoint,`upperInflectionPoint`))}checkLowerBiggerThanUpper(e){let t=e.lowerInflectionPoint.value,n=e.upperInflectionPoint.value;return[`number`,`percentage`,`percentile`].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(n)?`LowerBiggerThanUpper`:`Success`}checkMinBiggerThanMax(e){let t=e.minimum.value,n=e.maximum.value;return[`number`,`percentage`,`percentile`].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&jI(t)>=jI(n)?`MinBiggerThanMax`:`Success`}checkMidBiggerThanMax(e){let t=e.midpoint?.value,n=e.maximum.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&jI(t)>=jI(n)?`MidBiggerThanMax`:`Success`}checkMinBiggerThanMid(e){let t=e.minimum.value,n=e.midpoint?.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&jI(t)>=jI(n)?`MinBiggerThanMid`:`Success`}checkCFValues(e){for(let t of e.values)if(t.startsWith(`=`)&&Rc.IsBadExpression(t))return`ValueCellIsInvalidFormula`;return`Success`}removeConditionalFormatting(e,t){let n=this.cfRules[t].findIndex(t=>t.id===e);if(n!==-1){let e=this.cfRules[t].slice();e.splice(n,1),this.history.update(`cfRules`,t,e)}}changeCFPriority(e,t,n){let r=this.cfRules[n].findIndex(t=>t.id===e),i=this.cfRules[n][r],a=r-t,o=[...this.cfRules[n]];o.splice(r,1),o.splice(a,0,i),this.history.update(`cfRules`,n,o)}},NI=class extends SI{static getters=[`cellHasListDataValidationIcon`,`getDataValidationRule`,`getDataValidationRules`,`getValidationRuleForCell`];rules={};adaptRanges(e){for(let t in this.rules)this.adaptDVRanges(t,e);this.adaptDVFormulas(e)}adaptDVFormulas({adaptFormulaString:e}){for(let t in this.rules){let n=this.rules[t];for(let r=n.length-1;r>=0;r--){let n=this.rules[t][r];for(let i=0;i<n.criterion.values.length;i++){let a=e(t,n.criterion.values[i]);this.history.update(`rules`,t,r,`criterion`,`values`,i,a)}}}}adaptDVRanges(e,{applyChange:t}){let n=this.rules[e];for(let r=n.length-1;r>=0;r--){let n=this.rules[e][r];for(let i=n.ranges.length-1;i>=0;i--){let a=n.ranges[i],o=t(a);switch(o.changeType){case`REMOVE`:if(n.ranges.length===1)this.removeDataValidationRule(e,n.id);else{let t=n.ranges.slice();t.splice(i,1),this.history.update(`rules`,e,r,`ranges`,t)}break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`rules`,e,r,`ranges`,i,o.range);break}}}}allowDispatch(e){switch(e.type){case`ADD_DATA_VALIDATION_RULE`:return!this.getters.tryGetSheet(e.sheetId)||e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkValidations(e,this.chainValidations(this.checkEmptyRange,this.checkValidRange,this.checkCriterionTypeIsValid,this.checkCriterionHasValidNumberOfValues,this.checkCriterionValuesAreValid));case`REMOVE_DATA_VALIDATION_RULE`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;if(!this.rules[e.sheetId].find(t=>t.id===e.id))return`UnknownDataValidationRule`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`rules`,e.sheetId,[]);break;case`DUPLICATE_SHEET`:{let t=x(this.rules[e.sheetId]).map(t=>({...t,ranges:t.ranges.map(t=>tc(e.sheetId,e.sheetIdTo,t))}));this.history.update(`rules`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.rules};delete t[e.sheetId],this.history.update(`rules`,t);break}case`REMOVE_DATA_VALIDATION_RULE`:this.removeDataValidationRule(e.sheetId,e.id);break;case`ADD_DATA_VALIDATION_RULE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e));this.addDataValidationRule(e.sheetId,{...e.rule,ranges:t});break}case`DELETE_CONTENT`:{let t=cn(e.target),n=e.sheetId;for(let e of t)for(let t=e.top;t<=e.bottom;t++)for(let r=e.left;r<=e.right;r++){let e=this.getValidationRuleForCell({sheetId:n,col:r,row:t});if(!e)continue;let i=this.getters.getCell({sheetId:n,col:r,row:t});if(e.criterion.type===`isBoolean`||e.criterion.type===`isValueInList`&&!i?.isFormula&&!i?.content){let e=this.rules[n],i=[this.getters.getRangeFromSheetXC(n,E(r,t))],a=this.removeRangesFromRules(n,i,e);this.history.update(`rules`,n,a)}}}}}getDataValidationRules(e){return this.rules[e]}getDataValidationRule(e,t){return this.rules[e].find(e=>e.id===t)}getValidationRuleForCell({sheetId:e,col:t,row:n}){if(this.rules[e]){for(let r of this.rules[e])for(let e of r.ranges)if(Fn(t,n,e.zone))return r}}cellHasListDataValidationIcon(e){let t=this.getValidationRuleForCell(e);return t?(t.criterion.type===`isValueInList`||t.criterion.type===`isValueInRange`)&&(t.criterion.displayStyle===`arrow`||t.criterion.displayStyle===`chip`):!1}addDataValidationRule(e,t){let n=this.rules[e];t.criterion.type===`isBoolean`?this.setCenterStyleToBooleanCells(t):t.criterion.type===`isValueInList`&&(t.criterion.values=Array.from(new Set(t.criterion.values)));let r=this.removeRangesFromRules(e,t.ranges,n,t.id),i=r.findIndex(e=>e.id===t.id);i===-1?this.history.update(`rules`,e,[...r,t]):(r[i]=t,this.history.update(`rules`,e,r))}removeRangesFromRules(e,t,n,r){n=x(n);for(let e of n)e.id!==r&&(e.ranges=this.getters.recomputeRanges(e.ranges,t));return n.filter(e=>e.ranges.length>0)}removeDataValidationRule(e,t){let n=this.rules[e].filter(e=>e.id!==t);this.history.update(`rules`,e,n)}setCenterStyleToBooleanCells(e){for(let t of rc(e.ranges)){let e=this.getters.getCell(t),n={...e?.style,align:e?.style?.align??`center`,verticalAlign:e?.style?.verticalAlign??`middle`};this.dispatch(`UPDATE_CELL`,{...t,style:n})}}checkEmptyRange(e){return e.ranges.length?`Success`:`EmptyRange`}import(e){for(let t of e.sheets)if(this.rules[t.id]=[],t.dataValidationRules)for(let e of t.dataValidationRules)this.rules[t.id].push({...e,ranges:e.ranges.map(e=>this.getters.getRangeFromSheetXC(t.id,e))})}export(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id])t.dataValidationRules.push({...e,ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id))})}}exportForExcel(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id]){let n={...x(e),ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id,{useBoundedReference:!0}))};e.criterion.type===`isValueInRange`&&(n.criterion.values=e.criterion.values.map(e=>{let n=this.getters.getRangeFromSheetXC(t.id,e);return this.getters.getRangeString(n,t.id,{useBoundedReference:!0,useFixedReference:!0})})),t.dataValidationRules.push(n)}}}checkCriterionTypeIsValid(e){return X.contains(e.rule.criterion.type)?`Success`:`UnknownDataValidationCriterionType`}checkCriterionHasValidNumberOfValues(e){let t=e.rule.criterion,n=X.get(t.type).numberOfValues(t);return n!==void 0&&t.values.length!==n?`InvalidNumberOfCriterionValues`:`Success`}checkCriterionValuesAreValid(e){let t=e.rule.criterion,n=X.get(t.type);return t.values.some(e=>n.allowedValues===`onlyFormulas`&&!e.startsWith(`=`)?!0:e.startsWith(`=`)?n.allowedValues===`onlyLiterals`||Rc.IsBadExpression(e):!n.isCriterionValueValid(e))?`InvalidDataValidationCriterionValue`:`Success`}checkValidRange(e){return e.ranges.map(e=>this.getters.getRangeFromRangeData(e)).map(t=>this.getters.getRangeString(t,e.sheetId)).some(e=>!this.getters.isRangeValid(e))?`InvalidRange`:`Success`}},PI=class extends SI{static getters=[`getFigures`,`getFigure`,`getFigureSheetId`];figures={};insertionOrders=[];adaptRanges(e){for(let t in this.figures)this.adaptRangesOnSheet(e,t)}adaptRangesOnSheet({applyChange:e},t){for(let n of this.getFigures(t)){let r=e(this.getters.getRangeFromZone(t,{left:n.col,right:n.col,top:n.row,bottom:n.row}));if(r.changeType===`MOVE`)this.history.update(`figures`,t,n.id,`col`,r.range.zone.right),this.history.update(`figures`,t,n.id,`row`,r.range.zone.bottom);else if(r.changeType===`REMOVE`){let r=e(this.getters.getRangeFromZone(t,{left:0,right:n.col-1,top:0,bottom:n.row-1})),{offset:i,col:a,row:o}=n;r.changeType!==`NONE`&&(a=r.range.zone.right+1,o=r.range.zone.bottom+1),{offset:i,col:a,row:o}=this.getPositionInSheet(t,{...n,col:a,row:o}),this.history.update(`figures`,t,n.id,`offset`,i),this.history.update(`figures`,t,n.id,`col`,a),this.history.update(`figures`,t,n.id,`row`,o)}}}allowDispatch(e){switch(e.type){case`CREATE_FIGURE`:return this.checkValidations(e,this.checkFigureDuplicate,this.checkFigureAnchorOffset);case`UPDATE_FIGURE`:return this.checkValidations(e,this.checkFigureExists,this.checkFigureAnchorOffset);case`DELETE_FIGURE`:return this.checkFigureExists(e);default:return`Success`}}beforeHandle(e){switch(e.type){case`DELETE_SHEET`:this.getters.getFigures(e.sheetId).forEach(t=>{this.dispatch(`DELETE_FIGURE`,{figureId:t.id,sheetId:e.sheetId})});break}}handle(e){switch(e.type){case`CREATE_SHEET`:this.figures[e.sheetId]={};break;case`DELETE_SHEET`:this.deleteSheet(e.sheetId);break;case`CREATE_FIGURE`:let t={id:e.figureId,col:e.col,row:e.row,offset:e.offset,width:e.size.width,height:e.size.height,tag:e.tag};this.addFigure(t,e.sheetId);break;case`UPDATE_FIGURE`:this.updateFigure(e);break;case`DELETE_FIGURE`:this.removeFigure(e.figureId,e.sheetId);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.onColRemove(e.sheetId):this.onRowRemove(e.sheetId);break;case`DUPLICATE_SHEET`:for(let t of this.getFigures(e.sheetId)){let n=t.id,r=this.figures[e.sheetId]?.[n];if(!r)continue;let i=n.split(`??`).pop(),a=`${e.sheetIdTo}??${i}`;this.dispatch(`CREATE_FIGURE`,{figureId:a,...r,size:{width:r.width,height:r.height},sheetId:e.sheetIdTo})}break}}onColRemove(e){let t=this.getters.getNumberCols(e),n=Array(t+1);n[t]=0;for(let r=t-1;r>=0;r--)n[r]=n[r+1]+this.getters.getColSize(e,r);for(let t of this.getFigures(e))if(t.offset.x+t.width>n[t.col]){let r=t.offset.x,i=t.col;for(r=Math.min(r,n[i]-t.width);r<0&&i>0;)i--,r=n[i]-t.width;r!==t.offset.x&&this.history.update(`figures`,e,t.id,`offset`,{x:Math.max(r,0),y:t.offset.y}),i!==t.col&&this.history.update(`figures`,e,t.id,`col`,i)}}onRowRemove(e){let t=this.getters.getNumberRows(e),n=Array(t+1);n[t]=0;for(let r=t-1;r>=0;r--)n[r]=n[r+1]+(this.getters.getUserRowSize(e,r)??23);for(let t of this.getFigures(e))if(t.offset.y+t.height>n[t.row]){let r=t.offset.y,i=t.row;for(let t=this.getters.getUserRowSize(e,i)??23;t<r;t=this.getters.getUserRowSize(e,i)??23)i+=1,r-=t;for(r=Math.min(r,n[i]-t.height);r<0&&i>0;)i--,r=n[i]-t.height;r!==t.offset.y&&this.history.update(`figures`,e,t.id,`offset`,{x:t.offset.x,y:Math.max(0,r)}),i!==t.row&&this.history.update(`figures`,e,t.id,`row`,i)}else t.offset.y+t.height>n[0]&&this.history.update(`figures`,e,t.id,`offset`,{x:t.offset.x,y:Math.max(n[0]-t.height,0)})}getPositionInSheet(e,t){let{numberOfRows:n,numberOfCols:r}=this.getters.getSheetSize(e),i=0,a=0,o,s,{col:c,row:l}=t,u={...t.offset};for(o=n;i<t.height&&o>0;o--)i+=this.getters.getUserRowSize(e,o-1)??23;for(l>o?(l=o,u.y=Math.max(i-t.height,0)):l===o&&(u.y=S(u.y,0,Math.max(i-t.height,0))),s=r;a<t.width&&s>0;s--)a+=this.getters.getColSize(e,s-1);return c>s?(c=s,u.x=Math.max(a-t.width,0)):s===c&&(u.x=S(u.x,0,Math.max(a-t.width,0))),{col:c,row:l,offset:u}}updateFigure(e){if(!(`figureId`in e)||!(`sheetId`in e))return;let{figureId:t,sheetId:n,...r}=e,i={...this.getFigure(n,t),...r};for(let[e,t]of Object.entries(r))switch(e){case`tag`:this.history.update(`figures`,n,i.id,e,t);break;case`offset`:this.history.update(`figures`,n,i.id,e,t);break;case`col`:case`row`:case`width`:case`height`:t!==void 0&&this.history.update(`figures`,n,i.id,e,t);break}}addFigure(e,t){this.history.update(`figures`,t,e.id,e),this.history.update(`insertionOrders`,this.insertionOrders.length,e.id)}deleteSheet(e){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>!this.figures[e]?.[t])),this.history.update(`figures`,e,void 0)}removeFigure(e,t){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>t!==e)),this.history.update(`figures`,t,e,void 0)}checkFigureExists(e){return this.figures[e.sheetId]?.[e.figureId]===void 0?`FigureDoesNotExist`:`Success`}checkFigureDuplicate(e){return Object.values(this.figures).find(t=>t?.[e.figureId])?`DuplicatedFigureId`:`Success`}checkFigureAnchorOffset(e){return e.col<0||e.row<0||e.offset&&(e.offset.x<0||e.offset.y<0)?`WrongSheetPosition`:`Success`}getFigures(e){let t=[];for(let n of this.insertionOrders){let r=this.figures[e]?.[n];r&&t.push(r)}return t}getFigure(e,t){return this.figures[e]?.[t]}getFigureSheetId(e){return Object.keys(this.figures).find(t=>this.figures[t]?.[e]!==void 0)}import(e){for(let t of e.sheets)for(let e of t.figures)this.addFigure(e,t.id)}export(e){for(let t of e.sheets)for(let e of this.getFigures(t.id))t.figures.push({...e,data:void 0})}exportForExcel(e){return this.export(e)}},FI=class extends SI{static getters=[`getHeaderGroups`,`getGroupsLayers`,`getVisibleGroupLayers`,`getHeaderGroup`,`getHeaderGroupsInZone`,`isGroupFolded`,`isRowFolded`,`isColFolded`];groups={};allowDispatch(e){switch(e.type){case`GROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;if(this.findGroupWithStartEnd(e.sheetId,e.dimension,t,n))return`HeaderGroupAlreadyExists`;break}case`UNGROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;break}case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUP`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);if(!t)return`UnknownHeaderGroup`;if(C(0,this.getters.getNumberHeaders(e.sheetId,e.dimension)).every(n=>n>=t.start&&n<=t.end||this.getters.isHeaderHiddenByUser(e.sheetId,e.dimension,n)))return`NotEnoughElements`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`groups`,e.sheetId,{ROW:[],COL:[]});break;case`GROUP_HEADERS`:this.groupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`UNGROUP_HEADERS`:this.unGroupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`DUPLICATE_SHEET`:{let t=x(this.groups[e.sheetId]);this.history.update(`groups`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.groups};delete t[e.sheetId],this.history.update(`groups`,t);break}case`ADD_COLUMNS_ROWS`:let t=Ct(e.position,e.base);this.moveGroupsOnHeaderInsertion(e.sheetId,e.dimension,t,e.quantity);break;case`REMOVE_COLUMNS_ROWS`:this.moveGroupsOnHeaderDeletion(e.sheetId,e.dimension,e.elements);break;case`UNFOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.unfoldHeaderGroup(e.sheetId,e.dimension,t);break}case`FOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.foldHeaderGroup(e.sheetId,e.dimension,t);break}case`UNFOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.unfoldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.foldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:{let t=e.type===`UNFOLD_HEADER_GROUPS_IN_ZONE`?`unfold`:`fold`,n=this.getGroupsLayers(e.sheetId,e.dimension);t===`fold`&&n.reverse();let r=n.flat(),i=e.dimension===`ROW`?e.zone.top:e.zone.left,a=e.dimension===`ROW`?e.zone.bottom:e.zone.right,o=new Set;for(let e=i;e<=a;e++){let n=r.filter(t=>t.start-1<=e&&e<=t.end);for(let e of n)if(!(t===`fold`&&e.isFolded||t===`unfold`&&!e.isFolded)){o.add(e);break}}for(let n of o)t===`unfold`?this.unfoldHeaderGroup(e.sheetId,e.dimension,n):this.foldHeaderGroup(e.sheetId,e.dimension,n);break}}}getHeaderGroups(e,t){return this.groups[e][t]}getHeaderGroup(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}getHeaderGroupsInZone(e,t,n){return this.getHeaderGroups(e,t).filter(e=>{let r=t===`ROW`?n.top:n.left,i=t===`ROW`?n.bottom:n.right;return this.doGroupOverlap(e,r,i)})}getGroupsLayers(e,t){let n=this.getHeaderGroups(e,t);return this.bricksFallingAlgorithm(n,0,0)}getVisibleGroupLayers(e,t){let n=this.getGroupsLayers(e,t);for(let r of n)for(let n=r.length-1;n>=0;n--){let i=r[n];i.start!==0&&C(i.start-1,i.end+1).every(n=>this.getters.isHeaderHiddenByUser(e,t,n))&&r.splice(n,1)}return n.filter(e=>e.length>0)}isGroupFolded(e,t,n,r){return this.getHeaderGroup(e,t,n,r)?.isFolded||!1}isRowFolded(e,t){return this.getters.getHeaderGroups(e,`ROW`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}isColFolded(e,t){return this.getters.getHeaderGroups(e,`COL`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}getGroupId(e){return`${e.start}-${e.end}}`}bricksFallingAlgorithm(e,t,n,r=0){let i={};for(let t of e)i[this.getGroupId(t)]=t.isFolded;let a={};for(let t of e)for(let e=t.start;e<=t.end;e++)a[e]=a[e]?a[e]+1:1;for(let e=t;e<=n;e++)a[e]=a[e]?a[e]+r:r;let o=Math.max(...Object.values(a),0),s=Array.from({length:o},()=>[]),c=Math.max(n,...e.map(e=>e.end)),l=Math.min(t,...e.map(e=>e.start));for(let e=l;e<=c;e++){let t=a[e]||0;for(let n=0;n<t;n++){let t=s[n].at(-1);if(t&&Nt([t.end,e]))t.end++;else{let t={start:e,end:e};s[n].push(t)}}}for(let e of s)for(let t of e)t.isFolded=i[this.getGroupId(t)];return s}groupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}unGroupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,-1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}moveGroupsOnHeaderInsertion(e,t,n,r){let i=this.groups[e][t];for(let a=0;a<i.length;a++){let o=i[a],[s,c]=gc(n,r,[o.start,o.end]);(s!==o.start||c!==o.end)&&this.history.update(`groups`,e,t,a,{...o,start:s,end:c})}}moveGroupsOnHeaderDeletion(e,t,n){let r=this.getHeaderGroups(e,t),i=[];for(let e of r){let t=_c(n,C(e.start,e.end+1));t.length!==0&&i.push({...e,start:Math.min(...t),end:Math.max(...t)})}this.history.update(`groups`,e,t,this.bricksFallingAlgorithm(i,0,0).flat())}doGroupOverlap(e,t,n){return e.start<=n&&e.end>=t}removeDuplicateGroups(e){let t={};for(let n of e)t[this.getGroupId(n)]=n;return Object.values(t)}findGroupWithStartEnd(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}foldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!0);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end<=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!0)}}unfoldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!1);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end>=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!1)}}getGroupIndex(e,t,n,r){let i=this.groups[e][t].findIndex(e=>e.start===n&&e.end===r);return i===-1?void 0:i}import(e){for(let t of e.sheets)if(this.groups[t.id]={ROW:[],COL:[]},t.headerGroups)for(let e of[`ROW`,`COL`])for(let n of t.headerGroups[e]||[])this.groups[t.id][e].push({...n})}export(e){for(let t of e.sheets)t.headerGroups=this.groups[t.id]}exportForExcel(e){for(let t of e.sheets)for(let e of[`ROW`,`COL`]){let n=this.getGroupsLayers(t.id,e);for(let r=0;r<n.length;r++){let i=n[r];for(let n of i){for(let i=n.start;i<=n.end;i++){let a=Ib(t,e,i);a.outlineLevel=r+1,n.isFolded&&(a.isHidden=!0)}if(n.isFolded){let r=Ib(t,e,n.end+1);r.collapsed=!0}}}}}},II=class extends SI{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,x(this.sizes[e.sheetId]));break;case`DELETE_SHEET`:let t={...this.sizes};delete t[e.sheetId],this.history.update(`sizes`,t);break;case`REMOVE_COLUMNS_ROWS`:{let t=this.sizes[e.sheetId][e.dimension],n=Ft(t,e.elements);this.history.update(`sizes`,e.sheetId,e.dimension,n);break}case`ADD_COLUMNS_ROWS`:{let t=this.sizes[e.sheetId][e.dimension],n=Ct(e.position,e.base),r=t[e.base],i=It(t,Array(e.quantity).fill(r),n);this.history.update(`sizes`,e.sheetId,e.dimension,i);break}case`RESIZE_COLUMNS_ROWS`:if(e.dimension===`ROW`)for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);else for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);break}}getColSize(e,t){return Math.round(this.sizes[e]?.COL[t]||96)}getUserRowSize(e,t){let n=this.sizes[e]?.ROW[t];return n?Math.round(n):void 0}import(e){for(let t of e.sheets){let e={COL:Array(t.colNumber).fill(void 0),ROW:Array(t.rowNumber).fill(void 0)};for(let[n,r]of Object.entries(t.rows))r.size&&(e.ROW[n]=r.size);for(let[n,r]of Object.entries(t.cols))r.size&&(e.COL[n]=r.size);this.sizes[t.id]=e}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e of C(0,this.getters.getNumberRows(n.id)))(t||this.sizes[n.id].ROW[e])&&(n.rows[e]={...n.rows[e],size:this.getUserRowSize(n.id,e)??23});n.cols===void 0&&(n.cols={});for(let e of C(0,this.getters.getNumberCols(n.id)))(t||this.sizes[n.id].COL[e])&&(n.cols[e]={...n.cols[e],size:this.getColSize(n.id,e)})}}},LI=class extends SI{static getters=[`checkElementsIncludeAllVisibleHeaders`,`getHiddenColsGroups`,`getHiddenRowsGroups`,`isHeaderHiddenByUser`,`isRowHiddenByUser`,`isColHiddenByUser`];hiddenHeaders={};allowDispatch(e){switch(e.type){case`HIDE_COLUMNS_ROWS`:{if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=e.dimension===`COL`?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),n=e.dimension===`COL`?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=n?`TooManyHiddenElements`:Ht(e.elements)<0||Vt(e.elements)>n?`InvalidHeaderIndex`:`Success`}case`REMOVE_COLUMNS_ROWS`:return this.getters.tryGetSheet(e.sheetId)?this.checkElementsIncludeAllVisibleHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`:`InvalidSheetId`}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:let t={COL:Array(this.getters.getNumberCols(e.sheetId)).fill(!1),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(!1)};this.history.update(`hiddenHeaders`,e.sheetId,t);break;case`DUPLICATE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetIdTo,x(this.hiddenHeaders[e.sheetId]));break;case`DELETE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetId,void 0);break;case`REMOVE_COLUMNS_ROWS`:{let t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(let n of[...e.elements].sort((e,t)=>t-e))t.splice(n,1);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t);break}case`ADD_COLUMNS_ROWS`:{let t=Ct(e.position,e.base),n=It([...this.hiddenHeaders[e.sheetId][e.dimension]],Array(e.quantity).fill(!1),t);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,n);break}case`HIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!0);break;case`UNHIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!1);break}}checkElementsIncludeAllVisibleHeaders(e,t,n){return Et(n,this.getAllVisibleHeaders(e,t))}isHeaderHiddenByUser(e,t,n){return t===`COL`?this.isColHiddenByUser(e,n):this.isRowHiddenByUser(e,n)}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]||this.getters.isRowFolded(e,t)}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]||this.getters.isColFolded(e,t)}getHiddenColsGroups(e){let t=[[]],n=this.hiddenHeaders[e].COL;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getHiddenRowsGroups(e){let t=[[]],n=this.hiddenHeaders[e].ROW;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getAllVisibleHeaders(e,t){let n=C(0,this.getters.getNumberHeaders(e,t)),r=[];return this.getters.getHeaderGroups(e,t).forEach(e=>{e.isFolded&&r.push(...C(e.start,e.end+1))}),n.filter(n=>!this.hiddenHeaders[e][t][n]&&!r.includes(n))}import(e){for(let t of e.sheets){this.hiddenHeaders[t.id]={COL:[],ROW:[]};for(let e=0;e<t.rowNumber;e++)this.hiddenHeaders[t.id].ROW[e]=!!t.rows[e]?.isHidden;for(let e=0;e<t.colNumber;e++)this.hiddenHeaders[t.id].COL[e]=!!t.cols[e]?.isHidden}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e=0;e<this.getters.getNumberRows(n.id);e++)(t||this.hiddenHeaders[n.id].ROW[e])&&(n.rows[e]===void 0&&(n.rows[e]={}),n.rows[e].isHidden||=this.hiddenHeaders[n.id].ROW[e]);n.cols===void 0&&(n.cols={});for(let e=0;e<this.getters.getNumberCols(n.id);e++)(t||this.hiddenHeaders[n.id].COL[e])&&(n.cols[e]===void 0&&(n.cols[e]={}),n.cols[e].isHidden||=this.hiddenHeaders[n.id].COL[e])}}},RI=class extends SI{static getters=[`getImage`,`getImagePath`,`getImageSize`];fileStore;images={};syncedImages=new Set;constructor(e){super(e),this.fileStore=e.external.fileStore}allowDispatch(e){switch(e.type){case`CREATE_IMAGE`:return this.getters.getFigure(e.sheetId,e.figureId)?`InvalidFigureId`:`Success`;default:return`Success`}}handle(e){switch(e.type){case`CREATE_IMAGE`:this.getters.getFigure(e.sheetId,e.figureId)||this.addFigure(e.figureId,e.sheetId,e.col,e.row,e.offset,e.size),this.history.update(`images`,e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`image`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.getImage(n.id);if(i){let t={width:n.width,height:n.height};this.dispatch(`CREATE_IMAGE`,{sheetId:e.sheetIdTo,figureId:r,offset:n.offset,col:n.col,row:n.row,size:t,definition:x(i)})}}break}case`DELETE_FIGURE`:this.history.update(`images`,e.sheetId,e.figureId,void 0);break;case`DELETE_SHEET`:this.history.update(`images`,e.sheetId,void 0);break}}getImage(e){for(let t of Object.values(this.images))if(t&&t[e])return t[e];throw Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addFigure(e,t,n,r,i,a){this.dispatch(`CREATE_FIGURE`,{sheetId:t,figureId:e,col:n,row:r,offset:i,size:a,tag:`image`})}import(e){for(let t of e.sheets){let e=(t.figures||[]).filter(e=>e.tag===`image`);for(let n of e)this.history.update(`images`,t.id,n.id,n.data),this.syncedImages.add(n.data.path)}}export(e){for(let t of e.sheets){let e=t.figures.filter(e=>e.tag===`image`);for(let n of e)n.data=this.images[t.id]?.[n.id]}}exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let t of e)if(t?.tag===`image`){let e=this.getImage(t.id);e&&n.push({...t,data:x(e)})}t.images=[...t.images,...n]}}},zI=class extends SI{static getters=[`isInMerge`,`isInSameMerge`,`isMergeHidden`,`getMainCellPosition`,`expandZone`,`doesIntersectMerge`,`doesColumnsHaveCommonMerges`,`doesRowsHaveCommonMerges`,`getMerges`,`getMerge`,`getMergesInZone`,`isSingleCellOrMerge`,`isMainCellPosition`];nextId=1;merges={};mergeCellMap={};allowDispatch(e){let t=`force`in e?!!e.force:!1;switch(e.type){case`ADD_MERGE`:return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case`UPDATE_CELL`:return this.checkMergedContentUpdate(e);case`REMOVE_MERGE`:return this.checkMergeExists(e);default:return`Success`}}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DELETE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DUPLICATE_SHEET`:let t=this.merges[e.sheetId];if(!t)break;for(let n of Object.values(t).filter(w))this.addMerge(e.sheetIdTo,n.zone);break;case`ADD_MERGE`:for(let t of e.target)this.addMerge(e.sheetId,t);break;case`REMOVE_MERGE`:for(let t of e.target)this.removeMerge(e.sheetId,t);break}}adaptRanges(e){for(let t in this.merges)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map(t=>this.getMergeById(e,parseInt(t,10))).filter(w)}getMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e],i=r?t in r&&r[t]?.[n]:void 0;return i?this.getMergeById(e,i):void 0}getMergesInZone(e,t){let n=this.mergeCellMap[e];if(!n)return[];let r=new Set;for(let e=t.left;e<=t.right;e++)for(let i=t.top;i<=t.bottom;i++){let t=n[e]?.[i];t&&r.add(t)}return Array.from(r).map(t=>this.getMergeById(e,t)).filter(w)}doesIntersectMerge(e,t){for(let n of this.getMerges(e))if(Nn(t,n))return!0;return!1}doesColumnsHaveCommonMerges(e,t,n){let r=this.getters.getSheet(e);for(let i=0;i<this.getters.getNumberRows(e);i++)if(this.isInSameMerge(r.id,t,i,n,i))return!0;return!1}doesRowsHaveCommonMerges(e,t,n){let r=this.getters.getSheet(e);for(let i=0;i<=this.getters.getNumberCols(e);i++)if(this.isInSameMerge(r.id,i,t,i,n))return!0;return!1}expandZone(e,t){let{left:n,right:r,top:i,bottom:a}=t,o={left:n,right:r,top:i,bottom:a};for(let t in this.merges[e]){let n=this.getMergeById(e,parseInt(t));n&&Nn(n,o)&&(o=kn(n,o))}return Mn(o,t)?o:this.expandZone(e,o)}isInSameMerge(e,t,n,r,i){let a=this.getMerge({sheetId:e,col:t,row:n}),o=this.getMerge({sheetId:e,col:r,row:i});return!a||!o?!1:Mn(a,o)}isInMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e];return r?t in r&&!!r[t]?.[n]:!1}getMainCellPosition(e){let t=this.getMerge(e);return t?{sheetId:e.sheetId,col:t.left,row:t.top}:e}isMergeHidden(e,t){let n=this.getters.getHiddenColsGroups(e),r=this.getters.getHiddenRowsGroups(e);for(let e of n)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of r)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){let n=this.getMerge({sheetId:e,col:t.left,row:t.top});if(n)return Mn(t,n);let{numberOfCols:r,numberOfRows:i}=Ln(t);return r===1&&i===1}isMainCellPosition(e){return T(this.getMainCellPosition(e),e)}isMergeDestructive(e,t){let{left:n,right:r,top:i,bottom:a}=t;r=S(r,0,this.getters.getNumberCols(e)-1),a=S(a,0,this.getters.getNumberRows(e)-1);for(let t=i;t<=a;t++)for(let a=n;a<=r;a++)if(a!==n||t!==i){let n=this.getters.getCell({sheetId:e,col:a,row:t});if(n&&(n.isFormula||n.content!==``))return!0}return!1}getMergeById(e,t){let n=this.merges[e]?.[t];return n===void 0?void 0:VI(t,n)}checkDestructiveMerge({sheetId:e,target:t}){return this.getters.tryGetSheet(e)&&t.some(t=>this.isMergeDestructive(e,t))?`MergeIsDestructive`:`Success`}checkOverlap({target:e}){for(let t of e)for(let n of e)if(t!==n&&Nn(t,n))return`MergeOverlap`;return`Success`}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return`Success`;let{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(e);return Qn(t,n,r)?`FrozenPaneOverlap`:`Success`}checkMergedContentUpdate(e){let{col:t,row:n,content:r}=e;if(r===void 0)return`Success`;let{col:i,row:a}=this.getMainCellPosition(e);return i===t&&a===n?`Success`:`CellIsMerged`}checkMergeExists(e){let{sheetId:t,target:n}=e;for(let e of n){let{left:n,top:r}=e,i=this.getMerge({sheetId:t,col:n,row:r});if(i===void 0||!Mn(e,i))return`InvalidTarget`}return`Success`}addMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t;if(r=S(r,0,this.getters.getNumberCols(e)-1),a=S(a,0,this.getters.getNumberRows(e)-1),E(n,i)===E(r,a))return;let o=this.getters.getCell({sheetId:e,col:n,row:i}),s=this.nextId++;this.history.update(`merges`,e,s,this.getters.getRangeFromSheetXC(e,wn({left:n,top:i,right:r,bottom:a})));let c=new Set;for(let t=i;t<=a;t++)for(let a=n;a<=r;a++){(a!==n||t!==i)&&this.dispatch(`UPDATE_CELL`,{sheetId:e,col:a,row:t,style:o?o.style:null,content:``});let r=this.getMerge({sheetId:e,col:a,row:t});r&&c.add(r.id),this.history.update(`mergeCellMap`,e,a,t,s)}for(let t of c){let{top:n,bottom:r,left:i,right:a}=this.getMergeById(e,t);for(let t=n;t<=r;t++)for(let n=i;n<=a;n++){let r={sheetId:e,col:n,row:t},i=this.getMerge(r);(!i||i.id!==s)&&(this.history.update(`mergeCellMap`,e,n,t,void 0),this.dispatch(`CLEAR_CELL`,r))}this.history.update(`merges`,e,t,void 0)}}removeMerge(e,t){let{left:n,top:r,bottom:i,right:a}=t,o=this.getMerge({sheetId:e,col:n,row:r});if(!(o===void 0||!Mn(t,o))){this.history.update(`merges`,e,o.id,void 0);for(let t=r;t<=i;t++)for(let r=n;r<=a;r++)this.history.update(`mergeCellMap`,e,r,t,void 0)}}applyRangeChangeOnSheet(e,{applyChange:t}){let n=Object.entries(this.merges[e]||{});for(let[r,i]of n)if(i){let n=i.zone,a=t(i);switch(a.changeType){case`NONE`:break;case`REMOVE`:this.removeMerge(e,n);break;default:let{numberOfCols:t,numberOfRows:i}=Ln(a.range.zone);t===1&&i===1?this.removeMerge(e,n):this.history.update(`merges`,e,parseInt(r,10),a.range);break}}this.history.update(`mergeCellMap`,e,{});for(let t of this.getMerges(e))for(let{col:n,row:r}of Bn(t))this.history.update(`mergeCellMap`,e,n,r,t.id)}import(e){let t=e.sheets||[];for(let e of t)this.history.update(`merges`,e.id,{}),this.history.update(`mergeCellMap`,e.id,{}),e.merges&&this.importMerges(e.id,e.merges)}importMerges(e,t){for(let n of t)this.addMerge(e,yn(n))}export(e){for(let t of e.sheets){let e=this.merges[t.id];e&&t.merges.push(...BI(e))}}exportForExcel(e){this.export(e)}};function BI(e){return Object.entries(e).map(([e,t])=>t?VI(parseInt(e,10),t):void 0).filter(w).map(e=>E(e.left,e.top)+`:`+E(e.right,e.bottom))}function VI(e,t){return{...t.zone,id:e}}let HI=/^[\p{L}\p{N}_.]+$/u;var UI=class extends SI{static getters=[`getNamedRange`,`getNamedRangeFromZone`,`getNamedRanges`];namedRanges=[];adaptRanges({applyChange:e}){let t=[],n=!1;for(let r of this.namedRanges){let i=e(r.range);switch(i.changeType){case`REMOVE`:n=!0;break;case`RESIZE`:case`MOVE`:case`CHANGE`:n=!0,t.push({...r,range:i.range});break;case`NONE`:t.push(r)}}n&&this.history.update(`namedRanges`,t)}allowDispatch(e){switch(e.type){case`CREATE_NAMED_RANGE`:return this.checkValidNewNamedRangeName(e.name);case`UPDATE_NAMED_RANGE`:return this.checkValidations(e,()=>this.checkNamedRangeExists(e.oldRangeName),()=>e.newRangeName===e.oldRangeName?`Success`:this.checkValidNewNamedRangeName(e.newRangeName));case`DELETE_NAMED_RANGE`:return this.checkNamedRangeExists(e.name)}return`Success`}handle(e){switch(e.type){case`CREATE_NAMED_RANGE`:{let t=this.getters.getRangeFromRangeData(e.ranges[0]),n=[...this.namedRanges,{name:e.name,range:t}];this.history.update(`namedRanges`,n);break}case`UPDATE_NAMED_RANGE`:{let t=this.getNamedRangeIndex(e.oldRangeName);if(t!==-1){let n=this.getters.getRangeFromRangeData(e.ranges[0]);this.history.update(`namedRanges`,t,{name:e.newRangeName,range:n})}break}case`DELETE_NAMED_RANGE`:{let t=this.getNamedRangeIndex(e.name);if(t!==-1){let e=[...this.namedRanges];e.splice(t,1),this.history.update(`namedRanges`,e)}break}}}getNamedRange(e){return this.namedRanges[this.getNamedRangeIndex(e)]}getNamedRangeFromZone(e,t){for(let n of this.namedRanges){let r=n.range;if(r.sheetId===e&&T(r.unboundedZone,t))return n}}getNamedRanges(){return this.namedRanges}getNamedRangeIndex(e){return this.namedRanges.findIndex(t=>t&&t.name.toLowerCase()===e.toLowerCase())}import(e){for(let t in e.namedRanges||{})this.namedRanges.push({name:t,range:this.getters.getRangeFromSheetXC(void 0,e.namedRanges[t])})}export(e){e.namedRanges={};for(let t of this.namedRanges){let n=this.getters.getRangeString(t.range);e.namedRanges[t.name]=n}}checkValidNewNamedRangeName(e){return this.getNamedRange(e)?`NamedRangeNameAlreadyExists`:!HI.test(e)||Pa(e,V)||[`TRUE`,`FALSE`].includes(e.toUpperCase())?`NamedRangeInvalidName`:Uo.test(e)?`NamedRangeNameLooksLikeCellReference`:`Success`}checkNamedRangeExists(e){return this.getNamedRange(e)?`Success`:`NamedRangeNotFound`}},WI=class extends SI{static getters=[`getPivotCoreDefinition`,`getPivotDisplayName`,`getPivotId`,`getPivotFormulaId`,`getPivotIds`,`getMeasureCompiledFormula`,`getPivotName`,`isExistingPivot`,`getMeasureFullDependencies`];nextFormulaId=1;pivots={};formulaIds={};compiledMeasureFormulas={};allowDispatch(e){switch(e.type){case`ADD_PIVOT`:return e.pivotId in this.pivots?`PivotIdTaken`:this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid);case`UPDATE_PIVOT`:return e.pivotId in this.pivots?T(e.pivot,this.pivots[e.pivotId]?.definition)?`NoChanges`:e.pivot.name===``?`EmptyName`:this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid):`PivotIdNotFound`;case`RENAME_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;if(e.name===``)return`EmptyName`;break;case`REMOVE_PIVOT`:case`DUPLICATE_PIVOT`:case`INSERT_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;break;case`DUPLICATE_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`}return`Success`}handle(e){switch(e.type){case`ADD_PIVOT`:{let{pivotId:t,pivot:n}=e;this.addPivot(t,n);break}case`INSERT_PIVOT`:{let{sheetId:t,col:n,row:r,pivotId:i,table:a}=e,o={sheetId:t,col:n,row:r},{cols:s,rows:c,measures:l,fieldsType:u}=a,d=new jj(s,c,l,u||{}),f=this.getPivotFormulaId(i);this.insertPivot(o,f,d);break}case`RENAME_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,`name`,e.name);break;case`REMOVE_PIVOT`:{let t={...this.pivots};delete t[e.pivotId];let n=this.getPivotFormulaId(e.pivotId);this.history.update(`formulaIds`,n,void 0),this.history.update(`pivots`,t);break}case`DUPLICATE_PIVOT`:{let{pivotId:t,newPivotId:n}=e,r=x(this.getPivotCore(t).definition);r.name=e.duplicatedPivotName??r.name+` (copy)`,this.addPivot(n,r);break}case`UPDATE_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,x(e.pivot)),this.compileCalculatedMeasures(e.pivotId,e.pivot.measures);break;case`CREATE_NAMED_RANGE`:case`UPDATE_NAMED_RANGE`:case`DELETE_NAMED_RANGE`:for(let e in this.pivots){let t=this.pivots[e];t&&this.compileCalculatedMeasures(e,t.definition.measures)}}}adaptRanges(e){let{applyChange:t,adaptFormulaString:n}=e;for(let e in this.pivots){let n=x(this.pivots[e]?.definition);if(!n)continue;let r=Uj.get(n.type)?.adaptRanges?.(this.getters,n,t);r&&!T(n,r)&&this.history.update(`pivots`,e,`definition`,r)}for(let r in this.compiledMeasureFormulas)for(let i in this.compiledMeasureFormulas[r]){let a=this.pivots[r]?.definition.measures.find(e=>e.id===i);if(!a||!a.computedBy)continue;let o=a.computedBy.sheetId,{formula:s,dependencies:c}=this.compiledMeasureFormulas[r][i],l=e.adaptCompiledFormula(s);l!==s&&this.history.update(`compiledMeasureFormulas`,r,i,`formula`,l),this.history.update(`compiledMeasureFormulas`,r,a.id,`dependencies`,c.map(e=>t(e).range));let u=a.computedBy.formula,d=n(o,u);d!==u&&this.replaceMeasureFormula(r,a,d)}}getPivotDisplayName(e){return`(#${this.getPivotFormulaId(e)}) ${this.getPivotName(e)}`}getPivotName(e){return this.getPivotCore(e).definition.name}getPivotCoreDefinition(e){return this.getPivotCore(e).definition}getPivotId(e){return this.formulaIds[e]}getPivotFormulaId(e){return this.getPivotCore(e).formulaId}getPivotIds(){return Object.keys(this.pivots)}isExistingPivot(e){return e in this.pivots}getMeasureCompiledFormula(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].formula}getMeasureFullDependencies(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].dependencies}addPivot(e,t,n=this.nextFormulaId.toString()){this.history.update(`pivots`,e,{definition:x(t),formulaId:n}),this.compileCalculatedMeasures(e,t.measures),this.history.update(`formulaIds`,n,e),this.history.update(`nextFormulaId`,this.nextFormulaId+1)}compileCalculatedMeasures(e,t){for(let n of t)if(n.computedBy){let t=Rc.Compile(n.computedBy.formula,n.computedBy.sheetId,this.getters);this.history.update(`compiledMeasureFormulas`,e,n.id,`formula`,t)}for(let n of t)if(n.computedBy){let t=this.computeMeasureFullDependencies(e,n);this.history.update(`compiledMeasureFormulas`,e,n.id,`dependencies`,t)}}computeMeasureFullDependencies(e,t,n=new Set){let r=[],i=this.getPivotCoreDefinition(e),a=this.getMeasureCompiledFormula(e,t);n.add(t.id);for(let o of a.symbols){let a=i.measures.find(e=>tt(e.id)===o&&t.id!==e.id);!a||n.has(a.id)||!a.computedBy||r.push(...this.computeMeasureFullDependencies(e,a,n))}return r.push(...a.rangeDependencies.filter(e=>!e.invalidXc)),r.push(...a.getNamedRangesInFormula(this.getters).map(e=>e.range)),r}insertPivot(e,t,n){this.resizeSheet(e.sheetId,e,n);let r=n.getPivotCells();for(let n=0;n<r.length;n++)for(let i=0;i<r[n].length;i++){let a=r[n][i];this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col+n,row:e.row+i,content:Eg(t,a)})}}resizeSheet(e,{col:t,row:n},r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:s-l,position:`after`})}getPivotCore(e){let t=this.pivots[e];if(!t)throw Error(`Pivot with id ${e} not found`);return t}replaceMeasureFormula(e,t,n){let r=this.pivots[e];if(!r)return;let i=r.definition.measures.indexOf(t);this.history.update(`pivots`,e,`definition`,`measures`,i,`computedBy`,{formula:n,sheetId:t.computedBy.sheetId})}checkSortedColumnInMeasures(e){let t=e.measures.map(e=>e.id);return e.sortedColumn&&!t.includes(e.sortedColumn.measure)?`InvalidDefinition`:`Success`}checkDuplicatedMeasureIds(e){let t=new Set(e.measures.map(e=>e.id));return e.measures.length===t.size?`Success`:`InvalidDefinition`}checkCustomFieldsAreValid(e){for(let t in e.customFields){let n=e.customFields[t],r=new Set,i=new Set,a=!1;for(let e of n.groups){if(!e.name||i.has(e.name)||e.values.some(e=>r.has(e))||e.isOtherGroup&&a)return`InvalidPivotCustomField`;e.values.forEach(e=>r.add(e)),i.add(e.name),a||=!!e.isOtherGroup}}return`Success`}import(e){if(e.pivots)for(let[t,n]of Object.entries(e.pivots))this.addPivot(t,n,n.formulaId);this.history.update(`nextFormulaId`,e.pivotNextId||yg(this.pivots)+1)}export(e){e.pivots={};for(let t in this.pivots)e.pivots[t]={...this.getPivotCoreDefinition(t),formulaId:this.getPivotFormulaId(t)};e.pivotNextId=this.nextFormulaId}},GI=class extends SI{static getters=[`getLocale`];locale=V;allowDispatch(e){switch(e.type){case`UPDATE_LOCALE`:return Wy(e.locale)?`Success`:`InvalidLocale`}return`Success`}handle(e){switch(e.type){case`UPDATE_LOCALE`:let t=this.locale,n=e.locale;this.history.update(`locale`,n),this.changeCellsDateFormatWithLocale(t,n);break}}getLocale(){return this.locale}changeCellsDateFormatWithLocale(e,t){for(let n of this.getters.getSheetIds())for(let r of this.getters.getCells(n)){let n;if(r.format===e.dateFormat&&(n=t.dateFormat),r.format===e.timeFormat&&(n=t.timeFormat),r.format===sb(e)&&(n=sb(t)),n){let{col:e,row:t,sheetId:i}=this.getters.getCellPosition(r.id);this.dispatch(`UPDATE_CELL`,{col:e,row:t,sheetId:i,format:n})}}}import(e){this.locale=e.settings?.locale??V}export(e){e.settings={locale:this.locale}}},KI=class extends SI{static getters=`getSheetName.tryGetSheetName.getSheet.tryGetSheet.getSheetIdByName.getSheetIds.getVisibleSheetIds.isSheetVisible.doesHeaderExist.doesHeadersExist.getCell.getCellPosition.getColsZone.getRowCellIds.getRowsZone.getNumberCols.getNumberRows.getNumberHeaders.getGridLinesVisibility.getNextSheetName.getSheetSize.getSheetZone.getPaneDivisions.checkZonesExistInSheet.getCommandZones.getUnboundedZone.checkElementsIncludeAllNonFrozenHeaders.getDuplicateSheetName.tryGetCellPosition.isSheetLocked`.split(`.`);sheetIdsMapName={};orderedSheetIds=[];sheets={};cellPosition={};allowDispatch(e){let t=this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e);if(t!==`Success`)return t;let n=!1;switch(e.type){case`CREATE_SHEET`:e.name===void 0&&(n=!0);break;case`DELETE_SHEET`:case`ADD_COLUMNS_ROWS`:case`REMOVE_COLUMNS_ROWS`:case`MOVE_RANGES`:e.sheetName===void 0&&(n=!0);break}switch(n&&console.warn(`Deprecation Warning: Sheet name is missing in the command %s payload.`,e.type),e.type){case`HIDE_SHEET`:return this.getVisibleSheetIds().length===1?`NotEnoughSheets`:`Success`;case`CREATE_SHEET`:return this.checkValidations(e,this.createSheetHasName,this.checkSheetName,this.checkSheetPosition);case`DUPLICATE_SHEET`:return this.sheets[e.sheetIdTo]?`DuplicatedSheetId`:this.orderedSheetIds.map(this.getSheetName.bind(this)).includes(e.sheetNameTo)?`DuplicatedSheetName`:`Success`;case`MOVE_SHEET`:try{let t=this.orderedSheetIds.findIndex(t=>t===e.sheetId);return this.findIndexOfTargetSheet(t,e.delta),`Success`}catch{return`WrongSheetMove`}case`RENAME_SHEET`:return this.isRenameAllowed(e);case`COLOR_SHEET`:return!e.color||Pr(e.color)?`Success`:`InvalidColor`;case`DELETE_SHEET`:return this.getVisibleSheetIds().length>1?`Success`:`NotEnoughSheets`;case`ADD_COLUMNS_ROWS`:return this.doesHeaderExist(e.sheetId,e.dimension,e.base)?e.quantity<=0?`InvalidQuantity`:`Success`:`InvalidHeaderIndex`;case`REMOVE_COLUMNS_ROWS`:{let t=Ht(e.elements),n=Vt(e.elements);return t<0||!this.doesHeaderExist(e.sheetId,e.dimension,n)?`InvalidHeaderIndex`:this.checkElementsIncludeAllNonFrozenHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`}case`FREEZE_ROWS`:return this.checkValidations(e,this.checkRowFreezeQuantity,this.checkRowFreezeOverlapMerge);case`FREEZE_COLUMNS`:return this.checkValidations(e,this.checkColFreezeQuantity,this.checkColFreezeOverlapMerge);default:return`Success`}}handle(e){switch(e.type){case`SET_GRID_LINES_VISIBILITY`:this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);break;case`CREATE_SHEET`:let t=this.createSheet(e.sheetId,e.name||this.getNextSheetName(),e.cols||26,e.rows||100,e.position);this.history.update(`sheetIdsMapName`,bc(t.name),t.id);break;case`MOVE_SHEET`:this.moveSheet(e.sheetId,e.delta);break;case`RENAME_SHEET`:this.renameSheet(this.sheets[e.sheetId],e.newName);break;case`COLOR_SHEET`:this.history.update(`sheets`,e.sheetId,`color`,e.color);break;case`HIDE_SHEET`:this.hideSheet(e.sheetId);break;case`SHOW_SHEET`:this.showSheet(e.sheetId);break;case`DUPLICATE_SHEET`:this.duplicateSheet(e.sheetId,e.sheetIdTo,e.sheetNameTo);break;case`DELETE_SHEET`:this.deleteSheet(this.sheets[e.sheetId]);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case`UPDATE_CELL_POSITION`:this.updateCellPosition(e);break;case`FREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,e.quantity,`COL`);break;case`FREEZE_ROWS`:this.setPaneDivisions(e.sheetId,e.quantity,`ROW`);break;case`UNFREEZE_ROWS`:this.setPaneDivisions(e.sheetId,0,`ROW`);break;case`UNFREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,0,`COL`);break;case`UNFREEZE_COLUMNS_ROWS`:this.setPaneDivisions(e.sheetId,0,`COL`),this.setPaneDivisions(e.sheetId,0,`ROW`);break;case`LOCK_SHEET`:this.history.update(`sheets`,e.sheetId,`isLocked`,!0);break;case`UNLOCK_SHEET`:this.history.update(`sheets`,e.sheetId,`isLocked`,!1);break}}import(e){for(let t of e.sheets)this.sheetIdsMapName[bc(t.name)]=t.id;for(let t of e.sheets){let e=t.name||`Sheet`+(Object.keys(this.sheets).length+1),{colNumber:n,rowNumber:r}=this.getImportedSheetSize(t),i={id:t.id,name:e,numberOfCols:n,rows:hc(r),areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,panes:{xSplit:t.panes?.xSplit||0,ySplit:t.panes?.ySplit||0},color:t.color,isLocked:t.isLocked};this.orderedSheetIds.push(i.id),this.sheets[i.id]=i}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(w).map(e=>{let t=this.sheets[e],n={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},styles:{},formats:{},borders:{},conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,isLocked:t.isLocked,color:t.color};return(t.panes.xSplit||t.panes.ySplit)&&(n.panes=t.panes),n})}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}isSheetLocked(e){return this.tryGetSheet(e)?.isLocked||!1}tryGetSheet(e){return this.sheets[e]}getSheet(e){let t=this.sheets[e];if(!t)throw Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){return this.tryGetSheet(e)?.name}getSheetIdByName(e){if(e)return this.sheetIdsMapName[bc(e)]}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}doesHeaderExist(e,t,n){return t===`COL`?n>=0&&n<this.getNumberCols(e):n>=0&&n<this.getNumberRows(e)}doesHeadersExist(e,t,n){return n.every(n=>this.doesHeaderExist(e,t,n))}getCell({sheetId:e,col:t,row:n}){let r=this.tryGetSheet(e)?.rows[n]?.cells[t];if(r!==void 0)return this.getters.getCellById(r)}getColsZone(e,t,n){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:n}}getRowCellIds(e,t){return Object.values(this.getSheet(e).rows[t]?.cells).filter(w)}getRowsZone(e,t,n){return{top:t,bottom:n,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){let t=this.cellPosition[e];if(!t)throw Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}tryGetCellPosition(e){return this.cellPosition[e]}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return t===`COL`?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e=`Sheet`){return vc(this.orderedSheetIds.map(this.getSheetName.bind(this)),e)}getSheetSize(e){return{numberOfRows:this.getNumberRows(e),numberOfCols:this.getNumberCols(e)}}getSheetZone(e){return{top:0,left:0,bottom:this.getNumberRows(e)-1,right:this.getNumberCols(e)-1}}getUnboundedZone(e,t){if(t.bottom===void 0||t.right===void 0)return t;let n=t.left===0&&t.right===this.getNumberCols(e)-1,r=t.top===0&&t.bottom===this.getNumberRows(e)-1;return{...t,bottom:r?void 0:t.bottom,right:n&&!r?void 0:t.right}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,n){let r={...this.getPaneDivisions(e)};n===`COL`?r.xSplit=t:n===`ROW`&&(r.ySplit=t),this.history.update(`sheets`,e,`panes`,r)}checkElementsIncludeAllNonFrozenHeaders(e,t,n){let r=this.getters.getPaneDivisions(e),i=t===`ROW`?r.ySplit:r.xSplit,a=this.getters.getNumberHeaders(e,t);return i?Et(n,C(i,a)):!1}getCommandZones(e){let t=[];return`zone`in e&&t.push(e.zone),`target`in e&&t.push(...e.target),`ranges`in e&&t.push(...e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone)),`col`in e&&e.col!==void 0&&`row`in e&&e.row!==void 0&&t.push({top:e.row,left:e.col,bottom:e.row,right:e.col}),t}checkZonesExistInSheet(e,t){if(!t.every(Sn))return`InvalidRange`;if(t.length){let n=this.getSheetZone(e);return t.every(e=>In(e,n))?`Success`:`TargetOutOfSheet`}return`Success`}updateCellPosition(e){let{sheetId:t,cellId:n,col:r,row:i}=e;n?this.setNewPosition(n,t,r,i):this.clearPosition(t,r,i)}setNewPosition(e,t,n,r){let i=this.cellPosition[e];i&&this.clearPosition(t,i.col,i.row),this.history.update(`cellPosition`,e,{row:r,col:n,sheetId:t}),this.history.update(`sheets`,t,`rows`,r,`cells`,n,e)}clearPosition(e,t,n){let r=this.sheets[e]?.rows[n].cells[t];r&&(this.history.update(`cellPosition`,r,void 0),this.history.update(`sheets`,e,`rows`,n,`cells`,t,void 0))}setGridLinesVisibility(e,t){this.history.update(`sheets`,e,`areGridLinesVisible`,t)}createSheet(e,t,n,r,i){let a={id:e,name:t,numberOfCols:n,rows:hc(r),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0},isLocked:!1},o=this.orderedSheetIds.slice();o.splice(i,0,a.id);let s=this.sheets;return this.history.update(`orderedSheetIds`,o),this.history.update(`sheets`,Object.assign({},s,{[a.id]:a})),a}moveSheet(e,t){let n=this.orderedSheetIds.slice(),r=n.findIndex(t=>t===e),i=n.splice(r,1),a=this.findIndexOfTargetSheet(r,t);n.splice(a,0,i[0]),this.history.update(`orderedSheetIds`,n)}findIndexOfTargetSheet(e,t){for(;t!==0&&0<=e&&e<=this.orderedSheetIds.length;)t>0?(e++,this.isSheetVisible(this.orderedSheetIds[e])&&t--):t<0&&(e--,this.isSheetVisible(this.orderedSheetIds[e])&&t++);if(t===0)return e;throw Error(`There is not enough visible sheets`)}createSheetHasName(e){return e.name!==void 0&&!e.name.trim()?`MissingSheetName`:`Success`}checkSheetName(e){let t=this.getters.tryGetSheetName(e.sheetId),n=e.type===`RENAME_SHEET`?e.newName:e.name;if(t!==void 0&&n===t)return`UnchangedSheetName`;let{orderedSheetIds:r,sheets:i}=this,a=n&&n.trim().toLowerCase();return r.find(t=>xc(i[t]?.name,a)&&t!==e.sheetId)?`DuplicatedSheetName`:Fe.test(a)?`ForbiddenCharactersInSheetName`:`Success`}checkSheetPosition(e){let{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?`WrongSheetPosition`:`Success`}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkRowFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.top<e.quantity&&e.quantity<=n.bottom)return`MergeOverlap`;return`Success`}checkColFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.left<e.quantity&&e.quantity<=n.right)return`MergeOverlap`;return`Success`}isRenameAllowed(e){return e.newName&&e.newName.trim().toLowerCase()?this.checkSheetName(e):`MissingSheetName`}renameSheet(e,t){let n=e.name;this.history.update(`sheets`,e.id,`name`,t.trim());let r=Object.assign({},this.sheetIdsMapName);delete r[bc(n)],r[bc(t)]=e.id,this.history.update(`sheetIdsMapName`,r)}hideSheet(e){this.history.update(`sheets`,e,`isVisible`,!1)}showSheet(e){this.history.update(`sheets`,e,`isVisible`,!0)}duplicateSheet(e,t,n){let r=x(this.getSheet(e));r.id=t,r.name=n,r.isLocked=!1;for(let e=0;e<=r.numberOfCols;e++)for(let t=0;t<=r.rows.length;t++)r.rows[t]&&(r.rows[t].cells[e]=void 0);let i=this.orderedSheetIds.slice(),a=i.indexOf(e);i.splice(a+1,0,r.id),this.history.update(`orderedSheetIds`,i),this.history.update(`sheets`,Object.assign({},this.sheets,{[r.id]:r}));for(let t of Object.values(this.getters.getCells(e))){let{col:e,row:n}=this.getCellPosition(t.id);this.dispatch(`UPDATE_CELL`,{sheetId:r.id,col:e,row:n,content:t.isFormula?t.compiledFormula.toFormulaString(this.getters):t.content,format:t.format,style:t.style})}let o=Object.assign({},this.sheetIdsMapName);o[bc(r.name)]=r.id,this.history.update(`sheetIdsMapName`,o)}getDuplicateSheetName(e){return yc(e,this.orderedSheetIds.map(this.getSheetName.bind(this)))}deleteSheet(e){let t=e.name,n=Object.assign({},this.sheets);delete n[e.id],this.history.update(`sheets`,n);let r=this.orderedSheetIds.slice(),i=r.indexOf(e.id);r.splice(i,1),this.history.update(`orderedSheetIds`,r);let a=Object.assign({},this.sheetIdsMapName);delete a[bc(t)],this.history.update(`sheetIdsMapName`,a)}removeColumns(e,t){t.sort((e,t)=>t-e);for(let n of t)this.moveCellOnColumnsDeletion(e,n);let n=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,n-t.length);let r=t.filter(t=>t<e.panes.xSplit).length;r&&this.setPaneDivisions(e.id,e.panes.xSplit-r,`COL`)}removeRows(e,t){t.sort((e,t)=>t-e);for(let n of rt(t)){let t=n[n.length-1],r=n[0];this.moveCellOnRowsDeletion(e,t,r),this.updateRowsStructureOnDeletion(e,t,r)}let n=t.filter(t=>t<e.panes.ySplit).length;n&&this.setPaneDivisions(e.id,e.panes.ySplit-n,`ROW`)}addColumns(e,t,n,r){let i=n===`before`?t:t+1;this.moveCellsOnAddition(e,i,r,`columns`);let a=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,a+r),i<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+r,`COL`)}addRows(e,t,n,r){let i=n===`before`?t:t+1;this.addEmptyRows(e,r),this.moveCellsOnAddition(e,i,r,`rows`),i<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+r,`ROW`)}moveCellOnColumnsDeletion(e,t){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:t,top:0,right:t,bottom:e.rows.length-1}]});for(let n=0;n<e.rows.length;n++){let r=e.rows[n];for(let i in r.cells){let a=Number(i),o=r.cells[i];o&&a>t&&this.setNewPosition(o,e.id,a-1,n)}}}moveCellsOnAddition(e,t,n,r){let i=[];for(let a=0;a<e.rows.length;a++){let o=e.rows[a];if(r!==`rows`||a>=t)for(let s in o.cells){let c=Number(s),l=o.cells[s];l&&(r===`rows`||c>=t)&&i.push({sheetId:e.id,cellId:l,col:c+(r===`columns`?n:0),row:a+(r===`rows`?n:0),type:`UPDATE_CELL_POSITION`})}}for(let e of i.reverse())this.updateCellPosition(e)}moveCellOnRowsDeletion(e,t,n){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:0,top:t,right:this.getters.getNumberCols(e.id),bottom:n}]});let r=n-t+1;for(let t=0;t<e.rows.length;t++){let i=e.rows[t];if(t>n)for(let n in i.cells){let a=Number(n),o=i.cells[n];o&&this.setNewPosition(o,e.id,a,t-r)}}}updateRowsStructureOnDeletion(e,t,n){let r=[],i=e.rows.map(e=>e.cells).reverse();for(let a in e.rows){let e=Number(a);e>=t&&e<=n||r.push({cells:i.pop()})}this.history.update(`sheets`,e.id,`rows`,r)}addEmptyRows(e,t){let n=e.rows.slice();for(let e=0;e<t;e++)n.push({cells:{}});this.history.update(`sheets`,e.id,`rows`,n)}getImportedSheetSize(e){let t=Object.keys(e.cells).map(yn),n=e.rowNumber,r=e.colNumber;for(let{right:e,bottom:i}of t)n=Math.max(n,i+1),r=Math.max(r,e+1);return{rowNumber:n,colNumber:r}}checkSheetExists(e){return e.type!==`CREATE_SHEET`&&`sheetId`in e&&this.sheets[e.sheetId]===void 0?`InvalidSheetId`:e.type===`CREATE_SHEET`&&this.sheets[e.sheetId]!==void 0?`DuplicatedSheetId`:`Success`}checkZonesAreInSheet(e){return fu(e)&&e.ranges.length===0?`EmptyRange`:`sheetId`in e?`ranges`in e&&e.ranges.some(e=>e._sheetId!==``&&!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:du(e)&&e.target.length===0?`EmptyTarget`:this.checkZonesExistInSheet(e.sheetId,this.getCommandZones(e)):`Success`}},qI=class extends SI{allowDispatch(e){switch(e.type){case`ADD_PIVOT`:case`UPDATE_PIVOT`:let t=e.pivot;return this.checkDataSetValidity(t)}return`Success`}checkDataSetValidity(e){if(e.type===`SPREADSHEET`&&e.dataSet){let{zone:t,sheetId:n}=e.dataSet;return!n||!this.getters.tryGetSheet(n)||!t||!Sn(t)?`InvalidDataSet`:this.getters.checkZonesExistInSheet(n,[t])}return`Success`}},JI=class extends SI{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(!nC[e.templateName])return`InvalidTableStyle`;try{Nr(e.primaryColor)}catch{return`InvalidTableStyle`}break}return`Success`}handle(e){switch(e.type){case`CREATE_TABLE_STYLE`:let t=rC(e.tableStyleName,e.templateName,e.primaryColor);this.history.update(`styles`,e.tableStyleId,t);break;case`REMOVE_TABLE_STYLE`:let n={...this.styles};delete n[e.tableStyleId],this.history.update(`styles`,n);for(let t of this.getters.getSheetIds())for(let n of this.getters.getCoreTables(t))n.config.styleId===e.tableStyleId&&this.dispatch(`UPDATE_TABLE`,{sheetId:t,zone:n.range.zone,config:{styleId:BS.styleId}});break}}getTableStyle(e){if(_M[e])return _M[e];if(!this.styles[e])throw Error(`Table style ${e} does not exist`);return this.styles[e]}getTableStyles(){return this.styles}getNewCustomTableStyleName(){return Kt(j(`Custom Table Style`),Object.values(this.styles).map(e=>e.displayName),{compute:(e,t)=>`${e} ${t}`,start:2})}isTableStyleEditable(e){return!tC[e]&&!_M[e]}import(e){for(let e in tC)this.styles[e]=tC[e];for(let t in e.customTableStyles){let n=e.customTableStyles[t];this.styles[t]=rC(n.displayName,n.templateName,n.primaryColor)}}export(e){let t={};for(let e in this.styles)tC[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}},YI=class extends SI{static getters=[`getCoreTable`,`getCoreTables`,`getCoreTableMatchingTopLeft`];tables={};nextTableId=1;adaptRanges({applyChange:e}){for(let t in this.tables)for(let n of this.getCoreTables(t))this.applyRangeChangeOnTable(t,n,e)}allowDispatch(e){switch(e.type){case`CREATE_TABLE`:if(e.ranges.some(t=>!this.getters.tryGetSheet(t._sheetId)||t._sheetId!==e.sheetId))return`InvalidSheetId`;let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone);return er(t)?this.checkValidations(e,e=>this.getTablesOverlappingZones(e.sheetId,t).length?`TableOverlap`:`Success`,e=>this.checkTableConfigUpdateIsValid(e.config)):`NonContinuousTargets`;case`UPDATE_TABLE`:return this.getCoreTableMatchingTopLeft(e.sheetId,e.zone)?this.checkValidations(e,this.checkUpdatedTableZoneIsValid,e=>this.checkTableConfigUpdateIsValid(e.config)):`TableNotFound`;case`ADD_MERGE`:for(let t of this.getCoreTables(e.sheetId)){let n=t.range.zone;for(let t of e.target)if(Nn(n,t))return`MergeInTable`}break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`tables`,e.sheetId,{});break;case`DELETE_SHEET`:{let t={...this.tables};delete t[e.sheetId],this.history.update(`tables`,t);break}case`DUPLICATE_SHEET`:{let t={};for(let n of this.getCoreTables(e.sheetId))t[n.id]=n.type===`dynamic`?this.copyDynamicTableForSheet(e.sheetIdTo,n):this.copyStaticTableForSheet(e.sheetIdTo,n);this.history.update(`tables`,e.sheetIdTo,t);break}case`CREATE_TABLE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e)),n=this.getters.getRangesUnion(t),r=this.getters.getMergesInZone(e.sheetId,n.zone);r.length&&this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:r});let i=this.consumeNextId(),a=e.config||BS,o=e.tableType===`dynamic`?this.createDynamicTable(i,n,a):this.createStaticTable(i,e.tableType,n,a);this.history.update(`tables`,e.sheetId,o.id,o);break}case`REMOVE_TABLE`:{let t={};for(let n of this.getCoreTables(e.sheetId))e.target.every(e=>!jn(n.range.zone,e))&&(t[n.id]=n);this.history.update(`tables`,e.sheetId,t);break}case`UPDATE_TABLE`:this.updateTable(e);break;case`UPDATE_CELL`:{let t=e.sheetId;for(let n of this.getCoreTables(t)){if(n.type===`dynamic`)continue;let r=this.canUpdateCellCmdExtendTable(e,n);r===`down`?this.extendTableDown(t,n):r===`right`&&this.extendTableRight(t,n)}break}case`DELETE_CONTENT`:{let t={...this.tables[e.sheetId]};for(let n in t){let r=t[n];r&&e.target.some(e=>In(r.range.zone,e))&&this.dispatch(`REMOVE_TABLE`,{sheetId:e.sheetId,target:[r.range.zone]})}break}}}getCoreTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(w):[]}getCoreTable({sheetId:e,col:t,row:n}){return this.getCoreTables(e).find(e=>Fn(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter(e=>t.some(t=>Nn(e.range.zone,t)))}extendTableDown(e,t){let n=this.getters.extendRange(t.range,`ROW`,1);this.history.update(`tables`,e,t.id,this.updateStaticTable(t,n))}extendTableRight(e,t){let n=this.getters.extendRange(t.range,`COL`,1);this.history.update(`tables`,e,t.id,this.updateStaticTable(t,n))}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:n,row:r},i){if(!e||this.isPivotFormula(e,t))return`none`;let a=i.range.zone,o=`none`;if(a.bottom+1===r&&n>=a.left&&n<=a.right?o=`down`:a.right+1===n&&r>=a.top&&r<=a.bottom&&(o=`right`),o===`none`)return`none`;let s=o===`down`?{...a,bottom:a.bottom+1,top:a.bottom+1}:{...a,right:a.right+1,left:a.right+1};for(let e=s.top;e<=s.bottom;e++)for(let n=s.left;n<=s.right;n++){let r={sheetId:t,col:n,row:e},i=this.getters.getCell(r);if(i?.isFormula||i?.content||this.getters.isInMerge(r)||this.getTablesOverlappingZones(t,[D(r)]).length)return`none`}return o}isPivotFormula(e,t){return e.startsWith(`=`)?Jj(Rc.Compile(e,t,this.getters),this.getters)?.functionName===`PIVOT`:!1}getCoreTableMatchingTopLeft(e,t){for(let n of this.getCoreTables(e)){let e=n.range.zone;if(e.left===t.left&&e.top===t.top)return n}}checkUpdatedTableZoneIsValid(e){if(!e.newTableRange)return`Success`;let t=this.getters.getRangeFromRangeData(e.newTableRange).zone,n=this.getters.checkZonesExistInSheet(e.sheetId,[t]);if(n!==`Success`)return n;let r=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);return r?this.getTablesOverlappingZones(e.sheetId,[t]).filter(e=>e.id!==r.id).length?`TableOverlap`:`Success`:`TableNotFound`}checkTableConfigUpdateIsValid(e){return e&&(e.numberOfHeaders!==void 0&&e.numberOfHeaders<0||e.hasFilters&&e.numberOfHeaders===0)?`InvalidTableConfig`:`Success`}createStaticTable(e,t,n,r,i){let a=n.zone;if(!i){i=[];for(let e of C(a.left,a.right+1)){let t={...a,left:e,right:e},o=this.consumeNextId();i.push(this.createFilterFromZone(o,n.sheetId,t,r))}}return{id:e,range:n,filters:i,config:r,type:t}}createDynamicTable(e,t,n){let r=qn(t.zone);return{id:e,range:this.getters.getRangeFromZone(t.sheetId,r),config:n,type:`dynamic`}}updateTable(e){let t=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return;let n=e.newTableRange?this.getters.getRangeFromRangeData(e.newTableRange):void 0;if(n){let t=this.getters.getMergesInZone(e.sheetId,n.zone);this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:t})}let r=n||t.range,i=this.updateTableConfig(e.config,t.config),a=e.tableType??t.type;if(a===`dynamic`&&t.type!==`dynamic`||a!==`dynamic`&&t.type===`dynamic`){let n=a===`dynamic`?this.createDynamicTable(t.id,r,i):this.createStaticTable(t.id,a,r,i);this.history.update(`tables`,e.sheetId,t.id,n)}else{let n=t.type===`dynamic`?this.updateDynamicTable(t,r,i):this.updateStaticTable(t,r,i,a);this.history.update(`tables`,e.sheetId,t.id,n)}}updateStaticTable(e,t,n,r=e.type){if(r===`dynamic`)throw Error(`Cannot use updateStaticTable to update a dynamic table`);let i=t||e.range,a=i.zone,o=this.updateTableConfig(n,e.config),s=o||e.config,c=[];if(t||o&&`numberOfHeaders`in o)for(let t of C(a.left,a.right+1)){let n=a.top===e.range.zone.top?e.filters.find(e=>e.col===t):void 0,r={...a,left:t,right:t},o=n?.id||this.consumeNextId();c.push(this.createFilterFromZone(o,i.sheetId,r,s))}return{...e,range:i,config:s,filters:c.length?c:e.filters,type:r}}updateDynamicTable(e,t,n){let r=t?this.getters.getRangeFromZone(t.sheetId,qn(t.zone)):e.range,i=n||e.config;return{...e,range:r,config:i}}updateTableConfig(e,t){if(!e)return t;let n={...t,...e};return e.numberOfHeaders===0?n.hasFilters=!1:e.hasFilters===!0&&(n.numberOfHeaders||=1),n}createFilterFromZone(e,t,n,r){return TM(e,this.getters.getRangeFromZone(t,n),r,this.getters.getRangeFromZone)}copyStaticTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone),r=t.filters.map(n=>{let r=this.getters.getRangeFromZone(e,n.rangeWithHeaders.zone);return TM(n.id,r,t.config,this.getters.getRangeFromZone)});return{id:t.id,range:n,filters:r,config:x(t.config),type:t.type}}copyDynamicTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone);return{id:t.id,range:n,config:x(t.config),type:`dynamic`}}applyRangeChangeOnTable(e,t,n){let r=n(t.range),i;switch(r.changeType){case`REMOVE`:this.history.update(`tables`,e,t.id,void 0);return;case`NONE`:return;default:i=r.range}if(t.type===`dynamic`){let n=this.updateDynamicTable(t,i);this.history.update(`tables`,e,t.id,n);return}let a=[];for(let e of t.filters){let r=n(e.rangeWithHeaders);switch(r.changeType){case`REMOVE`:continue;case`NONE`:a.push(e);break;default:let n=r.range,i=TM(e.id,n,t.config,this.getters.getRangeFromZone);a.push(i)}}let o=i.zone;if(a.length<Ln(o).numberOfCols){for(let n=o.left;n<=o.right;n++)if(!a.find(e=>e.col===n)){let r=this.consumeNextId(),i={...o,left:n,right:n};a.push(this.createFilterFromZone(r,e,i,t.config))}a.sort((e,t)=>e.col-t.col)}let s=this.createStaticTable(t.id,t.type,i,t.config,a);this.history.update(`tables`,e,t.id,s)}consumeNextId(){let e=`${this.nextTableId}`;return this.history.update(`nextTableId`,this.nextTableId+1),e}import(e){for(let t of e.sheets)for(let e of t.tables||[]){let n=this.consumeNextId(),r=e.config||BS,i=this.getters.getRangeFromSheetXC(t.id,e.range),a=e.type||`static`,o=a===`dynamic`?this.createDynamicTable(n,i,r):this.createStaticTable(n,a,i,r);this.history.update(`tables`,t.id,o.id,o)}}export(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n={range:wn(e.range.zone),type:e.type};T(e.config,BS)||(n.config=e.config),t.tables.push(n)}}exportForExcel(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n=wn(e.range.zone);t.tables.push({range:n,filters:[],config:e.config})}}},XI=class extends xI{getters;constructor({getters:e,stateObserver:t}){super(t),this.getters=e}};let ZI=Fo.mapping;function QI(e,t,n){return new $I(e,t,n).getParameters()}var $I=class{getters;computeCell;evalContext;rangeCache={};constructor(e,t,n){this.getters=t,this.computeCell=n,this.evalContext=Object.assign(Object.create(ZI),e,{getters:this.getters,locale:this.getters.getLocale(),getFormulaResult:this.getFormulaResult.bind(this)})}getParameters(){return{referenceDenormalizer:this.refFn.bind(this),ensureRange:this.range.bind(this),evalContext:this.evalContext}}refFn(e){let t=this.getRangeError(e);if(t)return t;let n={sheetId:e.sheetId,col:e.zone.left,row:e.zone.top},r=this.computeCell(n);return r.position?r:{...r,position:n}}range(e){let t=this.getRangeError(e);if(t)return[[t]];let n=e.sheetId,r=e.zone,i=jn(r,this.getters.getSheetZone(n));if(!i)return[[]];let{top:a,left:o,bottom:s,right:c}=r,l=`${n}-${a}-${o}-${s}-${c}`;if(l in this.rangeCache)return this.rangeCache[l];let u=i.bottom-i.top+1,d=i.right-i.left+1,f=Array(d);for(let e=i.left;e<=i.right;e++){let t=e-i.left;f[t]=Array(u);for(let r=i.top;r<=i.bottom;r++){let a=r-i.top;f[t][a]=this.getFormulaResult({sheetId:n,col:e,row:r})}}return this.rangeCache[l]=f,f}getFormulaResult(e){let t=this.computeCell(e);return t.position?t:{...t,position:e}}getRangeError(e){if(!Sn(e.zone))return new Li;if(e.invalidSheetName)return new Li(j(`Invalid sheet name: %s`,e.invalidSheetName))}},eL=class{interval;left;right;max;constructor(e,t=null,n=null){this.interval=e,this.left=t,this.right=n,this.max=e.bottom}},tL=class{root=null;buffer=[];insert(e){this.buffer.push(e)}query(e){this.buffer.length&&this.rebuild();let t=[];return this.searchTree(this.root,e,t),t}rebuild(){let e=[];this.inOrderTraversal(this.root,e);let t=this.buffer.sort(nL),n=this.mergeSortedIntervals(e,t);this.bulkLoad(n),this.buffer=[]}compactSortedIntervals(e){let t=e[0],n=[];for(let r=1;r<e.length;r++){let i=e[r];if(i.top===t.top&&i.bottom===t.bottom&&i.dependents.zone.left===t.dependents.zone.left&&i.dependents.zone.right===t.dependents.zone.right&&i.dependents.sheetId===t.dependents.sheetId)if(i.dependents.zone.top-1===t.dependents.zone.bottom)t.dependents.zone.bottom=i.dependents.zone.bottom;else if(i.dependents.zone.top===t.dependents.zone.top&&i.dependents.zone.bottom===t.dependents.zone.bottom)continue;else n.push(t),t=i;else n.push(t),t=i}return n.push(t),n}mergeSortedIntervals(e,t){let n=[],r=0,i=0;for(;r<e.length&&i<t.length;)nL(e[r],t[i])<=0?n.push(e[r++]):n.push(t[i++]);return n.concat(r<e.length?e.slice(r):t.slice(i))}bulkLoad(e){let t=this.compactSortedIntervals(e);this.root=this.buildBalancedTree(t)}buildBalancedTree(e,t=0,n=e.length){if(t>=n)return null;let r=t+(n-t>>1),i=new eL(e[r]);return i.left=this.buildBalancedTree(e,t,r),i.right=this.buildBalancedTree(e,r+1,n),i.max=Math.max(i.interval.bottom,i.left?i.left.max:-1,i.right?i.right.max:-1),i}searchTree(e,t,n){!e||t.top>e.max||(this.isOverlapping(e.interval,t)&&n.push(e.interval),e.left&&e.left.max>=t.top&&this.searchTree(e.left,t,n),e.right&&t.bottom>=e.interval.top&&this.searchTree(e.right,t,n))}inOrderTraversal(e,t){e&&(this.inOrderTraversal(e.left,t),t.push(e.interval),this.inOrderTraversal(e.right,t))}isOverlapping(e,t){return e.top<=t.bottom&&e.bottom>=t.top}};function nL(e,t){if(e.top!==t.top)return e.top-t.top;if(e.bottom!==t.bottom)return e.bottom-t.bottom;let{zone:n,sheetId:r}=e.dependents,{zone:i,sheetId:a}=t.dependents;return r===a?n.left-i.left||n.right-i.right||n.top-i.top||n.bottom-i.bottom:r>a?1:-1}var rL=class e{profilesStartingPosition=[0];profiles=new Map([[0,[]]]);constructor(e=[]){for(let t of e)this.add(t)}isEmpty(){return this.profiles.size===1&&this.profiles.get(0)?.length===0}add(e){ln(this.profilesStartingPosition,this.profiles,[e])}delete(e){ln(this.profilesStartingPosition,this.profiles,[e],!0)}has(e){return un(this.profilesStartingPosition,this.profiles,e)}difference(e){let t=this.copy();for(let n of e)t.delete(n);return t}copy(){let t=new e;t.profilesStartingPosition=[...this.profilesStartingPosition],t.profiles=new Map;for(let[e,n]of this.profiles)t.profiles.set(e,[...n]);return t}[Symbol.iterator](){return mn(this.profilesStartingPosition,this.profiles)[Symbol.iterator]()}},iL=class e{setsBySheetId={};constructor(e=[]){for(let t of e)this.add(t)}add(e){this.setsBySheetId[e.sheetId]||(this.setsBySheetId[e.sheetId]=new rL),this.setsBySheetId[e.sheetId].add(e.zone)}addMany(e){for(let t of e)this.add(t)}addPosition(e){this.add(ac(e))}addManyPositions(e){for(let t of e)this.addPosition(t)}has(e){return this.setsBySheetId[e.sheetId]?this.setsBySheetId[e.sheetId].has(e.zone):!1}hasPosition(e){return this.has(ac(e))}delete(e){this.setsBySheetId[e.sheetId]&&this.setsBySheetId[e.sheetId].delete(e.zone)}deleteMany(e){for(let t of e)this.delete(t)}deleteManyPositions(e){for(let t of e)this.delete(ac(t))}difference(t){let n=new e;for(let e in this.setsBySheetId)n.setsBySheetId[e]=this.setsBySheetId[e];for(let e in t.setsBySheetId)n.setsBySheetId[e]&&(n.setsBySheetId[e]=n.setsBySheetId[e].difference(t.setsBySheetId[e]));return n}copy(){let t=new e;for(let e in this.setsBySheetId)t.setsBySheetId[e]=this.setsBySheetId[e].copy();return t}clear(){this.setsBySheetId={}}isEmpty(){for(let e in this.setsBySheetId)if(!this.setsBySheetId[e].isEmpty())return!1;return!0}[Symbol.iterator](){let e=[];for(let t in this.setsBySheetId)for(let n of this.setsBySheetId[t])e.push({sheetId:t,zone:n});return e[Symbol.iterator]()}},aL=class{forest={};removeAllDependencies(e){}addDependencies(e,t){let n={zone:D(e),sheetId:e.sheetId};for(let e of t){if(e.invalidSheetName||e.invalidXc)continue;let{zone:t,sheetId:r}=e;for(let e=t.left;e<=t.right;e++)this.getOrCreateIntervalTree(r,e).insert({top:t.top,bottom:t.bottom,dependents:n})}}getCellsDependingOn(e,t=new iL){t=t.copy();let n=Array.from(e).reverse();for(;n.length>0;){let e=n.pop();t.add(e);let r=e.zone,i=this.forest[e.sheetId];if(!i)continue;let a=new iL;for(let e=r.left;e<=r.right;e++){let t=i[e];if(!t)continue;let n=t.query(r);for(let e of n)a.add(e.dependents)}n.push(...a.difference(t))}for(let n of e)t.delete(n);return t}getOrCreateIntervalTree(e,t){let n=this.forest[e]?.[t];return n||(this.forest[e]||(this.forest[e]={}),n=new tL,this.forest[e][t]=n),n}},oL=class extends Uint32Array{columnOffset=0;cols=0;rows=0;static create(e,t){let n=sL(t),r=e<<n>>5,i=new this(r+1);return i.columnOffset=n,i.cols=t,i.rows=e,i}getValue(e){let[t,n]=this.getCoordinates(e);return this[t]>>n&1}setValue(e,t){let[n,r]=this.getCoordinates(e),i=(this[n]>>r&1)==0&&t===1;return this[n]=this[n]&~(1<<r)|t<<r,i}isEmpty(){return!this.some(e=>e!==0)}fillAllPositions(){this.fill(-1>>>0)}clear(){this.fill(0)}getCoordinates(e){let{row:t,col:n}=e,r=(t<<this.columnOffset)+n,i=r>>5;return[i,r-(i<<5)]}};function sL(e){return e===0?-1/0:e<0?NaN:32-Math.clz32(--e)}var cL=class{sheets={};insertions=[];maxSize=0;constructor(e){for(let t in e){let n=e[t].cols,r=e[t].rows;this.maxSize+=n*r,this.sheets[t]=oL.create(r,n)}}add(e){this.sheets[e.sheetId].setValue(e,1)&&this.insertions.push(e)}addMany(e){for(let t of e)this.add(t)}delete(e){this.sheets[e.sheetId].setValue(e,0)}deleteMany(e){for(let t of e)this.delete(t)}has(e){return this.sheets[e.sheetId].getValue(e)===1}clear(){let e=[...this];this.insertions=[];for(let e in this.sheets)this.sheets[e].clear();return e}isEmpty(){if(this.insertions.length===0)return!0;for(let e in this.sheets)if(!this.sheets[e].isEmpty())return!1;return!0}fillAllPositions(){this.insertions=Array(this.maxSize);let e=0;for(let t in this.sheets){let n=this.sheets[t];n.fillAllPositions();for(let r=0;r<n.rows;r++)for(let i=0;i<n.cols;i++)this.insertions[e++]={sheetId:t,row:r,col:i}}}*[Symbol.iterator](){for(let e of this.insertions)this.sheets[e.sheetId].getValue(e)===1&&(yield e)}},lL=d(c(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n||=self).RBush=r()})(e,function(){"use strict";function e(e,r,i,a,o){(function e(n,r,i,a,o){for(;a>i;){if(a-i>600){var s=a-i+1,c=r-i+1,l=Math.log(s),u=.5*Math.exp(2*l/3),d=.5*Math.sqrt(l*u*(s-u)/s)*(c-s/2<0?-1:1);e(n,r,Math.max(i,Math.floor(r-c*u/s+d)),Math.min(a,Math.floor(r+(s-c)*u/s+d)),o)}var f=n[r],p=i,m=a;for(t(n,i,r),o(n[a],f)>0&&t(n,i,a);p<m;){for(t(n,p,m),p++,m--;o(n[p],f)<0;)p++;for(;o(n[m],f)>0;)m--}o(n[i],f)===0?t(n,i,m):t(n,++m,a),m<=r&&(i=m+1),r<=m&&(a=m-1)}})(e,r,i||0,a||e.length-1,o||n)}function t(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function n(e,t){return e<t?-1:+(e>t)}var r=function(e){e===void 0&&(e=9),this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()};function i(e,t,n){if(!n)return t.indexOf(e);for(var r=0;r<t.length;r++)if(n(e,t[r]))return r;return-1}function a(e,t){o(e,0,e.children.length,t,e)}function o(e,t,n,r,i){i||=m(null),i.minX=1/0,i.minY=1/0,i.maxX=-1/0,i.maxY=-1/0;for(var a=t;a<n;a++){var o=e.children[a];s(i,e.leaf?r(o):o)}return i}function s(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function c(e,t){return e.minX-t.minX}function l(e,t){return e.minY-t.minY}function u(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function d(e){return e.maxX-e.minX+(e.maxY-e.minY)}function f(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function p(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function m(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function h(t,n,r,i,a){for(var o=[n,r];o.length;)if(!((r=o.pop())-(n=o.pop())<=i)){var s=n+Math.ceil((r-n)/i/2)*i;e(t,s,n,r,a),o.push(n,s,s,r)}}return r.prototype.all=function(){return this._all(this.data,[])},r.prototype.search=function(e){var t=this.data,n=[];if(!p(e,t))return n;for(var r=this.toBBox,i=[];t;){for(var a=0;a<t.children.length;a++){var o=t.children[a],s=t.leaf?r(o):o;p(e,s)&&(t.leaf?n.push(o):f(e,s)?this._all(o,n):i.push(o))}t=i.pop()}return n},r.prototype.collides=function(e){var t=this.data;if(!p(e,t))return!1;for(var n=[];t;){for(var r=0;r<t.children.length;r++){var i=t.children[r],a=t.leaf?this.toBBox(i):i;if(p(e,a)){if(t.leaf||f(e,a))return!0;n.push(i)}}t=n.pop()}return!1},r.prototype.load=function(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(var t=0;t<e.length;t++)this.insert(e[t]);return this}var n=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===n.height)this._splitRoot(this.data,n);else{if(this.data.height<n.height){var r=this.data;this.data=n,n=r}this._insert(n,this.data.height-n.height-1,!0)}else this.data=n;return this},r.prototype.insert=function(e){return e&&this._insert(e,this.data.height-1),this},r.prototype.clear=function(){return this.data=m([]),this},r.prototype.remove=function(e,t){if(!e)return this;for(var n,r,a,o=this.data,s=this.toBBox(e),c=[],l=[];o||c.length;){if(o||(o=c.pop(),r=c[c.length-1],n=l.pop(),a=!0),o.leaf){var u=i(e,o.children,t);if(u!==-1)return o.children.splice(u,1),c.push(o),this._condense(c),this}a||o.leaf||!f(o,s)?r?(n++,o=r.children[n],a=!1):o=null:(c.push(o),l.push(n),n=0,r=o,o=o.children[0])}return this},r.prototype.toBBox=function(e){return e},r.prototype.compareMinX=function(e,t){return e.minX-t.minX},r.prototype.compareMinY=function(e,t){return e.minY-t.minY},r.prototype.toJSON=function(){return this.data},r.prototype.fromJSON=function(e){return this.data=e,this},r.prototype._all=function(e,t){for(var n=[];e;)e.leaf?t.push.apply(t,e.children):n.push.apply(n,e.children),e=n.pop();return t},r.prototype._build=function(e,t,n,r){var i,o=n-t+1,s=this._maxEntries;if(o<=s)return a(i=m(e.slice(t,n+1)),this.toBBox),i;r||(r=Math.ceil(Math.log(o)/Math.log(s)),s=Math.ceil(o/s**(r-1))),(i=m([])).leaf=!1,i.height=r;var c=Math.ceil(o/s),l=c*Math.ceil(Math.sqrt(s));h(e,t,n,l,this.compareMinX);for(var u=t;u<=n;u+=l){var d=Math.min(u+l-1,n);h(e,u,d,c,this.compareMinY);for(var f=u;f<=d;f+=c){var p=Math.min(f+c-1,d);i.children.push(this._build(e,f,p,r-1))}}return a(i,this.toBBox),i},r.prototype._chooseSubtree=function(e,t,n,r){for(;r.push(t),!t.leaf&&r.length-1!==n;){for(var i=1/0,a=1/0,o=void 0,s=0;s<t.children.length;s++){var c=t.children[s],l=u(c),d=(f=e,p=c,(Math.max(p.maxX,f.maxX)-Math.min(p.minX,f.minX))*(Math.max(p.maxY,f.maxY)-Math.min(p.minY,f.minY))-l);d<a?(a=d,i=l<i?l:i,o=c):d===a&&l<i&&(i=l,o=c)}t=o||t.children[0]}var f,p;return t},r.prototype._insert=function(e,t,n){var r=n?e:this.toBBox(e),i=[],a=this._chooseSubtree(r,this.data,t,i);for(a.children.push(e),s(a,r);t>=0&&i[t].children.length>this._maxEntries;)this._split(i,t),t--;this._adjustParentBBoxes(r,i,t)},r.prototype._split=function(e,t){var n=e[t],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);var o=this._chooseSplitIndex(n,i,r),s=m(n.children.splice(o,n.children.length-o));s.height=n.height,s.leaf=n.leaf,a(n,this.toBBox),a(s,this.toBBox),t?e[t-1].children.push(s):this._splitRoot(n,s)},r.prototype._splitRoot=function(e,t){this.data=m([e,t]),this.data.height=e.height+1,this.data.leaf=!1,a(this.data,this.toBBox)},r.prototype._chooseSplitIndex=function(e,t,n){for(var r,i,a,s,c,l,d,f=1/0,p=1/0,m=t;m<=n-t;m++){var h=o(e,0,m,this.toBBox),g=o(e,m,n,this.toBBox),_=(i=h,a=g,s=void 0,c=void 0,l=void 0,d=void 0,s=Math.max(i.minX,a.minX),c=Math.max(i.minY,a.minY),l=Math.min(i.maxX,a.maxX),d=Math.min(i.maxY,a.maxY),Math.max(0,l-s)*Math.max(0,d-c)),v=u(h)+u(g);_<f?(f=_,r=m,p=v<p?v:p):_===f&&v<p&&(p=v,r=m)}return r||n-t},r.prototype._chooseSplitAxis=function(e,t,n){var r=e.leaf?this.compareMinX:c,i=e.leaf?this.compareMinY:l;this._allDistMargin(e,t,n,r)<this._allDistMargin(e,t,n,i)&&e.children.sort(r)},r.prototype._allDistMargin=function(e,t,n,r){e.children.sort(r);for(var i=this.toBBox,a=o(e,0,t,i),c=o(e,n-t,n,i),l=d(a)+d(c),u=t;u<n-t;u++){var f=e.children[u];s(a,e.leaf?i(f):f),l+=d(a)}for(var p=n-t-1;p>=t;p--){var m=e.children[p];s(c,e.leaf?i(m):m),l+=d(c)}return l},r.prototype._adjustParentBBoxes=function(e,t,n){for(var r=n;r>=0;r--)s(t[r],e)},r.prototype._condense=function(e){for(var t=e.length-1,n=void 0;t>=0;t--)e[t].children.length===0?t>0?(n=e[t-1].children).splice(n.indexOf(e[t]),1):this.clear():a(e[t],this.toBBox)},r})}))(),1),uL=class{rTrees={};constructor(e=[]){let t={};for(let n of e){let e=n.boundingBox.sheetId;t[e]||(t[e]=[]),t[e].push(n)}for(let e in t)this.rTrees[e]=new dL,this.rTrees[e].load(t[e])}insert(e){let t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new dL),this.rTrees[t].insert(e)}search({zone:e,sheetId:t}){return this.rTrees[t]?this.rTrees[t].search({minX:e.left,minY:e.top,maxX:e.right,maxY:e.bottom}):[]}remove(e){let t=e.boundingBox.sheetId;this.rTrees[t]&&this.rTrees[t].remove(e,this.rtreeItemComparer)}rtreeItemComparer(e,t){return e.boundingBox.sheetId===t.boundingBox.sheetId&&e.boundingBox?.zone.left===t.boundingBox.zone.left&&e.boundingBox?.zone.top===t.boundingBox.zone.top&&e.boundingBox?.zone.right===t.boundingBox.zone.right&&e.boundingBox?.zone.bottom===t.boundingBox.zone.bottom&&T(e.data,t.data)}},dL=class extends lL.default{toBBox({boundingBox:e}){let t=e.zone;return{minX:t.left,minY:t.top,maxX:t.right,maxY:t.bottom}}compareMinX(e,t){return e.boundingBox.zone.left-t.boundingBox.zone.left}compareMinY(e,t){return e.boundingBox.zone.top-t.boundingBox.zone.top}},fL=class{resultsToArrayFormulas=new uL;arrayFormulasToResults=new tN;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map(e=>e.data)||pL}getArrayResultZone(e){return this.arrayFormulasToResults.get(e)}removeNode(e){let t=this.arrayFormulasToResults.get(e);t&&(this.resultsToArrayFormulas.remove({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.delete(e))}addRelation({arrayFormulaPosition:e,resultZone:t}){this.resultsToArrayFormulas.insert({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.set(e,t)}isArrayFormula(e){return this.arrayFormulasToResults.has(e)}};let pL=[],mL=new A;mL.add(`pivots`,e=>{for(let t of e.getPivotIds())e.getPivot(t).markAsDirtyForEvaluation?.()});let hL=Object.freeze(Uu({value:null}));var gL=class{context;getters;compilationParams;evaluatedCells=new tN;formulaDependencies=xt(new aL);blockedArrayFormulas=new cL({});spreadingRelations=new fL;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=QI(this.context,this.getters,this.computeAndSave.bind(this))}getEvaluatedCell(e){return this.evaluatedCells.get(e)||hL}getSpreadZone(e,t={ignoreSpillError:!1}){let n=this.spreadingRelations.getArrayResultZone(e);if(!n)return;let r=this.evaluatedCells.get(e);return r?.type===`error`&&!(t.ignoreSpillError&&r?.value===M.SpilledBlocked)?D(e):kn(D(e),n)}getEvaluatedPositions(){return this.evaluatedCells.keys()}getEvaluatedPositionsInSheet(e){return this.evaluatedCells.keysForSheet(e)}getArrayFormulaSpreadingOn(e){if(this.getEvaluatedCell(e).type!==`empty`)return this.spreadingRelations.searchFormulaPositionsSpreadingOn(e.sheetId,D(e)).find(e=>!this.blockedArrayFormulas.has(e))}isArrayFormulaSpillBlocked(e){return this.blockedArrayFormulas.has(e)}updateDependencies(e){this.formulaDependencies().removeAllDependencies(e);let t=this.getDirectDependencies(e);this.formulaDependencies().addDependencies(e,t)}addDependencies(e,t){this.formulaDependencies().addDependencies(e,t),this.computeDependencies(t)}computeDependencies(e){for(let t of e)this.compilationParams.ensureRange(t)}updateCompilationParametersForIsolatedFormula(e){this.compilationParams=QI(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.__originCellPosition=e,this.compilationParams.evalContext.updateDependencies=void 0,this.compilationParams.evalContext.addDependencies=void 0,this.compilationParams.evalContext.lookupCaches=this.compilationParams.evalContext.lookupCaches||{forwardSearch:new Map,reverseSearch:new Map}}updateCompilationParameters(){this.compilationParams=QI(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.updateDependencies=this.updateDependencies.bind(this),this.compilationParams.evalContext.addDependencies=this.addDependencies.bind(this),this.compilationParams.evalContext.lookupCaches={forwardSearch:new Map,reverseSearch:new Map}}createEmptyPositionSet(){let e={};for(let t of this.getters.getSheetIds())e[t]={rows:this.getters.getNumberRows(t),cols:this.getters.getNumberCols(t)};return new cL(e)}evaluateCells(e){let t=performance.now(),n=new iL;n.addManyPositions(e);let r=this.getArrayFormulasImpactedByChangesOf(e);n.addMany(this.getCellsDependingOn(n)),n.addMany(r),n.addMany(this.getCellsDependingOn(r)),this.evaluate(n),console.debug(`evaluate Cells`,performance.now()-t,`ms`)}getArrayFormulasImpactedByChangesOf(e){let t=new iL;for(let n of e){let e=this.getters.getCell(n),r=this.getArrayFormulaSpreadingOn(n);r!==void 0&&t.addPosition(r),!e?.isFormula&&!e?.content&&t.addPosition(n)}for(let e of[...t])t.addMany(this.getArrayFormulasBlockedBy(e.sheetId,e.zone));return t}buildDependencyGraph(){this.blockedArrayFormulas=this.createEmptyPositionSet(),this.spreadingRelations=new fL,this.formulaDependencies=xt(()=>{let e=new aL;for(let t of this.getters.getSheetIds())for(let n of this.getters.getCells(t))if(n.isFormula){let t=this.getters.getCellPosition(n.id);e.addDependencies(t,n.compiledFormula.rangeDependencies)}return e})}evaluateAllCells(){let e=performance.now();this.evaluatedCells=new tN;let t=[];for(let e of this.getters.getSheetIds()){let n=this.getters.getSheetZone(e);t.push({sheetId:e,zone:n})}this.evaluate(t),console.debug(`evaluate all cells`,performance.now()-e,`ms`)}evaluateFormulaResult(e,t,n){let r=Rc.Compile(t,e,this.getters);return this.updateCompilationParametersForIsolatedFormula(n),this.evaluateCompiledFormula(e,r)}evaluateCompiledFormula(e,t,n){try{let r=bL(t,this.compilationParams,e,this.buildSafeGetSymbolValue(n),this.compilationParams.evalContext.__originCellPosition);return Je(r)?co(r,vL):vL(r)}catch(e){return ko(e,``)}}getArrayFormulasBlockedBy(e,t){let n=new iL,r=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e,t);n.addManyPositions(r);let i=[...r].filter(e=>!this.blockedArrayFormulas.has(e));return i.length&&n.deleteManyPositions(i),n.addMany(this.getCellsDependingOn(n)),n}nextRangesToUpdate=new iL;cellsBeingComputed=new Set;symbolsBeingComputed=new Set;evaluate(e){this.cellsBeingComputed=new Set,this.nextRangesToUpdate=new iL(e);let t=0;for(;!this.nextRangesToUpdate.isEmpty()&&t++<30;){this.updateCompilationParameters();let e=[...this.nextRangesToUpdate];this.nextRangesToUpdate.clear(),this.clearEvaluatedRanges(e);for(let t of e){let{left:e,bottom:n,right:r,top:i}=t.zone;for(let a=e;a<=r;a++)for(let e=i;e<=n;e++){let n={sheetId:t.sheetId,col:a,row:e};if(this.nextRangesToUpdate.hasPosition(n))continue;let r=this.computeCell(n);(r.value!==null||r.format!==void 0)&&this.evaluatedCells.set(n,r)}}mL.getAll().forEach(e=>e(this.getters))}t>=30&&console.warn(`Maximum iteration reached while evaluating cells`)}clearEvaluatedRanges(e){for(let t of e){let{left:e,bottom:n,right:r,top:i}=t.zone;for(let a=e;a<=r;a++)for(let e=i;e<=n;e++)this.evaluatedCells.delete({sheetId:t.sheetId,col:a,row:e})}}computeCell(e){let t=this.evaluatedCells.get(e);if(t)return t;this.blockedArrayFormulas.has(e)||this.invalidateSpreading(e),this.spreadingRelations.isArrayFormula(e)&&this.spreadingRelations.removeNode(e);let n=this.getters.getCell(e);if(n===void 0)return{...hL,position:e};let r=n.id,i={format:n.format,locale:this.getters.getLocale()};try{return this.cellsBeingComputed.has(r)?xL(e):(this.cellsBeingComputed.add(r),n.isFormula?this.computeFormulaCell(e,n):Lu(n,i,e))}catch(t){return t.value=t?.value||M.GenericError,t.message=t?.message||Mo,t.origin=e,t.errorOriginPosition=t?.errorOriginPosition,Uu(t,i.locale,e)}finally{this.cellsBeingComputed.delete(r)}}computeAndSave(e){let t=this.computeCell(e);return this.evaluatedCells.has(e)||this.evaluatedCells.set(e,t),t}computeFormulaCell(e,t){let n=bL(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e);if(!Je(n)){let r=Uu(yL(n),this.getters.getLocale(),e,t);return r.type===`error`&&(r.errorOriginPosition=n.errorOriginPosition??e),r}this.assertSheetHasEnoughSpaceToSpreadFormulaResult(e,n);let r=n.length,i=n[0].length;if(i===0)return Uu({value:0},this.getters.getLocale(),e,t);if(i===1&&r===1)return Uu(yL(n[0][0]),this.getters.getLocale(),e,t);let a={top:e.row,bottom:e.row+i-1,left:e.col,right:e.col+r-1};return this.spreadingRelations.addRelation({resultZone:a,arrayFormulaPosition:e}),this.assertNoMergedCellsInSpreadZone(e,n),_L(r,i,this.checkCollision(e)),_L(r,i,this.spreadValues(e,n)),this.invalidatePositionsDependingOnSpread(e.sheetId,a),Uu(yL(n[0][0]),this.getters.getLocale(),e,t)}invalidatePositionsDependingOnSpread(e,t){let n=this.getCellsDependingOn(zn(t).map(t=>({sheetId:e,zone:t})));n.delete({sheetId:e,zone:t}),this.nextRangesToUpdate.addMany(n)}assertSheetHasEnoughSpaceToSpreadFormulaResult({sheetId:e,col:t,row:n},r){let i=this.getters.getNumberCols(e),a=this.getters.getNumberRows(e),o=t+r.length<=i,s=n+r[0].length<=a;if(!(o&&s))throw new Bi(j(`Result couldn't be automatically expanded.`))}assertNoMergedCellsInSpreadZone({sheetId:e,col:t,row:n},r){if(this.getters.getMergesInZone(e,{top:n,bottom:n+r[0].length-1,left:t,right:t+r.length-1}).length!==0)throw new Bi(j(`Merged cells found in the spill zone. Please unmerge cells before using array formulas.`))}checkCollision(e){let{sheetId:t,col:n,row:r}=e;return(i,a)=>{let o={sheetId:t,col:i+n,row:a+r},s=this.getters.getCell(o);if(s?.isFormula||s?.content||this.getters.getEvaluatedCell(o).type!==`empty`)throw this.blockedArrayFormulas.add(e),new Bi(j(`Array result was not expanded because it would overwrite data.`),o);this.blockedArrayFormulas.delete(e)}}spreadValues({sheetId:e,col:t,row:n},r){return(i,a)=>{let o={sheetId:e,col:i+t,row:a+n},s=this.getters.getCell(o),c=Uu(yL(r[i][a]),this.getters.getLocale(),o,s);c.type===`error`&&(c.errorOriginPosition=r[i][a].errorOriginPosition??o),this.evaluatedCells.set(o,c)}}invalidateSpreading(e){let t=this.spreadingRelations.getArrayResultZone(e);if(!t)return;for(let n=t.left;n<=t.right;n++)for(let r=t.top;r<=t.bottom;r++){let t={sheetId:e.sheetId,col:n,row:r},i=this.getters.getCell(t);i?.isFormula||i?.content||this.evaluatedCells.delete(t)}let n=e.sheetId;this.invalidatePositionsDependingOnSpread(n,t),this.nextRangesToUpdate.addMany(this.getArrayFormulasBlockedBy(n,t))}buildSafeGetSymbolValue(e){return(t,n)=>{if(this.symbolsBeingComputed.has(t))return xL(this.compilationParams.evalContext.__originCellPosition);this.symbolsBeingComputed.add(t);try{let r=this.getters.getNamedRange(t);if(r){let e=this.compilationParams.evalContext;return e.__originCellPosition?this.addDependencies(e.__originCellPosition,[r.range]):this.computeDependencies([r.range]),Xn(r.range.zone)>1||n?this.compilationParams.ensureRange(r.range):this.compilationParams.referenceDenormalizer(r.range)}return e?.(t,n)||new Fi(j(`Invalid formula`))}finally{this.symbolsBeingComputed.delete(t)}}}getDirectDependencies(e){let t=this.getters.getCell(e);return t?.isFormula?t.compiledFormula.rangeDependencies:[]}getCellsDependingOn(e){return this.formulaDependencies().getCellsDependingOn(e,this.nextRangesToUpdate)}};function _L(e,t,n){for(let r=0;r<e;++r)for(let e=0;e<t;++e)r===0&&e===0||n(r,e)}function vL(e){return e.value===null||e.value===void 0?{...e,value:0}:e}function yL(e){return typeof e.value==`number`&&Math.abs(e.value)>Number.MAX_VALUE?new Hi:vL(e)}function bL(e,t,n,r,i){let a=t.evalContext,o=a.__originCellPosition,s=a.__originSheetId;a.__originCellPosition=i,a.__originSheetId=n;let c=e.execute(e.rangeDependencies,t.referenceDenormalizer,t.ensureRange,r,a);return a.__originCellPosition=o,a.__originSheetId=s,c}function xL(e){return Uu({...new Ii,origin:void 0},void 0,e)}var SL=class extends XI{static getters=[`evaluateFormula`,`evaluateFormulaResult`,`evaluateCompiledFormula`,`getCorrespondingFormulaCell`,`getVisibleRangeValues`,`getEvaluatedCell`,`getEvaluatedCells`,`getEvaluatedCellsInZone`,`getEvaluatedCellsPositions`,`getSpreadZone`,`getArrayFormulaSpreadingOn`,`isArrayFormulaSpillBlocked`,`isEmpty`];shouldRebuildDependenciesGraph=!0;evaluator;positionsToUpdate=[];constructor(e){super(e),this.evaluator=new gL(e.custom,this.getters)}beforeHandle(e){(hu.has(e.type)||_u.has(e.type))&&(this.shouldRebuildDependenciesGraph=!0)}handle(e){switch(e.type){case`UPDATE_CELL`:if(!(`content`in e||`format`in e)||this.shouldRebuildDependenciesGraph)return;let t={sheetId:e.sheetId,row:e.row,col:e.col};this.positionsToUpdate.push(t),`content`in e&&this.evaluator.updateDependencies(t);break;case`EVALUATE_CELLS`:if(e.cellIds)for(let t=0;t<e.cellIds.length;t++)this.positionsToUpdate.push(this.getters.getCellPosition(e.cellIds[t]));else this.evaluator.evaluateAllCells();break}}finalize(){this.shouldRebuildDependenciesGraph?(this.evaluator.buildDependencyGraph(),this.evaluator.evaluateAllCells(),this.shouldRebuildDependenciesGraph=!1):this.positionsToUpdate.length&&this.evaluator.evaluateCells(this.positionsToUpdate),this.positionsToUpdate=[]}evaluateFormula(e,t,n){let r=this.evaluateFormulaResult(e,t,n);return Je(r)?co(r,e=>e.value):r.value}evaluateFormulaResult(e,t,n){return this.evaluator.evaluateFormulaResult(e,t,n)}evaluateCompiledFormula(e,t,n){return this.evaluator.evaluateCompiledFormula(e,t,n)}getVisibleRangeValues(e){return this.getters.tryGetSheet(e.sheetId)===void 0?[]:this.mapVisiblePositions(e,e=>this.getters.getEvaluatedCell(e))}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 Bn(t).map(({col:t,row:n})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}))}getSpreadZone(e,t={ignoreSpillError:!1}){return this.evaluator.getSpreadZone(e,t)}getArrayFormulaSpreadingOn(e){return this.evaluator.getArrayFormulaSpreadingOn(e)}isArrayFormulaSpillBlocked(e){return this.evaluator.isArrayFormulaSpillBlocked(e)}isEmpty(e,t){return Bn(t).map(({col:t,row:n})=>this.getEvaluatedCell({sheetId:e,col:t,row:n})).every(e=>e.type===`empty`)}mapVisiblePositions(e,t){let{sheetId:n,zone:r}=e;return Bn(r).reduce((e,r)=>{let{col:i,row:a}=r;return!this.getters.isColHidden(n,i)&&!this.getters.isRowHidden(n,a)&&e.push(t({sheetId:n,...r})),e},[])}exportForExcel(e){for(let t of e.sheets)t.cellValues={},t.formulaSpillRanges={};for(let t of this.evaluator.getEvaluatedPositions()){let n=this.evaluator.getEvaluatedCell(t),r=E(t.col,t.row),i=n.value,a=!1,o,s=!0,c=e.sheets.find(e=>e.id===t.sheetId),l=this.getCorrespondingFormulaCell(t);if(l){let u=this.getters.getCell(t);if(s=l.compiledFormula.areAllFunctionsExportableToExcel(),a=s&&(u?.isFormula?u.compiledFormula.toFormulaString(this.getters):u?.content)===l.compiledFormula.toFormulaString(this.getters),!s&&i!==``){o=(i??``).toString();let t=n.format;if(t){let n=od(t,e.formats);c.formats[r]=n}}}let u=c.cells[r],d;d=s&&a&&l?.isFormula?l.compiledFormula.toFormulaString(this.getters,{useBoundedReference:!0}):s?u:o,c.cells[r]=d,c.cellValues[r]=i===M.BadExpression?void 0:i;let f=this.getSpreadZone(t);f&&(c.formulaSpillRanges[r]=this.getters.getRangeString(this.getters.getRangeFromZone(t.sheetId,f),t.sheetId))}}getCorrespondingFormulaCell(e){let t=this.getters.getCell(e);if(t&&t.isFormula)return t.compiledFormula.isBadExpression?void 0:t;if(t&&t.content)return;let n=this.getArrayFormulaSpreadingOn(e);if(n===void 0)return;let r=this.getters.getCell(n);if(r?.isFormula)return r}};let CL=new A;CL.add(`data_validation_checkbox`,(e,t)=>{if(e.isCellValidCheckbox(t)){let n=!!e.getEvaluatedCell(t).value;return{svg:n?Eb:wb,hoverSvg:n?Eb:Tb,priority:2,horizontalAlign:`center`,size:17,margin:2,position:t,type:`data_validation_checkbox`,onClick:(e,t)=>{let r=t.model.getters.getCell(e);if(t.model.getters.isReadonly()||r?.isFormula)return;let i=n?`FALSE`:`TRUE`;t.model.dispatch(`UPDATE_CELL`,{...e,content:i})}}}}),CL.add(`data_validation_list_chip_icon`,(e,t)=>{if(e.isReadonly())return;let n=e.getDataValidationChipStyle(t);if(!e.cellHasListDataValidationIcon(t)&&!n)return;let r=e.getCellComputedStyle(t),i=n||r;return{svg:xb(i),hoverSvg:Cb(i),priority:2,horizontalAlign:`right`,size:Dd(r),margin:4,position:t,onClick:(e,t)=>{let{col:n,row:r}=e;t.model.selection.selectCell(n,r),t.startCellEdition()},type:`data_validation_list_chip_icon`}}),CL.add(`conditional_formatting`,(e,t)=>{let n=e.getConditionalIcon(t);if(n){let r=e.getCellStyle(t);return{type:`conditional_formatting`,svg:kb[n].svg,priority:1,horizontalAlign:`left`,size:Dd(r),margin:4,position:t}}}),CL.add(`pivot_collapse`,(e,t)=>{let n=e.getPivotIdFromPosition(t);if(!e.isSpillPivotFormula(t)||!n)return;let r=e.getPivotCellFromPosition(t),i=e.getPivotCoreDefinition(n);if(!(i.style?.tabularForm??pg.tabularForm)&&r.type===`HEADER`&&n&&r.domain.length){let n=e.isDashboard(),a=r.dimension===`COL`?i.columns:i.rows,o=!n&&!e.shouldShowFormulas()&&r.domain.length!==a.length,s=(i.collapsedDomains?.[r.dimension]??[]).some(e=>T(e,r.domain)),c=r.dimension===`ROW`?(r.domain.length-1)*15:0;return{type:`pivot_collapse`,priority:4,horizontalAlign:`left`,size:o||!n&&r.dimension===`ROW`&&i.rows.length>1?12:0,margin:o?4+c:c,svg:o?Db(s,!1):void 0,hoverSvg:o?Db(s,!0):void 0,position:t,onClick:Hg}}}),CL.add(`pivot_dashboard_sorting`,(e,t)=>{if(!e.isDashboard()||e.getPivotCellFromPosition(t).type!==`MEASURE_HEADER`)return;let n=e.getPivotCellSortDirection(t);if(n!==`asc`&&n!==`desc`)return;let r=e.getCellComputedStyle(t);return{type:`pivot_dashboard_sorting_${n}`,priority:5,horizontalAlign:`right`,size:Dd(r),margin:0,svg:n===`asc`?Sb(r):xb(r),position:t,onClick:void 0}});var wL=class extends XI{static getters=[`doesCellHaveGridIcon`,`getCellIcons`,`getCellIconRect`];cellIconsCache={};handle(e){e.type!==`SET_VIEWPORT_OFFSET`&&(this.cellIconsCache={})}getCellIcons(e){return this.cellIconsCache[e.sheetId]||(this.cellIconsCache[e.sheetId]={}),this.cellIconsCache[e.sheetId][e.col]||(this.cellIconsCache[e.sheetId][e.col]={}),this.cellIconsCache[e.sheetId][e.col][e.row]||(this.cellIconsCache[e.sheetId][e.col][e.row]=this.computeCellIcons(e)),this.cellIconsCache[e.sheetId][e.col][e.row]}getCellIconRect(e,t){let n=e.position,r=this.getters.getCell(n);return{x:this.getIconHorizontalPosition(t,e.horizontalAlign,e),y:this.getters.computeTextYCoordinate(t,e.size,r?.style?.verticalAlign),width:e.size,height:e.size}}getIconHorizontalPosition(e,t,n){let r=e.x,i=e.x+e.width;switch(t){case`right`:return i-n.margin-n.size;case`left`:return r+n.margin;default:let e=Math.floor((i-r-n.size)/2);return i-n.size-e}}computeCellIcons(e){let t={left:void 0,right:void 0,center:void 0},n=CL.getAll();for(let r of n){let n=r(this.getters,e);n&&(!t[n.horizontalAlign]||n.priority>t[n.horizontalAlign].priority)&&(t[n.horizontalAlign]=n)}if(t.center&&(t.left||t.right)){let e=Math.max(t.left?.priority||0,t.right?.priority||0);t.center.priority<e?t.center=void 0:(t.left=void 0,t.right=void 0)}return Object.values(t).filter(w)}doesCellHaveGridIcon(e){return!!this.getCellIcons(e).length}};let TL=/"(#[0-9a-fA-F]{6})"/g;function EL(e){let t=[{leadColor:Lr(255,0,0),colors:[]},{leadColor:Lr(255,128,0),colors:[]},{leadColor:Lr(128,128,0),colors:[]},{leadColor:Lr(128,255,0),colors:[]},{leadColor:Lr(0,255,0),colors:[]},{leadColor:Lr(0,255,128),colors:[]},{leadColor:Lr(0,255,255),colors:[]},{leadColor:Lr(0,127,255),colors:[]},{leadColor:Lr(0,0,255),colors:[]},{leadColor:Lr(127,0,255),colors:[]},{leadColor:Lr(128,0,128),colors:[]},{leadColor:Lr(255,0,128),colors:[]}];for(let n of e.map(Vr)){let e=500,r=0;t.forEach((t,i)=>{let a=DL(n,t.leadColor);e>a&&(e=a,r=i)}),t[r].colors.push(n)}return t.map(e=>e.colors.sort((e,t)=>Ur(e).s-Ur(t).s)).flat().map(Br)}function DL(e,t){return Math.sqrt((e.r-t.r)**2+(e.g-t.g)**2+(e.b-t.b)**2)}var OL=class extends XI{customColors={};shouldUpdateColors=!0;static getters=[`getCustomColors`];constructor(e){super(e),this.tryToAddColors(e.customColors??[])}handle(e){switch(e.type){case`START`:for(let e of this.getters.getSheetIds()){for(let t of this.getters.getChartIds(e))this.tryToAddColors(this.getChartColors(t));for(let t of this.getters.getFigures(e))this.tryToAddColors(this.getCarouselColors(e,t.id))}break;case`UPDATE_CHART`:case`CREATE_CHART`:this.tryToAddColors(this.getChartColors(e.chartId));break;case`CREATE_CAROUSEL`:case`UPDATE_CAROUSEL`:this.tryToAddColors(this.getCarouselColors(e.sheetId,e.figureId));break;case`COLOR_SHEET`:e.color&&this.tryToAddColors([e.color]);break;case`UPDATE_CELL`:case`ADD_CONDITIONAL_FORMAT`:case`SET_BORDER`:case`SET_ZONE_BORDERS`:case`SET_FORMATTING`:case`CREATE_TABLE`:case`UPDATE_TABLE`:this.history.update(`shouldUpdateColors`,!0);break}}finalize(){this.shouldUpdateColors&&(this.history.update(`shouldUpdateColors`,!1),this.tryToAddColors(this.computeCustomColors()))}getCustomColors(){return EL(Object.keys(this.customColors))}computeCustomColors(){let e=[];for(let t of this.getters.getSheetIds())e=e.concat(this.getSheetColors(t),this.getColorsFromCells(t),this.getFormattingColors(t),this.getTableColors(t));return[...new Set([...e])]}getSheetColors(e){let t=this.getters.getSheet(e);return t.color?[t.color]:[]}getColorsFromCells(e){let t=Object.values(this.getters.getCells(e)),n=new Set;for(let e of t)e.style?.textColor&&n.add(e.style.textColor),e.style?.fillColor&&n.add(e.style.fillColor);for(let t of this.getters.getBordersColors(e))n.add(t);return[...n]}getFormattingColors(e){let t=this.getters.getConditionalFormats(e),n=[];for(let e of t){let t=e.rule;t.type===`CellIsRule`?(n.push(t.style.textColor),n.push(t.style.fillColor)):t.type===`ColorScaleRule`&&(n.push(jr(t.minimum.color)),n.push(t.midpoint?jr(t.midpoint.color):void 0),n.push(jr(t.maximum.color)))}return n.filter(w)}getChartColors(e){let t=this.getters.getChart(e);return t===void 0?[]:[...JSON.stringify(t.getRangeDefinition()).matchAll(TL)].map(e=>e[1])}getCarouselColors(e,t){if(this.getters.getFigure(e,t)?.tag!==`carousel`)return[];let n=this.getters.getCarousel(t).title?.color;return n?[n]:[]}getTableColors(e){return this.getters.getTables(e).flatMap(e=>{let t=e.config,n=this.getters.getTableStyle(t.styleId);return[this.getTableStyleElementColors(n.wholeTable),t.numberOfHeaders>0?this.getTableStyleElementColors(n.headerRow):[],t.totalRow?this.getTableStyleElementColors(n.totalRow):[],t.bandedColumns?this.getTableStyleElementColors(n.firstColumnStripe):[],t.bandedColumns?this.getTableStyleElementColors(n.secondColumnStripe):[],t.bandedRows?this.getTableStyleElementColors(n.firstRowStripe):[],t.bandedRows?this.getTableStyleElementColors(n.secondRowStripe):[],t.firstColumn?this.getTableStyleElementColors(n.firstColumn):[],t.lastColumn?this.getTableStyleElementColors(n.lastColumn):[]].flat()})}getTableStyleElementColors(e){return e?[e.style?.fillColor,e.style?.textColor,e.border?.bottom?.color,e.border?.top?.color,e.border?.left?.color,e.border?.right?.color,e.border?.horizontal?.color,e.border?.vertical?.color].filter(w):[]}tryToAddColors(e){for(let t of e){if(!Pr(t))continue;let e=Nr(t);t&&!ye.includes(e)&&this.history.update(`customColors`,e,!0)}}},kL=class extends XI{static getters=[`canCreateDynamicTableOnZones`,`doesZonesContainFilter`,`getFilter`,`getFilters`,`getTable`,`getTables`,`getTablesOverlappingZones`,`getFilterId`,`getFilterHeaders`,`isFilterHeader`];tables={};handle(e){if(hu.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tables={};return}switch(e.type){case`CREATE_TABLE`:case`REMOVE_TABLE`:case`UPDATE_TABLE`:case`DELETE_CONTENT`:case`REFRESH_PIVOT`:this.tables={};break}}finalize(){for(let e of this.getters.getSheetIds())this.tables[e]||(this.tables[e]=this.computeTables(e))}computeTables(e){let t=[],n=[...this.getters.getCoreTables(e)].filter(e=>e.type!==`dynamic`);t.push(...n);for(let r of this.getDynamicTables(e)){let i=this.coreTableToTable(e,r),a=i.range.zone,o=a.left,s=a.top;if(!n.some(e=>Fn(o,s,e.range.zone))){for(let e of n){let t=e.range.zone;Nn(a,t)&&(a=t.left>a.left?{...a,right:Math.min(a.right,t.left-1)}:{...a,bottom:Math.min(a.bottom,t.top-1)})}t.push({...i,range:this.getters.getRangeFromZone(e,a)})}}return t}getDynamicTables(e){let t=this.getters.getCoreTables(e).filter(e=>e.type===`dynamic`),n=this.getTablesFromPivots(e),r=new Set(n.map(t=>this.getters.getRangeString(t.range,e))),i=t.filter(t=>!r.has(this.getters.getRangeString(t.range,e)));return[...n,...i]}getTablesFromPivots(e){let t=[];for(let{position:n,pivotStyle:r,pivotId:i}of this.getters.getAllPivotArrayFormulas()){if(!this.getters.getPivot(i).isValid())continue;let a=this.getters.getSpreadZone(n),o=this.getters.getCell(n);n.sheetId!==e||!a||!o||r.tableStyleId===`None`||t.push({type:`dynamic`,id:`pivot_table_`+i+`_`+o.id,range:this.getters.getRangeFromZone(e,D(n)),config:this.getTableConfigFromPivotStyle(i,r),isPivotTable:!0})}return t}getTableConfigFromPivotStyle(e,t){let n=this.getters.getPivot(e).getCollapsedTableStructure(),{numberOfRows:r,numberOfHeaderRows:i}=n.getPivotTableDimensions(t),a=n.getPivotCells(t)[0]?.[r-1],o=t.displayTotals&&a?.type===`HEADER`&&a.domain.length===0;return{hasFilters:t.hasFilters,totalRow:o,firstColumn:!0,lastColumn:!0,numberOfHeaders:i,bandedRows:t.bandedRows,bandedColumns:t.bandedColumns,styleId:t.tableStyleId}}getFilters(e){return this.getTables(e).filter(e=>e.config.hasFilters).map(e=>e.filters).flat()}getTables(e){return this.tables[e]||[]}getFilter(e){let t=this.getTable(e);if(!(!t||!t.config.hasFilters))return t.filters.find(t=>t.col===e.col)}getFilterId(e){return this.getFilter(e)?.id}getTable({sheetId:e,col:t,row:n}){return this.getTables(e).find(e=>Fn(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getTables(e).filter(e=>t.some(t=>Nn(e.range.zone,t)))}doesZonesContainFilter(e,t){return this.getTablesOverlappingZones(e,t).some(e=>e.config.hasFilters)}getFilterHeaders(e){let t=[];for(let n of this.getTables(e)){if(!n.config.hasFilters)continue;let r=n.range.zone,i=r.top;for(let n=r.left;n<=r.right;n++)t.push({sheetId:e,col:n,row:i})}return t}isFilterHeader({sheetId:e,col:t,row:n}){return this.getFilterHeaders(e).some(e=>e.col===t&&e.row===n)}canCreateDynamicTableOnZones(e,t){if(!er(t))return!1;let n=kn(...t),r={col:n.left,row:n.top,sheetId:e},i=this.getters.getArrayFormulaSpreadingOn(r);if(!i){let e=this.getters.getEvaluatedCell(r);return e.value===M.SpilledBlocked&&!e.errorOriginPosition}else if(T(i,r)&&Xn(n)===1)return!0;return T(n,this.getters.getSpreadZone(i))}coreTableToTable(e,t){if(t.type!==`dynamic`)return t;let n=t.range.zone,r={sheetId:e,col:n.left,row:n.top},i=this.getters.getSpreadZone(r)??t.range.zone,a=this.getters.getRangeFromZone(e,i),o=this.getDynamicTableFilters(e,t,i);return{id:t.id,range:a,filters:o,config:t.config,isPivotTable:t.isPivotTable}}getDynamicTableFilters(e,t,n){let r=[],{top:i,bottom:a,left:o,right:s}=n;for(let n=o;n<=s;n++){let s=n-o,c={left:n,right:n,top:i,bottom:a},l=TM(this.getDynamicTableFilterId(t.id,s),this.getters.getRangeFromZone(e,c),t.config,this.getters.getRangeFromZone);r.push(l)}return r}getDynamicTableFilterId(e,t){return e+`_`+t}isTableExcelExportable(e,t){return t.type===`dynamic`?!1:!Bn(t.range.zone).some(t=>this.getters.getArrayFormulaSpreadingOn({sheetId:e,...t}))}exportForExcel(e){for(let t of e.sheets){let n=[];for(let r of t.tables){let i=yn(r.range),a={sheetId:t.id,col:i.left,row:i.top},o=this.getters.getCoreTable(a),s=this.getTable(a);if(!o||!s||this.isTableExcelExportable(t.id,o)){n.push(r);continue}t.styles=t.styles||{},t.borders=t.borders||{};for(let n of Bn(s.range.zone)){let r={sheetId:t.id,...n},i=this.getters.getCellComputedStyle(r),a=this.getters.getCellComputedBorder(r),o=E(n.col,n.row);if(!gt(i)){let n=od(i,e.styles);t.styles[o]=n}if(a){let n=od(a,e.borders);t.borders[o]=n}}}t.tables=n}}};function AL(e){return{...e,data:{...e.data,datasets:e.data.datasets.filter(e=>!Nf(e.xAxisID)).map(e=>({...e,pointRadius:e.showLine===!1?2:0}))},options:{...e.options,hover:{mode:null},plugins:{...e.options.plugins,title:{display:!1},legend:{display:!1},tooltip:{enabled:!1},chartShowValuesPlugin:void 0},layout:{padding:{...e.options.layout?.padding,top:5,bottom:10}},scales:{y:{...e.options.scales?.y,display:!1},y1:{...e.options.scales?.y1,display:!1},x:{...e.options.scales?.x,title:void 0,ticks:{...e.options.scales?.x?.ticks,callback:function(t){return Mf(e.options.scales?.x?.ticks?.callback?.call(this,t),5)},padding:0,font:{size:9}}}}}}}var jL=class extends XI{static getters=[`getChartRuntime`,`getStyleOfSingleCellChart`];charts={};handle(e){if(hu.has(e.type)||vu.has(e.type)||gu.has(e.type))for(let e in this.charts)this.charts[e]=void 0;switch(e.type){case`UPDATE_CHART`:case`CREATE_CHART`:this.charts[e.chartId]=void 0;break;case`DELETE_CHART`:this.charts[e.chartId]=void 0;break;case`DELETE_SHEET`:for(let e in this.charts)this.getters.isChartDefined(e)||(this.charts[e]=void 0);break}}getChartRuntime(e){if(!this.charts[e]){let t=this.getters.getChart(e);if(!t)throw Error(`No chart for the given id: ${e}`);this.charts[e]=this.createRuntimeChart(e,t)}return this.charts[e]}getStyleOfSingleCellChart(e,t){if(e)return{background:e,fontColor:xf(e)};if(!t)return{background:oe,fontColor:xf(oe)};let n=t.zone.left,r=t.zone.top,i=t.sheetId,a=this.getters.getCellComputedStyle({sheetId:i,col:n,row:r}),o=a.fillColor||`#FFFFFF`;return{background:o,fontColor:a.textColor||xf(o)}}async exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let r of e){if(!r||r.tag!==`chart`)continue;let e=this.getters.getChartIds(t.id).find(e=>this.getters.getFigureIdFromChartId(e)===r.id);if(!e)continue;let i=this.getters.getChart(e),a=i?.getDefinitionForExcel(this.getters);if(a)n.push({...r,data:a});else{if(!i)continue;let n=this.getters.getChartType(e),a=await ih(this.getters.getChartRuntime(e),r,n);a&&t.images.push({...r,tag:`image`,data:{mimetype:`image/png`,path:a,size:{width:r.width,height:r.height}}})}}t.charts=n}}createRuntimeChart(e,t){let n=t.getRangeDefinition(),r=t.getRuntime(this.getters,e);if(`chartJsConfig`in r&&/line|combo|bar|scatter|waterfall/.test(n.type)){let e=r.chartJsConfig;r.masterChartConfig=AL(e)}return r}},ML=class extends XI{static getters=[`getConditionalIcon`,`getCellConditionalFormatStyle`,`getConditionalDataBar`];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(hu.has(e.type)||vu.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e))&&(this.isStale=!0)}finalize(){if(this.isStale){for(let e of this.getters.getSheetIds())this.computedStyles[e]=xt(()=>this.getComputedStyles(e)),this.computedIcons[e]=xt(()=>this.getComputedIcons(e)),this.computedDataBars[e]=xt(()=>this.getComputedDataBars(e));this.isStale=!1}}getCellConditionalFormatStyle(e){let{sheetId:t,col:n,row:r}=e,i=this.computedStyles[t]?.();return i&&i[n]?.[r]}getConditionalIcon({sheetId:e,col:t,row:n}){let r=this.computedIcons[e]?.();return r&&r[t]?.[n]}getConditionalDataBar({sheetId:e,col:t,row:n}){let r=this.computedDataBars[e]?.();return r&&r[t]?.[n]}getComputedStyles(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())switch(n.rule.type){case`ColorScaleRule`:for(let r of n.ranges)this.applyColorScale(e,r,n.rule,t);break;case`CellIsRule`:let r=n.rule.values.map(t=>{if(t.startsWith(`=`))return Rc.Compile(t,e,this.getters)}),i=X.get(n.rule.operator),a={...n.rule,type:n.rule.operator},o=n.ranges.map(t=>this.getters.getRangeFromSheetXC(e,t)),s=i.preComputeCriterion?.(a,o,this.getters);for(let i of n.ranges){let a=this.getters.getRangeFromSheetXC(e,i).zone;for(let i=a.top;i<=a.bottom;i++)for(let o=a.left;o<=a.right;o++){let c={sheetId:e,col:o,row:i},l=n.rule.values.map((t,n)=>{let s=r[n];return s?this.getters.getTranslatedCellFormula(e,o-a.left,i-a.top,s):t});this.getRuleResultForTarget(c,{...n.rule,values:l},s)&&(t[o]||(t[o]=[]),t[o][i]=Object.assign(t[o]?.[i]||{},n.rule.style))}}break}return t}getComputedIcons(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`IconSetRule`)for(let r of n.ranges)this.applyIcon(e,r,n.rule,t);return t}getComputedDataBars(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`DataBarRule`)for(let r of n.ranges)this.applyDataBar(e,r,n.rule,t);return t}parsePoint(e,t,n,r){let i=this.getters.getRangeFromSheetXC(e,t).zone,a=this.getters.getEvaluatedCellsInZone(e,i).filter(e=>e.type===`number`).map(e=>e.value);switch(n.type){case`value`:return r===`max`?Vt(a):Ht(a);case`number`:return Number(n.value);case`percentage`:let t=Ht(a);return t+(Vt(a)-t)*Number(n.value)/100;case`percentile`:return La(a,Number(n.value)/100,!0);case`formula`:let i=n.value&&this.getters.evaluateFormula(e,n.value);return typeof i==`number`?i:null;default:return null}}applyIcon(e,t,n,r){let i=this.parsePoint(e,t,n.lowerInflectionPoint),a=this.parsePoint(e,t,n.upperInflectionPoint);if(i===null||a===null||i>a)return;let o=this.getters.getRangeFromSheetXC(e,t).zone,s=[n.icons.upper,n.icons.middle,n.icons.lower];for(let t=o.top;t<=o.bottom;t++)for(let c=o.left;c<=o.right;c++){let o=this.getters.getEvaluatedCell({sheetId:e,col:c,row:t});if(o.type!==`number`)continue;let l=this.computeIcon(o.value,a,n.upperInflectionPoint.operator,i,n.lowerInflectionPoint.operator,s);r[c]||(r[c]=[]),r[c][t]=l}}computeIcon(e,t,n,r,i,a){return n===`ge`&&e>=t||n===`gt`&&e>t?a[0]:i===`ge`&&e>=r||i===`gt`&&e>r?a[1]:a[2]}applyDataBar(e,t,n,r){let i=this.getters.getRangeFromSheetXC(e,n.rangeValues||t),a=Vt(this.getters.getEvaluatedCellsInZone(e,i.zone).filter(e=>e.type===`number`).map(e=>e.value));if(a<=0)return;let o=n.color,s=this.getters.getRangeFromSheetXC(e,t).zone,c=i.zone;for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let i=n-s.left+c.left,l=t-s.top+c.top,u=this.getters.getEvaluatedCell({sheetId:e,col:i,row:l});!Fn(i,l,c)||u.type!==`number`||u.value<=0||(r[n]||(r[n]=[]),r[n][t]={color:jr(o),percentage:u.value*100/a})}}applyColorScale(e,t,n,r){let i=this.parsePoint(e,t,n.minimum,`min`),a=n.midpoint?this.parsePoint(e,t,n.midpoint):null,o=this.parsePoint(e,t,n.maximum,`max`);if(i===null||o===null||i>=o||a!==null&&(i>=a||a>=o))return;let s=this.getters.getRangeFromSheetXC(e,t).zone,c=[{value:i,color:n.minimum.color}];n.midpoint&&a!==null&&c.push({value:a,color:n.midpoint.color}),c.push({value:o,color:n.maximum.color});let l=hi(c);for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let a=this.getters.getEvaluatedCell({sheetId:e,col:n,row:t});if(a.type===`number`){let e=S(a.value,i,o);r[n]||(r[n]=[]),r[n][t]=r[n]?.[t]||{},r[n][t].fillColor=l(e)}}}getRuleResultForTarget(e,t,n){let r=this.getters.getEvaluatedCell(e);if(r.type===`error`)return!1;let{sheetId:i}=e,a=X.get(t.operator),o=t.values.map(t=>t.startsWith(`=`)?this.getters.evaluateFormula(i,t,e)??``:Hu(t,V));if(o.some(Sh))return!1;let s={...t,type:t.operator,values:o.map(bh),dateValue:t.dateValue||`exactDate`};return a.isValueValid(r.value??``,s,n)}};let NL={isValid:!0};var PL=class extends XI{static getters=[`getDataValidationInvalidCriterionValueMessage`,`getInvalidDataValidationMessage`,`getValidationResultForCellValue`,`getDataValidationRangeValues`,`isCellValidCheckbox`,`getDataValidationCellStyle`,`getDataValidationChipStyle`,`isDataValidationInvalid`];validationResults={};criterionPreComputeResult={};handle(e){if(hu.has(e.type)||e.type===`EVALUATE_CELLS`||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)){this.validationResults={},this.criterionPreComputeResult={};return}switch(e.type){case`ADD_DATA_VALIDATION_RULE`:case`REMOVE_DATA_VALIDATION_RULE`:delete this.validationResults[e.sheetId],delete this.criterionPreComputeResult[e.sheetId];break}}isDataValidationInvalid(e){return!this.getValidationResultForCell(e).isValid}getDataValidationCellStyle(e){if(!this.hasChip(e))return this.getDataValidationStyle(e)}getDataValidationChipStyle(e){if(this.hasChip(e))return this.getDataValidationStyle(e)??{fillColor:`#E7E9ED`}}getInvalidDataValidationMessage(e){let t=this.getValidationResultForCell(e);return t.isValid?void 0:t.error}getDataValidationInvalidCriterionValueMessage(e,t){let n=X.get(e);return t.startsWith(`=`)?n.allowedValues===`onlyLiterals`?j(`The value must not be a formula`):this.isValidFormula(t)?void 0:By.CriterionError.validFormula:n.allowedValues===`onlyFormulas`?j(`The value must be a formula`):n.isCriterionValueValid(t)?void 0:n.criterionValueErrorString}getDataValidationRangeValues(e,t){let n=this.getters.getRangeFromSheetXC(e,String(t.values[0])),r=[],i=new Set;for(let e of Bn(n.zone)){let t=this.getters.getEvaluatedCell({...e,sheetId:n.sheetId});t.formattedValue&&!i.has(t.formattedValue)&&(i.add(t.formattedValue),r.push({label:t.formattedValue,value:t.value?.toString()||``}))}return r}isCellValidCheckbox(e){if(!this.getters.isMainCellPosition(e))return!1;let t=this.getters.getValidationRuleForCell(e);return!t||t.criterion.type!==`isBoolean`?!1:this.getValidationResultForCell(e).isValid}getValidationResultForCellValue(e,t){let n=this.getters.getValidationRuleForCell(t);if(!n)return NL;let r=this.getRuleErrorForCellValue(e,t,n);return r?{error:r,rule:n,isValid:!1}:NL}hasChip(e){let t=this.getters.getValidationRuleForCell(e);return(t?.criterion.type===`isValueInList`||t?.criterion.type===`isValueInRange`)&&t.criterion.displayStyle===`chip`}getDataValidationStyle(e){let t=this.getters.getValidationRuleForCell(e);if(!t||this.isDataValidationInvalid(e))return;let n=this.getters.getEvaluatedCell(e),r=this.getValueColor(t,n.value);if(r)return{fillColor:r,textColor:Qr(r)}}getValueColor(e,t){if(!(e.criterion.type!==`isValueInList`&&e.criterion.type!==`isValueInRange`)){for(let n in e.criterion.colors)if(n.toLowerCase()===String(t).toLowerCase())return e.criterion.colors[n]}}isValidFormula(e){return!Rc.IsBadExpression(e)}getValidationResultForCell(e){let{col:t,row:n,sheetId:r}=e;return this.validationResults[r]||(this.validationResults[r]=this.computeSheetValidationResults(r)),this.validationResults[r][t]?.[n]?.()||NL}computeSheetValidationResults(e){let t={},n=this.getters.getDataValidationRules(e).map(e=>e.ranges);for(let e of rc(n.flat())){let{col:n,row:r}=e;t[n]||(t[n]=[]),t[n][r]=xt(()=>{let t=this.getters.getEvaluatedCell(e);return t.type===`empty`?NL:this.getValidationResultForCellValue(t.value,e)})}return t}getRuleErrorForCellValue(e,t,n){let{sheetId:r}=t,i=n.criterion,a=X.get(i.type),o=this.getCellOffsetInRule(t,n),s=this.getEvaluatedCriterionValues(r,t,o,i);if(s.some(Sh))return;let c={...i,values:s.map(bh)};this.criterionPreComputeResult[r]||(this.criterionPreComputeResult[r]={});let l=this.criterionPreComputeResult[r][n.id];if(l===void 0&&(l=a.preComputeCriterion?.(n.criterion,n.ranges,this.getters),this.criterionPreComputeResult[r][n.id]=l),!a.isValueValid(e,c,l))return a.getErrorString(c,this.getters,r)}getCellOffsetInRule(e,t){let n=t.ranges.find(t=>Fn(e.col,e.row,t.zone));if(!n)throw Error(`The cell is not in any range of the rule`);return{col:e.col-n.zone.left,row:e.row-n.zone.top}}getEvaluatedCriterionValues(e,t,n,r){return r.values.map(r=>{if(!r.startsWith(`=`))return Hu(r,V);let i=Rc.Compile(r,e,this.getters),a=this.getters.getTranslatedCellFormula(e,n.col,n.row,i);return this.getters.evaluateFormula(e,a,t)})}};let FL=[`SUBTOTAL`,`PIVOT`];var IL=class extends XI{static getters=[`getCellsWithTrackedFormula`];trackedCells={};handle(e){switch(e.type){case`START`:for(let e of FL)this.trackedCells[e]={};for(let e of this.getters.getSheetIds())for(let t of this.getters.getCells(e))for(let e of FL)Yt(t,e)&&this.history.update(`trackedCells`,e,t.id,t.id);break;case`UPDATE_CELL`:{if(!(`content`in e))return;let t=this.getters.getCell(e);if(!t)return;for(let e of FL)Yt(t,e)?this.history.update(`trackedCells`,e,t.id,t.id):this.trackedCells[e][t.id]&&this.history.update(`trackedCells`,e,t.id,void 0);break}}}getCellsWithTrackedFormula(e){return Object.values(this.trackedCells[e]||{}).filter(t=>t!==void 0&&this.trackedCells[e][t]&&this.getters.tryGetCellPosition(t))}},LL=class extends XI{static getters=[`getRowSize`,`getHeaderSize`,`getMaxAnchorOffset`];tallestCellInRow={};ctx=hd();beforeHandle(e){switch(e.type){case`ADD_COLUMNS_ROWS`:if(e.dimension===`COL`)return;let t=Ct(e.position,e.base),n=Array(e.quantity).fill(void 0),r=It(this.tallestCellInRow[e.sheetId],n,t);this.history.update(`tallestCellInRow`,e.sheetId,r);break}}handle(e){switch(e.type){case`START`:case`UPDATE_LOCALE`:for(let e of this.getters.getSheetIds())this.initializeSheet(e);break;case`CREATE_SHEET`:this.initializeSheet(e.sheetId);break;case`DUPLICATE_SHEET`:{let t=x(this.tallestCellInRow[e.sheetId]);this.history.update(`tallestCellInRow`,e.sheetIdTo,t);break}case`DELETE_SHEET`:let t={...this.tallestCellInRow};delete t[e.sheetId],this.history.update(`tallestCellInRow`,t);break;case`REMOVE_COLUMNS_ROWS`:{if(e.dimension===`COL`)return;let t=Ft(this.tallestCellInRow[e.sheetId],e.elements);this.history.update(`tallestCellInRow`,e.sheetId,t);break}case`RESIZE_COLUMNS_ROWS`:{let t=e.sheetId;if(e.dimension===`ROW`)for(let n of e.elements){let e=this.getRowTallestCell(t,n);this.history.update(`tallestCellInRow`,t,n,e)}else for(let n of C(0,this.getters.getNumberRows(t)))for(let r of e.elements)this.updateRowSizeForCellChange(t,n,r)}break;case`SET_FORMATTING`:if(e.style&&(`fontSize`in e.style||`wrapping`in e.style||`rotation`in e.style))for(let t of e.target)this.updateRowSizeForZoneChange(e.sheetId,t);break;case`UPDATE_CELL`:this.updateRowSizeForCellChange(e.sheetId,e.row,e.col);break;case`ADD_MERGE`:case`REMOVE_MERGE`:for(let t of e.target)for(let n of Bn(t))this.updateRowSizeForCellChange(e.sheetId,n.row,n.col)}}getRowSize(e,t){return Math.round(this.getters.getUserRowSize(e,t)??this.tallestCellInRow[e][t]?.size??23)}getMaxAnchorOffset(e,t,n){let{numberOfRows:r,numberOfCols:i}=this.getters.getSheetSize(e),a=0;for(;a<t&&r>0;r--)a+=this.getRowSize(e,r-1);let o=0;for(;o<n&&i>0;i--)o+=this.getters.getColSize(e,i-1);return{col:i,row:r,offset:{x:o-n,y:a-t}}}getHeaderSize(e,t,n){return this.getters.isHeaderHidden(e,t,n)?0:t===`ROW`?this.getRowSize(e,n):this.getters.getColSize(e,n)}updateRowSizeForZoneChange(e,t){for(let n=t.top;n<=t.bottom;n++){let t=this.getRowTallestCell(e,n);this.history.update(`tallestCellInRow`,e,n,t)}}updateRowSizeForCellChange(e,t,n){let r=this.tallestCellInRow[e]?.[t];if(r?.cell.col===n){let n=this.getRowTallestCell(e,t);this.history.update(`tallestCellInRow`,e,t,n)}let i=this.getCellHeight({sheetId:e,col:n,row:t});if(!(i<=23)&&(!r&&i>23||r&&i>r.size)){let r={cell:{sheetId:e,col:n,row:t},size:i};this.history.update(`tallestCellInRow`,e,t,r)}}initializeSheet(e){let t=[];for(let n=0;n<this.getters.getNumberRows(e);n++){let r=this.getRowTallestCell(e,n);t.push(r)}this.history.update(`tallestCellInRow`,e,t)}getCellHeight(e){if(this.isInMultiRowMerge(e))return 23;let t=this.getters.getCell(e),n=this.getters.getColSize(e.sheetId,e.col);return gd(this.ctx,t,this.getters.getLocale(),n)}isInMultiRowMerge(e){let t=this.getters.getMerge(e);return!!t&&t.bottom!==t.top}getRowTallestCell(e,t){if(this.getters.getUserRowSize(e,t)!==void 0)return;let n=this.getters.getRowCellIds(e,t),r=0,i;for(let e=0;e<n.length;e++){let t=this.getters.getCellById(n[e]);if(!t)continue;let a=this.getters.getCellPosition(t.id),o=this.getCellHeight(a);o>r&&o>23&&(r=o,i={cell:a,size:o})}if(i&&i.size>23)return i}};let RL=`0.00%`;function zL(e){class t extends e{getters;pivotId;cache={};rankAsc={};rankDesc={};runningTotal={};runningTotalInPercent={};constructor(e,t,n){super(t,n),this.getters=n.getters,this.pivotId=e}markAsDirtyForEvaluation(){this.cache={},this.rankAsc={},this.rankDesc={},this.runningTotal={},this.runningTotalInPercent={},super.markAsDirtyForEvaluation?.()}getPivotCellValueAndFormat(e,t){return this.getMeasureDisplayValue(e,t)}_getPivotCellValueAndFormat(e,t){let n=`${e}-${t.map(e=>e.field+`=`+e.value).join(`,`)}`;if(this.cache[n])return this.cache[n];let r=this.getMeasure(e),i=r.computedBy?this.computeMeasure(r,t):super.getPivotCellValueAndFormat(e,t);return r.format?this.cache[n]={...i,format:r.format}:this.cache[n]=i,this.cache[n]}computeMeasure(e,t){if(!e.computedBy)return{value:0};let{columns:n,rows:r}=super.definition;if(e.aggregator&&n.length+r.length!==t.length){let n=this.getValuesToAggregate(e,t),r=vg[e.aggregator];if(!r)return{value:0};try{return r([n],this.getters.getLocale())}catch(t){return ko(t,e.aggregator.toUpperCase())}}let i=this.getters.getMeasureCompiledFormula(this.pivotId,e),a=this.getters.evaluateCompiledFormula(e.computedBy.sheetId,i,e=>{let{columns:n,rows:r}=this.definition;if(n.find(t=>t.nameWithGranularity===e)){let{colDomain:n}=mj(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new Ri:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}if(r.find(t=>t.nameWithGranularity===e)){let{rowDomain:n}=mj(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new Ri:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}return this.getPivotCellValueAndFormat(e,t)});return Je(a)?a[0][0]:a}getValuesToAggregate(e,t){let{rowDomain:n,colDomain:r}=mj(this,t),i=super.getExpandedTableStructure(),a=[];if(r.length===0&&n.length<this.definition.rows.length&&this.definition.rows.length&&this.definition.columns.length){let t=this.treeToLeafDomains(i.getColTree()),r=this.getSubTreeMatchingDomain(i.getRowTree(),n),o=this.treeToLeafDomains(r);for(let r of t)for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t).concat(r)));return a}else if(n.length===this.definition.rows.length&&r.length===0){let t=i.getColTree(),o=this.getSubTreeMatchingDomain(t,r),s=this.treeToLeafDomains(o,r);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else if(n.length===this.definition.rows.length&&r.length&&r.length<this.definition.columns.length){let t=this.getSubTreeMatchingDomain(i.getColTree(),r),o=this.treeToLeafDomains(t,r);for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else{let t=i.getRowTree(),o=this.getSubTreeMatchingDomain(t,n),s=this.treeToLeafDomains(o,n);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,t.concat(r)));return a}}getSubTreeMatchingDomain(e,t,n=0){if(n>t.length)return[];if(t.length===n)return e;for(let r of e){let e=Dg(this.definition.getDimension(r.field),t[n]?.value);if(r.field===t[n]?.field&&r.value===e)return this.getSubTreeMatchingDomain(r.children,t,n+1)}return[]}treeToLeafDomains(e,t=[]){let n=[];for(let r of e){let e=this.definition.getDimension(r.field),i=[...t,{field:r.field,value:r.value,type:e.type}];r.children.length===0?n.push(i):n.push(...this.treeToLeafDomains(r.children,i))}return n}getMeasureDisplayValue(e,t){let n=this.getMeasure(e),r=this._getPivotCellValueAndFormat(e,t);if(!n.display||n.display.type===`no_calculations`||r.message)return r;let i=n.display.fieldNameWithGranularity;if(i&&!this.isFieldInPivot(i))return{value:M.NotAvailable,message:j(`Field "%s" not found in pivot for measure display calculation`,i)};try{let e=n.display;switch(e.type){case`%_of_grand_total`:return this.asPercentOfGrandTotal(r,n);case`%_of_col_total`:return this.asPercentOfColumnTotal(r,n,t);case`%_of_row_total`:return this.asPercentOfRowTotal(r,n,t);case`%_of_parent_row_total`:return this.asPercentOfParentRowTotal(r,n,t);case`%_of_parent_col_total`:return this.asPercentOfParentColumnTotal(r,n,t);case`index`:return this.asIndex(r,n,t);case`%_of_parent_total`:return this.asPercentOfParentTotal(r,n,t,e);case`running_total`:return this.asRunningTotal(r,n,t,e,`running_total`);case`%_running_total`:return this.asRunningTotal(r,n,t,e,`%_running_total`);case`rank_asc`:return this.asRank(r,n,t,e,`asc`);case`rank_desc`:return this.asRank(r,n,t,e,`desc`);case`%_of`:return this.asPercentOf(r,n,t,e);case`difference_from`:return this.asDifferenceFrom(r,n,t,e);case`%_difference_from`:return this.asDifferenceFromInPercent(r,n,t,e)}return r}catch(e){return ko(e,`COMPUTE_MEASURE_DISPLAY_VALUE`)}}asPercentOfGrandTotal(e,t){let n=this.getGrandTotal(t.id);return n===0?{value:M.DivisionByZero}:{value:this.measureValueToNumber(e)/n,format:RL}}asPercentOfRowTotal(e,t,n){let r=this.getRowTotal(t.id,n);return r===0?{value:M.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:RL}}asPercentOfColumnTotal(e,t,n){let r=this.getColumnTotal(t.id,n);return r===0?{value:M.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:RL}}asPercentOfParentRowTotal(e,t,n){let r=fj(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:RL}}asPercentOfParentColumnTotal(e,t,n){let r=pj(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:RL}}asPercentOfParentTotal(e,t,n,r){let{fieldNameWithGranularity:i}=r;if(!i)return e;if(!Sj(i,n))return{value:``};let a=bj(this,i,n),o=this._getPivotCellValueAndFormat(t.id,a),s=this.measureValueToNumber(o);return s===0?{value:``}:{value:this.measureValueToNumber(e)/s,format:RL}}asIndex(e,t,n){let r=this.measureValueToNumber(e),i=this.getRowTotal(t.id,n),a=this.getColumnTotal(t.id,n),o=this.getGrandTotal(t.id);return i===0||a===0?{value:M.DivisionByZero}:{value:r*o/(a*i),format:void 0}}asRunningTotal(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;let o=i===`running_total`?this.runningTotal:this.runningTotalInPercent,s=o[t.id]?.[a];s||(s=this.computeRunningTotal(t,a,i),o[t.id]||(o[t.id]={}),o[t.id][a]=s);let{rowDomain:c,colDomain:l}=mj(this,n),u=Tj(l),d=Tj(c),f=s[u]?.[d];return f===void 0&&(f=this.getPreviousRunningTotalValue(a,n,s)),{value:f??``,format:i===`running_total`?e.format:RL}}asPercentOf(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!Sj(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0||o===`sameValue`&&s===0?{value:M.DivisionByZero}:!o||o===`sameValue`&&!s?{value:``}:o===`sameValue`?{value:1,format:RL}:s===void 0?{value:M.NullError}:{value:s/o,format:RL}}asDifferenceFrom(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!Sj(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a)||0;return o===`sameValue`?{value:``}:{value:this.measureValueToNumber(e)-o,format:e.format}}asDifferenceFromInPercent(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!Sj(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0?{value:M.DivisionByZero}:!o||o===`sameValue`?{value:``}:s===void 0?{value:M.NullError}:{value:(s-o)/o,format:RL}}asRank(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;if(!Sj(a,n))return{value:``};let o=i===`asc`?this.rankAsc:this.rankDesc,s=o[t.id]?.[a];s||(s=this.computeRank(t,a,i),o[t.id]||(o[t.id]={}),o[t.id][a]=s);let{rowDomain:c,colDomain:l}=mj(this,n),u=Tj(l),d=Tj(c);return{value:s[u]?.[d]??``}}computeRank(e,t,n){let r={},i=Cj(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=uo(o));for(let s of o){let o=Tj(hj(this,a,s[0].domain)),c=s.map(t=>({...t,value:this.strictMeasureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain)),rowDomain:hj(this,i,t.domain)})).filter(e=>Sj(t,e.rowDomain)),l=Object.groupBy(c,e=>Dj(e.rowDomain,t));for(let e in l)l[e]=Wt(l[e]||[],e=>e.value).filter(e=>e.value!==void 0).sort((e,t)=>n===`asc`?e.value-t.value:t.value-e.value);r[o]={};for(let e of c){let n=Tj(hj(this,i,e.domain)),a=l[Dj(e.rowDomain,t)];if(!a)continue;let s=a.findIndex(t=>t.value===e.value);s!==-1&&(r[o][n]=s+1)}}return i===`row`?r:Gt(r)}computeRunningTotal(e,t,n){let r={},i=Cj(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=uo(o));for(let s of o){let o=Tj(hj(this,a,s[0].domain));r[o]={};let c={},l=s.map(t=>({...t,rowDomain:hj(this,i,t.domain),value:this.measureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain))})).filter(e=>Sj(t,e.rowDomain));for(let e of l){let n=Tj(e.rowDomain),i=Oj(e.rowDomain,t),a=(c[i]||0)+e.value;c[i]=a,r[o][n]=a}if(n===`%_running_total`)for(let e of l){let n=e.rowDomain,i=Tj(n),a=Oj(n,t),s=r[o][i]||0,l=c[a];r[o][i]=l?s/l:void 0}}return i===`row`?r:Gt(r)}getPreviousRunningTotalValue(e,t,n){let r=this.definition.getDimension(e);if(r.type!==`date`&&r.type!==`datetime`)return;let i=Cj(this,e),{rowDomain:a,colDomain:o}=mj(this,t),s=i===`row`?a:o,c=i===`row`?o:a,l=s.find(t=>t.field===e)?.value;if(l===void 0)return;let u=Tj(c),d=Oj(s,e),f,p,m=this.getCollapsedTableStructure(),h=i===`row`?m.getRowTree():m.getColTree(),g=(t,n=[])=>{for(let i of t){let t=[...n,{field:i.field,value:i.value,type:i.type}];i.children.length&&g(i.children,t);let a=t.find(t=>t.field===e)?.value,o=Oj(t,e);a===void 0||o!==d||this.compareRunningTotalValues(a,l,r)>=0||(p===void 0||this.compareRunningTotalValues(p,a,r)<0)&&(p=a,f=Tj(t))}};if(g(h),f)return i===`row`?n[u]?.[f]:n[f]?.[u]}compareRunningTotalValues(e,t,n){let r=n.order??`asc`,i=e===null,a=t===null;if(i&&a)return 0;if(i)return r===`asc`?1:-1;if(a)return r===`asc`?-1:1;let o=this.getRunningTotalComparableValue(e,n)-this.getRunningTotalComparableValue(t,n);return r===`asc`?o:-o}getRunningTotalComparableValue(e,t){let n=t.granularity;if(n&&$h.contains(n)){let t=eg(n).toComparableValue?.(e);if(t!==void 0)return t}return I(e,V)}getGrandTotal(e){let t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){let n=mj(this,t).rowDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}getColumnTotal(e,t){let n=mj(this,t).colDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}isFieldInPivot(e){return this.definition.columns.some(t=>t.nameWithGranularity===e)||this.definition.rows.some(t=>t.nameWithGranularity===e)}getComparisonValue(e,t,n,r){let i=r===`(previous)`||r===`(next)`?wj(this,t,n,r):xj(t,n,r);if(T(i,t))return`sameValue`;if(!i||!_j(this,i))throw new Ri;let a=this._getPivotCellValueAndFormat(e.id,i);return this.strictMeasureValueToNumber(a)}getPivotValueCells(e){return this.getCollapsedTableStructure().getPivotCells().map(t=>t.filter(t=>t.type===`VALUE`&&t.measure===e)).filter(e=>e.length>0)}measureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(!e.value)return 0;throw Error(`Value ${e.value} is not a number`)}strictMeasureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(e.value)throw Error(`Value ${e.value} is not a number`)}getCollapsedTableStructure(){let e=super.getCollapsedTableStructure();return this.sortTableStructure(e),e}getExpandedTableStructure(){let e=super.getExpandedTableStructure();return this.sortTableStructure(e),e}sortTableStructure(e){if(!this.definition.sortedColumn||e.isSorted)return;let t=this.definition.sortedColumn.measure;Fg(this.definition.sortedColumn,this)&&e.sort(t,this.definition.sortedColumn,(e,t)=>this._getPivotCellValueAndFormat(e,t))}}return t}let BL=[`ADD_PIVOT`,`UPDATE_PIVOT`,`REMOVE_PIVOT`];function VL(e){return BL.includes(e.type)}var HL=class extends XI{static getters=[`getPivot`,`getFirstPivotFunction`,`getPivotCellSortDirection`,`getPivotIdFromPosition`,`getPivotIdsFromPosition`,`getPivotCellFromPosition`,`generateNewCalculatedMeasureName`,`isPivotUnused`,`isSpillPivotFormula`,`getAllPivotArrayFormulas`,`getPivotStyleAtPosition`];pivots={};unusedPivotsInFormulas;custom;pivotPositionCache=new tN;shouldInvalidateCache=!1;constructor(e){super(e),this.custom=e.custom}beforeHandle(e){switch(e.type){case`START`:for(let e of this.getters.getPivotIds())this.setupPivot(e)}}handle(e){if(hu.has(e.type)){this.shouldInvalidateCache=!0;for(let e of this.getters.getPivotIds())this.setupPivot(e,{recreate:!0})}switch(e.type===`UPDATE_CELL`&&(this.shouldInvalidateCache=!0),e.type){case`REFRESH_PIVOT`:this.refreshPivot(e.id);break;case`ADD_PIVOT`:this.unusedPivotsInFormulas?.push(e.pivotId),this.setupPivot(e.pivotId);break;case`DUPLICATE_PIVOT`:this.unusedPivotsInFormulas?.push(e.newPivotId),this.setupPivot(e.newPivotId);break;case`UPDATE_PIVOT`:this.setupPivot(e.pivotId,{recreate:!0});break;case`DELETE_SHEET`:case`UPDATE_CELL`:this.unusedPivotsInFormulas=void 0;break;case`UNDO`:case`REDO`:{this.unusedPivotsInFormulas=void 0;let t=e.commands.filter(VL);for(let e of t){let t=e.pivotId;this.getters.isExistingPivot(t)&&this.setupPivot(t,{recreate:!0})}break}case`UPDATE_LOCALE`:Yg();break}}finalize(){this.shouldInvalidateCache&&=(this.pivotPositionCache=new tN,!1)}getPivotIdFromPosition(e){return this.getPivotIdsFromPosition(e)[0]}getPivotIdsFromPosition(e){if(!this.pivotPositionCache.has(e)){let t=this.getters.getCorrespondingFormulaCell(e);if(t&&t.isFormula){let n=this.getPivotIdsFromFormula(e.sheetId,t.compiledFormula);this.pivotPositionCache.set(e,n)}}return this.pivotPositionCache.get(e)||[]}getPivotIdsFromFormula(e,t){return this.getPivotFunctions(e,t).map(e=>{let t=e.args[0]?.toString();return t&&this.getters.getPivotId(t)}).filter(w)}isSpillPivotFormula(e){let t=this.getters.getCorrespondingFormulaCell(e);return t&&t.isFormula?this.getFirstPivotFunction(e.sheetId,t.compiledFormula)?.functionName===`PIVOT`:!1}getPivotFunctions(e,t){let n=Yj(t,this.getters);if(!n.length)return[];let r=[];for(let t of n){let{functionName:n,args:i}=t,a=i.map(t=>{if(t.type===`EMPTY`)return;if(t.type===`STRING`||t.type===`BOOLEAN`||t.type===`NUMBER`)return t.value;let n=xF(t);return this.getters.evaluateFormula(e,n)});r.push({functionName:n,args:a})}return r}getFirstPivotFunction(e,t){return this.getPivotFunctions(e,t)[0]}getPivotCellFromPosition(e){let t=this.getters.getCorrespondingFormulaCell(e);if(!t||!t.isFormula||Xj(t.compiledFormula,this.getters)===0)return Mj;let n=this.getters.getCellPosition(t.id),r=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula);if(!r)return Mj;let{functionName:i,args:a}=r,o=a[0];if(!o)return Mj;let s=this.getters.getPivotId(o.toString());if(!s)return Mj;let c=this.getPivot(s);if(!c.isValid()||i===`PIVOT`&&!this.isMainFunctionPivotSpreadFunction(t))return Mj;try{if(i===`PIVOT`){let t=Ug(this.getters.getPivotCoreDefinition(s),bh(a[1]),bh(a[2]),bh(a[3]),bh(a[4]),bh(a[5]),this.getters.getLocale()),r=c.getCollapsedTableStructure().getPivotCells(t),i=e.col-n.col,o=e.row-n.row;return r[i][o]}let t=e.row-n.row,r=e.col-n.col;if(a=a.map(e=>Je(e)?e[r][t]:e),i===`PIVOT.HEADER`&&a.at(-2)===`measure`)return{type:`MEASURE_HEADER`,domain:c.parseArgsToPivotDomain(a.slice(1,-2).map(e=>({value:e}))),measure:a.at(-1)?.toString()||``};if(i===`PIVOT.HEADER`){let e=c.parseArgsToPivotDomain(a.slice(1).map(e=>({value:e})));return{type:`HEADER`,domain:e,dimension:mj(c,e).colDomain.length?`COL`:`ROW`}}let[o,...l]=a.slice(1);return{type:`VALUE`,domain:c.parseArgsToPivotDomain(l.map(e=>({value:e}))),measure:o?.toString()||``}}catch{return Mj}}generateNewCalculatedMeasureName(e){let t=e.map(e=>e.fieldName);return Kt(j(`Calculated measure 1`),t,{compute:(e,t)=>j(`Calculated measure %s`,t)})}getPivot(e){if(!this.getters.isExistingPivot(e))throw Error(`pivot ${e} not found`);return this.pivots[e]}isPivotUnused(e){let{type:t}=this.getters.getPivot(e);return this._getUnusedPivotsInFormulas().includes(e)&&Uj.get(t).isPivotUnused(this.getters,e)}getPivotCellSortDirection(e){let t=this.getters.getPivotIdFromPosition(e),n=this.getters.getPivotCellFromPosition(e);if(n.type===`EMPTY`||n.type===`HEADER`||n.type===`ROW_GROUP_NAME`||!t)return;let r=this.getters.getPivot(t),i=mj(r,n.domain).colDomain,a=r.definition.sortedColumn;return a?.measure===n.measure&&T(a.domain,i)?a.order:`none`}refreshPivot(e){this.getters.getPivot(e).init({reload:!0})}setupPivot(e,{recreate:t}={recreate:!1}){let n=x(this.getters.getPivotCoreDefinition(e));if(e in this.pivots)t&&this.pivots[e].onDefinitionChange(n);else{let t=zL(Uj.get(n.type).ui);this.pivots[e]=new t(e,this.custom,{definition:n,getters:this.getters})}}_getUnusedPivotsInFormulas(){if(this.unusedPivotsInFormulas!==void 0)return this.unusedPivotsInFormulas;let e=new Set(this.getters.getPivotIds());for(let t of this.getters.getSheetIds())for(let n of this.getters.getCells(t)){let t=this.getters.getCellPosition(n.id),r=this.getPivotIdsFromPosition(t);for(let t of r)if(e.delete(t),!e.size)return this.unusedPivotsInFormulas=[],[]}for(let t of this.getters.getPivotIds()){let n=this.getters.getPivotCoreDefinition(t);for(let r of n.measures)if(r.computedBy){let{sheetId:n}=r.computedBy,i=this.getters.getMeasureCompiledFormula(t,r),a=this.getPivotIdsFromFormula(n,i);for(let t of a)if(e.delete(t),!e.size)return this.unusedPivotsInFormulas=[],[]}}return this.unusedPivotsInFormulas=[...e],this.unusedPivotsInFormulas}getAllPivotArrayFormulas(){let e=[];for(let t of this.getters.getCellsWithTrackedFormula(`PIVOT`)){let n=this.getters.getCellPosition(t);if(this.getters.getEvaluatedCell(n).type===`error`)continue;let r=this.getPivotStyleAtPosition(n);r&&e.push({position:n,...r})}return e}getPivotStyleAtPosition(e){e=this.getters.getArrayFormulaSpreadingOn(e)||e;let t=this.getters.getCell(e);if(!t||!t.isFormula||!this.isMainFunctionPivotSpreadFunction(t))return;let n=this.getFirstPivotFunction(e.sheetId,t.compiledFormula);if(!n||n.functionName!==`PIVOT`)return;let r=n.args[0];if(!r)return;let i=this.getters.getPivotId(r.toString());if(i)return{pivotStyle:Ug(this.getters.getPivotCoreDefinition(i),bh(n.args[1]),bh(n.args[2]),bh(n.args[3]),bh(n.args[4]),bh(n.args[5]),this.getters.getLocale()),pivotId:i}}isMainFunctionPivotSpreadFunction(e){return e.compiledFormula.isFirstNonWhitespaceSymbol(`PIVOT`)}},UL=class{getters;dispatch;constructor(e,t){this.getters=e,this.dispatch=t}copy(e,t,n=`copyPaste`){}paste(e,t,n){}isPasteAllowed(e,t,n,r){return`Success`}isCutAllowed(e){return`Success`}getPasteTarget(e,t,n,r){return{zones:[],sheetId:e}}convertTextToClipboardData(e){}},WL=class extends UL{copy(e,t,n=`copyPaste`){}pasteFromCopy(e,t,n,r){if(t.length===1)for(let i of qT(t,n))this.pasteZone(e,i.left,i.top,n,r);else for(let i of cn(t))for(let t=i.left;t<=i.right;t++)for(let a=i.top;a<=i.bottom;a++)this.pasteZone(e,t,a,n,r)}pasteZone(e,t,n,r,i){}},GL=class extends WL{isCutAllowed(e){return e.zones.length===1?`Success`:`WrongCutSelection`}copy(e,t,n=`copyPaste`){let r=e.sheetId,{clippedZones:i,rowsIndexes:a,columnsIndexes:o}=e,s=[],c=a.length===1&&o.length===1;for(let t of a){let i=[];for(let s of o){let l={col:s,row:t,sheetId:r},u=this.getters.getCell(l),d=this.getters.getEvaluatedCell(l),f=this.getters.getPivotIdFromPosition(l),p=this.getters.getArrayFormulaSpreadingOn(l);if(n!==`shiftCells`&&f&&p){let t=this.getters.getSpreadZone(p);if((!T(p,l)||!c)&&t&&!e.zones.some(e=>In(t,e))){let e=this.getters.getPivotCellFromPosition(l),t=Eg(this.getters.getPivotFormulaId(f),e);u={id:u?.id??0,style:u?.style,format:u?.format,content:t,isFormula:!1,parsedValue:d.value}}}else if(n!==`shiftCells`&&p&&!T(p,l)){let e=a.includes(p.row)&&o.includes(p.col)?``:H(d.value,{locale:this.getters.getLocale()});u={id:u?.id??0,style:u?.style,format:d.format,content:e,isFormula:!1,parsedValue:d.value}}i.push({content:u?.isFormula?u.compiledFormula.toFormulaString(this.getters):u?.content??``,style:u?.style,format:u?.format,compiledFormula:u?.isFormula?u?.compiledFormula:void 0,border:this.getters.getCellBorder(l)||void 0,evaluatedCell:d,position:l})}s.push(i)}return{cells:s,zones:i,sheetId:e.sheetId}}isPasteAllowed(e,t,n,r){if(!n.cells)return`Success`;if(r?.isCutOperation&&r?.pasteOption!==void 0)return`WrongPasteOption`;if(t.length>1&&(n.cells.length>1||n.cells[0].length>1))return`WrongPasteSelection`;let i=n.cells.length,a=n.cells[0].length;for(let r of qT(t,n.cells))if(this.getters.doesIntersectMerge(e,r)&&(t.length>1||!this.getters.isSingleCellOrMerge(e,t[0])||i*a!==1))return`WillRemoveExistingMerge`;return`Success`}paste(e,t,n){let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t,n):this.pasteFromCopy(i,r,t.cells,n)}getPasteTarget(e,t,n,r){let i=n.cells[0].length,a=n.cells.length;return r?.isCutOperation?{sheetId:e,zones:[{left:t[0].left,top:t[0].top,right:t[0].left+i-1,bottom:t[0].top+a-1}]}:i===1&&a===1?{zones:[],sheetId:e}:{sheetId:e,zones:qT(t,n.cells)}}pasteFromCut(e,t,n,r){this.clearClippedZones(n);let i=t[0];this.pasteZone(e,i.left,i.top,n.cells,r)}clearClippedZones(e){this.dispatch(`CLEAR_CELLS`,{sheetId:e.sheetId,target:e.zones}),this.dispatch(`CLEAR_FORMATTING`,{sheetId:e.sheetId,target:e.zones})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){if(!s)continue;let o={col:t+r,row:n+a,sheetId:e};this.pasteCell(s,o,i)}}pasteCell(e,t,n){let{sheetId:r,col:i,row:a}=t,o=this.getters.getEvaluatedCell(t),s=e?.format||e.evaluatedCell.format;if(n?.pasteOption===`asValue`){this.dispatch(`UPDATE_CELL`,{...t,content:e.evaluatedCell.value?.toString()||``});return}if(n?.pasteOption===`onlyFormat`){this.dispatch(`UPDATE_CELL`,{...t,style:e?.style??null,format:s??o.format});return}let c=e?.content;e?.compiledFormula?.hasDependencies&&!n?.isCutOperation?c=this.getters.getTranslatedCellFormula(r,i-e.position.col,a-e.position.row,e.compiledFormula):e?.compiledFormula?.hasDependencies&&(c=this.getters.getFormulaMovedInSheet(r,e.compiledFormula)),c!==``||e?.format||e?.style?this.dispatch(`UPDATE_CELL`,{...t,content:c,style:e?.style||null,format:e?.format}):o&&this.dispatch(`CLEAR_CELL`,t)}convertTextToClipboardData(e){let t=this.getters.getLocale(),n={cells:[]},r=[],i=0;for(let[t,n]of e.replace(/\r/g,``).split(`
114
+ />`;static defaultProps={topOffset:0};get offset(){return this.env.model.getters.getActiveSheetScrollInfo().scrollY}get height(){return this.env.model.getters.getMainViewportRect().height}get isDisplayed(){let{yRatio:e}=this.env.model.getters.getFrozenSheetViewRatio(this.env.model.getters.getActiveSheetId());return e<1}get position(){let{y:e}=this.env.model.getters.getMainViewportRect(),t=this.env.model.getters.getScrollBarWidth();return{top:`${this.props.topOffset+e}px`,right:`0px`,width:`${t}px`,bottom:Om()?`${t}px`:`0`}}onScroll(e){let{scrollX:t}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:t,offsetY:e})}},pI=class extends t.Component{static template=`o-spreadsheet-Selection`;static props={};static components={Highlight:cI};get highlightProps(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getUnboundedZone(e,this.env.model.getters.getSelectedZone());return{range:this.env.model.getters.getRangeFromZone(e,t),color:ae}}},mI=class extends t.Component{static template=`o-spreadsheet-TableResizer`;static props={table:Object};state=(0,t.useState)({highlightZone:void 0});dragNDropGrid=QP(this.env);setup(){dk(this)}get containerStyle(){let e=this.props.table.range.zone,t=this.props.table.range.sheetId;if(this.env.model.getters.isReadonly()||this.env.model.getters.isSheetLocked(t))return W({display:`none`});let n={...e,left:e.right,top:e.bottom},r=this.env.model.getters.getVisibleRect(n);return r.height===0||r.width===0?W({display:`none`}):W({top:`${r.y+r.height-6}px`,left:`${r.x+r.width-6}px`})}onMouseDown(e){let t=this.props.table.range.zone,n={col:t.left,row:t.top};document.body.style.cursor=`nwse-resize`;let r=Pm(this.env,e);this.dragNDropGrid.start(r,(e,t,r)=>{this.state.highlightZone={left:n.col,top:n.row,right:Math.max(e,n.col),bottom:Math.max(t,n.row)}},()=>{document.body.style.cursor=``;let e=this.state.highlightZone;if(!e)return;let t=this.props.table.range.sheetId;this.env.model.dispatch(`RESIZE_TABLE`,{sheetId:t,zone:this.props.table.range.zone,newTableRange:this.env.model.getters.getRangeDataFromZone(t,e)}),this.state.highlightZone=void 0})}get highlights(){return this.state.highlightZone?[{range:this.env.model.getters.getRangeFromZone(this.props.table.range.sheetId,this.state.highlightZone),color:`#777`,noFill:!0}]:[]}};let hI={ROW:YP,COL:HP,CELL:kP,GROUP_HEADERS:qP,UNGROUP_HEADERS:JP};var gI=class extends t.Component{static template=`o-spreadsheet-Grid`;static props={exposeFocus:Function,getGridSize:Function};static components={GridComposer:DF,GridOverlay:GF,GridPopover:KF,HeadersOverlay:QF,MenuPopover:wy,Autofill:eF,ClientTag:nF,Highlight:cI,Popover:by,VerticalScrollBar:fI,HorizontalScrollBar:dI,TableResizer:mI,Selection:pI};HEADER_HEIGHT=26;HEADER_WIDTH=48;menuState;gridRef;highlightStore;cellPopovers;composerFocusStore;DOMFocusableElementStore;paintFormatStore;clientFocusStore;dragNDropGrid=QP(this.env);onMouseWheel;hoveredCell;sidePanel;setup(){this.highlightStore=O(cT),this.menuState=(0,t.useState)({isOpen:!1,anchorRect:null,menuItems:[]}),this.gridRef=(0,t.useRef)(`grid`),this.hoveredCell=O(My),this.composerFocusStore=O(Er),this.DOMFocusableElementStore=O(ly),this.sidePanel=O($M),this.paintFormatStore=O(VF),this.clientFocusStore=O(ZP),O(XP),(0,t.useChildSubEnv)({getPopoverContainerRect:()=>this.getGridRect()}),(0,t.useExternalListener)(document.body,`cut`,this.copy.bind(this,!0)),(0,t.useExternalListener)(document.body,`copy`,this.copy.bind(this,!1)),(0,t.useExternalListener)(document.body,`paste`,this.paste),(0,t.onMounted)(()=>this.focusDefaultElement()),this.props.exposeFocus(()=>this.focusDefaultElement()),eI({refName:`canvas`,renderingCtx:()=>({dpr:window.devicePixelRatio||1,viewports:this.env.model.getters.getViewportCollection(),...this.env.model.getters.getSelectionState()})}),this.onMouseWheel=iI((e,t)=>{this.moveCanvas(e,t),this.hoveredCell.clear()}),this.cellPopovers=O(vw),(0,t.useEffect)((e,t)=>{!e&&!t&&this.DOMFocusableElementStore.focus()},()=>[this.sidePanel.isMainPanelOpen,this.sidePanel.isSecondaryPanelOpen]),nI(this.gridRef,{updateScroll:this.moveCanvas.bind(this),canMoveUp:()=>{let{scrollY:e}=this.env.model.getters.getActiveSheetScrollInfo();return e>0},canMoveDown:()=>{let{maxOffsetY:e}=this.env.model.getters.getMaximumSheetOffset(),{scrollY:t}=this.env.model.getters.getActiveSheetScrollInfo();return t<e},getZoom:()=>this.env.model.getters.getViewportZoomLevel(),setZoom:e=>this.env.model.dispatch(`SET_ZOOM`,{zoom:e})})}get highlights(){return this.highlightStore.highlights}get gridOverlayDimensions(){let e=this.env.model.getters.getScrollBarWidth();return W({top:`26px`,left:`48px`,height:`calc(100% - ${26+e}px)`,width:`calc(100% - ${48+e}px)`})}onClosePopover(){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.focusDefaultElement()}keyDownMapping={Enter:()=>this.editOrMoveInSelection(`down`),"Shift+Enter":()=>this.editOrMoveInSelection(`up`),Tab:()=>this.moveInSelection(`right`),"Shift+Tab":()=>this.moveInSelection(`left`),F2:()=>{this.focusComposerFromActiveCell()},Delete:()=>{this.env.model.dispatch(`DELETE_UNFILTERED_CONTENT`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Backspace:()=>{this.env.model.dispatch(`DELETE_UNFILTERED_CONTENT`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})},Escape:()=>{this.cellPopovers.isOpen?this.cellPopovers.close():this.menuState.isOpen?this.closeMenu():this.paintFormatStore.isActive?this.paintFormatStore.cancel():this.env.model.dispatch(`CLEAN_CLIPBOARD_HIGHLIGHT`)},"Ctrl+A":()=>this.env.model.selection.loopSelection(),"Ctrl+Z":()=>this.env.model.dispatch(`REQUEST_UNDO`),"Ctrl+Y":()=>this.env.model.dispatch(`REQUEST_REDO`),F4:()=>this.env.model.dispatch(`REQUEST_REDO`),"Ctrl+B":()=>this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{bold:!this.env.model.getters.getCurrentStyle().bold}}),"Ctrl+I":()=>this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{italic:!this.env.model.getters.getCurrentStyle().italic}}),"Ctrl+U":()=>this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{underline:!this.env.model.getters.getCurrentStyle().underline}}),"Ctrl+O":()=>VE(this.env),"Alt+=":()=>{let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone(),{anchor:n}=this.env.model.getters.getSelection(),r=this.env.model.getters.getAutomaticSums(e,t,n.cell);if(this.env.model.getters.isSingleCellOrMerge(e,t)||this.env.model.getters.isEmpty(e,t)&&r.length<=1){let t=r[0]?.zone?this.env.model.getters.zoneToXC(e,r[0].zone):``,n=`=SUM(${t})`;this.onComposerCellFocused(n,{start:5,end:5+t.length})}else this.env.model.dispatch(`SUM_SELECTION`)},"Alt+Enter":()=>{let e=this.env.model.getters.getActiveCell();e.link&&Fu(e.link,this.env)},"Ctrl+Home":()=>{let e=this.env.model.getters.getActiveSheetId(),{col:t,row:n}=this.env.model.getters.getNextVisibleCellPosition({sheetId:e,col:0,row:0});this.env.model.selection.selectCell(t,n)},"Ctrl+End":()=>{let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.findVisibleHeader(e,`COL`,this.env.model.getters.getNumberCols(e)-1,0),n=this.env.model.getters.findVisibleHeader(e,`ROW`,this.env.model.getters.getNumberRows(e)-1,0);this.env.model.selection.selectCell(t,n)},"Shift+ ":()=>{let e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),left:0,right:this.env.model.getters.getNumberCols(e)-1},n=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:n,zone:t})},"Ctrl+ ":()=>{let e=this.env.model.getters.getActiveSheetId(),t={...this.env.model.getters.getSelectedZone(),top:0,bottom:this.env.model.getters.getNumberRows(e)-1},n=this.env.model.getters.getActivePosition();this.env.model.selection.selectZone({cell:n,zone:t})},"Ctrl+D":()=>{fw(this.env,{type:`COPY_PASTE_CELLS_ABOVE`})},"Ctrl+R":()=>{fw(this.env,{type:`COPY_PASTE_CELLS_ON_LEFT`})},"Ctrl+Enter":()=>{fw(this.env,{type:`COPY_PASTE_CELLS_ON_ZONE`})},"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":()=>gE(this.env),"Ctrl+Shift+<":()=>this.clearFormatting(),"Ctrl+<":()=>this.clearFormatting(),"Ctrl+Shift+ ":()=>{this.env.model.selection.selectAll()},"Ctrl+Alt+=":()=>{let e=this.env.model.getters.getActiveCols(),t=this.env.model.getters.getActiveRows(),n=this.env.model.getters.getSelectedZones().length===1,r=e.size>0&&n,i=t.size>0&&n;r&&!i?ME(this.env):i&&!r&&AE(this.env)},"Ctrl+Alt+-":()=>{let e=[...this.env.model.getters.getActiveCols()],t=[...this.env.model.getters.getActiveRows()];e.length>0&&t.length===0?this.env.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:this.env.model.getters.getActiveSheetId(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:`COL`,elements:e}):t.length>0&&e.length===0&&this.env.model.dispatch(`REMOVE_COLUMNS_ROWS`,{sheetId:this.env.model.getters.getActiveSheetId(),sheetName:this.env.model.getters.getActiveSheetName(),dimension:`ROW`,elements:t})},"Shift+PageDown":()=>{this.env.model.dispatch(`ACTIVATE_NEXT_SHEET`)},"Shift+PageUp":()=>{this.env.model.dispatch(`ACTIVATE_PREVIOUS_SHEET`)},"Shift+F11":()=>{PD.execute?.(this.env)},"Alt+T":()=>{xD.execute?.(this.env)},PageDown:()=>this.env.model.dispatch(`SHIFT_VIEWPORT_DOWN`),PageUp:()=>this.env.model.dispatch(`SHIFT_VIEWPORT_UP`),"Ctrl+K":()=>{this.closeMenu(),WE(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`)};focusComposerFromActiveCell(){this.env.model.getters.getActiveCell().type===`empty`?this.onComposerCellFocused():this.onComposerContentFocused()}editOrMoveInSelection(e){if(this.isSingleCellOrMergeSelection()){this.focusComposerFromActiveCell();return}Fw(this.env.model.getters,this.env.model.selection,e)}moveInSelection(e){if(this.isSingleCellOrMergeSelection()){this.env.model.selection.moveAnchorCell(e,1);return}Fw(this.env.model.getters,this.env.model.selection,e)}isSingleCellOrMergeSelection(){let e=this.env.model.getters.getActiveSheetId(),t=this.env.model.getters.getSelectedZone();return this.env.model.getters.isSingleCellOrMerge(e,t)}focusDefaultElement(){!this.env.model.getters.getSelectedFigureId()&&this.composerFocusStore.activeComposer.editionMode===`inactive`&&this.DOMFocusableElementStore.focus()}get gridEl(){if(!this.gridRef.el)throw Error(`Grid el is not defined.`);return this.gridRef.el}getAutofillPosition(){let e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect(e);return{x:t.x+t.width-8/2,y:t.y+t.height-8/2}}get isAutofillVisible(){if(this.env.model.getters.isCurrentSheetLocked())return!1;let e=this.env.model.getters.getSelectedZone(),t=this.env.model.getters.getVisibleRect({left:e.right,right:e.right,top:e.bottom,bottom:e.bottom});return!(t.width===0||t.height===0)}onGridResized(){let{height:e,width:t}=this.props.getGridSize();this.env.model.dispatch(`RESIZE_SHEETVIEW`,{width:t-48,height:e-26,gridOffsetX:48,gridOffsetY:26})}moveCanvas(e,t){let{scrollX:n,scrollY:r}=this.env.model.getters.getActiveSheetScrollInfo();this.env.model.dispatch(`SET_VIEWPORT_OFFSET`,{offsetX:n+e,offsetY:r+t})}processSpaceKey(e){this.env.model.getters.hasBooleanValidationInZones(this.env.model.getters.getSelectedZones())&&(e.preventDefault(),e.stopPropagation(),this.env.model.dispatch(`TOGGLE_CHECKBOX`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()}))}getClientPositionKey(e){return`${e.id}-${e.position?.sheetId}-${e.position?.col}-${e.position?.row}`}isCellHovered(e,t){return this.hoveredCell.col===e&&this.hoveredCell.row===t}get focusedClients(){return this.clientFocusStore.focusedClients}getGridRect(){let e=this.env.model.getters.getViewportZoomLevel(),{width:t,height:n}=this.env.model.getters.getSheetViewDimensionWithHeaders();return{...hm(this.gridRef),width:t*e,height:n*e}}onCellClicked(e,t,n,r){if(r.ev.preventDefault(),this.composerFocusStore.activeComposer.editionMode===`editing`&&this.composerFocusStore.activeComposer.stopEdition(),n.expandZone?this.env.model.selection.setAnchorCorner(e,t):n.addZone?this.env.model.selection.addCellToSelection(e,t):this.env.model.selection.selectCell(e,t),this.env.isMobile())return;let i=e,a=t;this.dragNDropGrid.start(r,(e,t,n)=>{n.preventDefault(),(e!==i&&e!==-1||t!==a&&t!==-1)&&(i=e===-1?i:e,a=t===-1?a:t,this.env.model.selection.setAnchorCorner(i,a))},()=>{this.env.model.selection.commitSelection(),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())})}onCellDoubleClicked(e,t){let n=this.env.model.getters.getActiveSheetId();({col:e,row:t}=this.env.model.getters.getMainCellPosition({sheetId:n,col:e,row:t})),this.env.model.getters.getEvaluatedCell({sheetId:n,col:e,row:t}).type===`empty`?this.onComposerCellFocused():this.onComposerContentFocused()}processArrows(e){e.preventDefault(),e.stopPropagation(),this.cellPopovers.isOpen&&this.cellPopovers.close(),Pw(e,this.env.model.selection),this.paintFormatStore.isActive&&this.paintFormatStore.pasteFormat(this.env.model.getters.getSelectedZones())}onKeydown(e){let t=Cm(e),n=this.keyDownMapping[t];if(n){e.preventDefault(),e.stopPropagation(),n();return}if(t===` `){this.processSpaceKey(e);return}if(e.key.startsWith(`Arrow`)){this.processArrows(e);return}}onInputContextMenu(e){e.preventDefault();let t=this.env.model.getters.getSelectedZone(),{left:n,top:r}=t,i=`CELL`;this.composerFocusStore.activeComposer.stopEdition(),this.env.model.getters.getActiveCols().has(n)?i=`COL`:this.env.model.getters.getActiveRows().has(r)&&(i=`ROW`);let{x:a,y:o,width:s}=this.env.model.getters.getVisibleRectWithZoom(t),c=this.getGridRect();this.toggleContextMenu(i,c.x+a+s,c.y+o)}onCellRightClicked(e,t,{x:n,y:r}){let i=this.env.model.getters.getSelectedZones(),a=i[i.length-1],o=`CELL`;Fn(e,t,a)?this.env.model.getters.getActiveCols().has(e)?o=`COL`:this.env.model.getters.getActiveRows().has(t)&&(o=`ROW`):(this.env.model.selection.getBackToDefault(),this.env.model.selection.selectCell(e,t)),this.toggleContextMenu(o,n,r)}toggleContextMenu(e,t,n){this.cellPopovers.isOpen&&this.cellPopovers.close(),this.menuState.isOpen=!0,this.menuState.anchorRect={x:t,y:n,width:0,height:0},this.menuState.menuItems=hI[e].getMenuItems()}async copy(e,t){if(!this.gridEl.contains(document.activeElement)||this.composerFocusStore.activeComposer.editionMode!==`inactive`)return;e?NN(this.env):this.env.model.dispatch(`COPY`);let n=await this.env.model.getters.getClipboardTextAndImageContent();await this.env.clipboard.write(n),t.preventDefault()}async paste(e){if(!this.gridEl.contains(document.activeElement))return;e.preventDefault();let t=e.clipboardData;if(!t)return;let n=[...t.files].find(e=>WT.includes(e.type)),r={content:{"text/plain":t?.getData(`text/plain`),"text/html":t?.getData(`text/html`)}};n&&(r.content[n.type]=n);let i=this.env.model.getters.getSelectedZones(),a=this.env.model.getters.isCutOperation();if(this.env.model.getters.getClipboardId()===YT(r.content[`text/html`]))hw(this.env,i);else{let e=JT(r.content);await gw(this.env,i,e)}a&&await this.env.clipboard.write({"text/plain":``})}clearFormatting(){this.env.model.dispatch(`CLEAR_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones()})}setHorizontalAlign(e){this.env.model.dispatch(`SET_FORMATTING`,{sheetId:this.env.model.getters.getActiveSheetId(),target:this.env.model.getters.getSelectedZones(),style:{align:e}})}closeMenu(){this.menuState.isOpen=!1,this.focusDefaultElement()}processHeaderGroupingKey(e){if(this.env.model.getters.getSelectedZones().length!==1)return;let t=this.env.model.getters.getActiveRows().size>0,n=this.env.model.getters.getActiveCols().size>0;n&&t?this.processHeaderGroupingEventOnWholeSheet(e):n?this.processHeaderGroupingEventOnHeaders(e,`COL`):t?this.processHeaderGroupingEventOnHeaders(e,`ROW`):this.processHeaderGroupingEventOnGrid(e)}processHeaderGroupingEventOnHeaders(e,t){let n=this.env.model.getters.getActiveSheetId(),r=this.env.model.getters.getSelectedZone(),i=t===`COL`?r.left:r.top,a=t===`COL`?r.right:r.bottom;switch(e){case`right`:this.env.model.dispatch(`GROUP_HEADERS`,{sheetId:n,dimension:t,start:i,end:a});break;case`left`:this.env.model.dispatch(`UNGROUP_HEADERS`,{sheetId:n,dimension:t,start:i,end:a});break;case`down`:this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:n,dimension:t,zone:r});break;case`up`:this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:n,dimension:t,zone:r});break}}processHeaderGroupingEventOnWholeSheet(e){let t=this.env.model.getters.getActiveSheetId();e===`up`?(this.env.model.dispatch(`FOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`ROW`}),this.env.model.dispatch(`FOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`COL`})):e===`down`&&(this.env.model.dispatch(`UNFOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`ROW`}),this.env.model.dispatch(`UNFOLD_ALL_HEADER_GROUPS`,{sheetId:t,dimension:`COL`}))}processHeaderGroupingEventOnGrid(e){let t=this.env.model.getters.getActiveSheetId(),n=this.env.model.getters.getSelectedZone();switch(e){case`down`:this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`ROW`,zone:n}),this.env.model.dispatch(`UNFOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`COL`,zone:n});break;case`up`:this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`ROW`,zone:n}),this.env.model.dispatch(`FOLD_HEADER_GROUPS_IN_ZONE`,{sheetId:t,dimension:`COL`,zone:n});break;case`right`:{let{x:e,y:t,width:r}=this.env.model.getters.getVisibleRectWithZoom(n),i=this.getGridRect();this.toggleContextMenu(`GROUP_HEADERS`,e+r+i.x,t+i.y);break}case`left`:{if(!jN(this.env,`COL`)&&!jN(this.env,`ROW`))return;let{x:e,y:t,width:r}=this.env.model.getters.getVisibleRectWithZoom(n),i=this.getGridRect();this.toggleContextMenu(`UNGROUP_HEADERS`,e+r+i.x,t+i.y);break}}}onComposerCellFocused(e,t){this.composerFocusStore.focusActiveComposer({content:e,selection:t,focusMode:`cellFocus`})}onComposerContentFocused(){this.composerFocusStore.focusActiveComposer({focusMode:`contentFocus`})}get staticTables(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getCoreTables(e).filter(EM)}get displaySelectionHandler(){return this.env.isMobile()&&this.composerFocusStore.activeComposer.editionMode===`inactive`}get clientsToDisplay(){let e=this.env.model.getters.getActiveSheetId();return this.env.model.getters.getClientsToDisplay(e)}};let _I=new A;_I.add(`SPREADSHEET`,!1);var vI=class extends t.Component{static template=`o-spreadsheet-ClickableCellSortIcon`;static props={position:Object,sortDirection:String};hoveredTableStore;setup(){this.hoveredTableStore=O(HF)}get style(){let e=this.env.model.getters.getCellComputedStyle(this.props.position),t=Dd(e);return W({height:`${t}px`,width:`${t}px`,color:e.textColor||`#374151C2`,"background-color":this.getBackgroundColor(e)})}get verticalJustifyClass(){switch(this.env.model.getters.getCellComputedStyle(this.props.position).verticalAlign){case`top`:return`justify-content-start`;case`middle`:return`justify-content-center`;default:return`justify-content-end`}}getBackgroundColor(e){let t=this.hoveredTableStore.overlayColors.get(this.props.position);return t?Kr(e.fillColor||`#FFFFFF`,t):e.fillColor||`#FFFFFF`}},yI=class extends t.Component{static template=`o-spreadsheet-FullScreenFigure`;static props={};static components={ChartFigure:Oy};fullScreenFigureStore;ref=(0,t.useRef)(`fullScreenFigure`);spreadsheetRect=vy();figureRegistry=Ay;setup(){this.fullScreenFigureStore=O(cy);let e=O(Ud),n;(0,t.onWillUpdateProps)(()=>{n!==this.figureUI?.id&&e.enableAnimationForChart(this.chartId+`-fullscreen`),n=this.figureUI?.id}),(0,t.useEffect)(e=>e?.focus(),()=>[this.ref.el])}get figureUI(){return this.fullScreenFigureStore.fullScreenFigure}get chartId(){if(this.figureUI)return this.env.model.getters.getChartIdFromFigureId(this.figureUI?.id)}exitFullScreen(){this.figureUI&&this.fullScreenFigureStore.toggleFullScreenFigure(this.figureUI.id)}onKeyDown(e){e.key===`Escape`&&this.exitFullScreen()}get figureComponent(){if(this.figureUI)return Ay.get(this.figureUI.tag).Component}},bI=class extends t.Component{static template=`o_spreadsheet.PivotHTMLRenderer`;static components={Checkbox:IT};static props={pivotId:String,onCellClicked:Function};pivot=this.env.model.getters.getPivot(this.props.pivotId);data={columns:[],rows:[],values:[]};state=(0,t.useState)({showMissingValuesOnly:!1});setup(){let e=this.pivot.getExpandedTableStructure(),t=this.env.model.getters.getPivotFormulaId(this.props.pivotId);this.data={columns:this._buildColHeaders(t,e),rows:this._buildRowHeaders(t,e),values:this._buildValues(t,e)}}get tracker(){return this.env.model.getters.getPivotPresenceTracker(this.props.pivotId)}getTableData(){if(!this.state.showMissingValuesOnly)return this.data;let e=this.getColumnsIndexes(),t=this.getRowsIndexes();return{columns:this.buildColumnsMissing(e),rows:this.buildRowsMissing(t),values:this.buildValuesMissing(e,t)}}addRecursiveRow(e){let t=this.pivot.getExpandedTableStructure().rows,n=[...t[e].values];if(n.length<=1)return[e];n.pop();let r=t.findIndex(e=>JSON.stringify(e.values)===JSON.stringify(n));return[e].concat(this.addRecursiveRow(r))}buildColumnsMissing(e){let t=[];for(let e of this.data.columns){let n=[];for(let t in e)for(let r=0;r<e[t].span;r++)n.push(parseInt(t,10));t.push(n)}for(let n=t[t.length-1].length;n>=0;n--)if(!e.includes(n))for(let e of t)e.splice(n,1);let n=[];for(let e in t){let r=[],i,a=1;for(let n=0;n<t[e].length;n++)i===t[e][n]?a++:(i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),i=t[e][n],a=1);i!==void 0&&r.push(Object.assign({},this.data.columns[e][i],{span:a})),n.push(r)}return n}buildRowsMissing(e){return e.map(e=>this.data.rows[e])}buildValuesMissing(e,t){let n=e.map(()=>[]);for(let r of t)for(let t in e)n[t].push(this.data.values[e[t]][r]);return n}getColumnsIndexes(){let e=new Set;for(let t=0;t<this.data.columns.length;t++){let n=[];for(let e=0;e<this.data.columns[t].length;e++)for(let r=0;r<this.data.columns[t][e].span;r++)n.push(this.data.columns[t][e]);for(let t=0;t<n.length;t++)n[t].isMissing&&e.add(t)}for(let t=0;t<this.data.columns[this.data.columns.length-1].length;t++)this.data.values[t].find(e=>e.isMissing)&&e.add(t);return Array.from(e).sort((e,t)=>e-t)}getRowsIndexes(){let e=new Set;for(let t=0;t<this.data.rows.length;t++){this.data.rows[t].isMissing&&e.add(t);for(let n of this.data.values)n[t].isMissing&&this.addRecursiveRow(t).forEach(t=>e.add(t))}return Array.from(e).sort((e,t)=>e-t)}_buildColHeaders(e,t){let n=[];for(let r of t.columns){let t=[];for(let n of r){let r=[];for(let e=0;e<n.fields.length;e++)r.push({value:n.fields[e]},{value:n.values[e]});let i=this.pivot.parseArgsToPivotDomain(r),a=this.env.model.getters.getLocale();if(i.at(-1)?.field===`measure`){let{value:r,format:o}=this.pivot.getPivotMeasureValue(L(i.at(-1).value),i);t.push({formula:`=PIVOT.HEADER(${wg(e,i).join(`,`)})`,value:H(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}else{let{value:r,format:o}=this.pivot.getPivotHeaderValueAndFormat(i);t.push({formula:`=PIVOT.HEADER(${wg(e,i).join(`,`)})`,value:H(r,{format:o,locale:a}),span:n.width,isMissing:!this.tracker?.isHeaderPresent(i)})}}n.push(t)}let r=n[n.length-1];return n[n.length-1]=r.map(e=>(e.isMissing||(e.style=`color: #756f6f;`),e)),n}_buildRowHeaders(e,t){let n=[];for(let r of t.rows){let t=[];for(let e=0;e<r.fields.length;e++)t.push({value:r.fields[e]},{value:r.values[e]});let i=this.pivot.parseArgsToPivotDomain(t),{value:a,format:o}=this.pivot.getPivotHeaderValueAndFormat(i),s=this.env.model.getters.getLocale(),c={formula:`=PIVOT.HEADER(${wg(e,i).join(`,`)})`,value:H(a,{format:o,locale:s}),isMissing:!this.tracker?.isHeaderPresent(i)};r.indent>1&&(c.style=`padding-left: ${r.indent-10}px`),n.push(c)}return n}_buildValues(e,t){let n=[];for(let r of t.columns.at(-1)||[]){let i=[],a=L(r.values[r.values.length-1]);for(let n of t.rows){let t=[];for(let e=0;e<n.fields.length;e++)t.push({value:n.fields[e]},{value:n.values[e]});for(let e=0;e<r.fields.length-1;e++)t.push({value:r.fields[e]},{value:r.values[e]});let o=this.pivot.parseArgsToPivotDomain(t),{value:s,format:c}=this.pivot.getPivotCellValueAndFormat(a,o),l=this.env.model.getters.getLocale();i.push({formula:`=PIVOT.VALUE(${wg(e,o,a).join(`,`)})`,value:H(s,{format:c,locale:l}),isMissing:!this.tracker?.isValuePresent(a,o)})}n.push(i)}return n}},xI=class{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(let n of e){let e=n.call(this,t);Array.isArray(e)||(e=[e]);let r=e.filter(e=>e!==`Success`);if(r.length)return r}return`Success`}}checkValidations(e,...t){return this.batchValidations(...t)(e)}},SI=class extends xI{getters;dispatch;canDispatch;constructor({getters:e,stateObserver:t,range:n,dispatch:r,canDispatch:i}){super(t),n.addRangeProvider(this.adaptRanges.bind(this)),this.getters=e,this.dispatch=r,this.canDispatch=i}import(e){}export(e,t){}adaptRanges(e){}},CI=class extends SI{static getters=[`getCellBorder`,`getBordersColors`];borders={};allowDispatch(e){switch(e.type){case`SET_BORDER`:return this.checkBordersUnchanged(e);default:return`Success`}}handle(e){switch(e.type){case`ADD_MERGE`:for(let t of e.target)this.addBordersToMerge(e.sheetId,t);break;case`DUPLICATE_SHEET`:let t=this.borders[e.sheetId];if(t){let n=t.slice().map(e=>e?.slice().map(e=>x(e)));this.history.update(`borders`,e.sheetIdTo,n)}break;case`DELETE_SHEET`:let n={...this.borders};delete n[e.sheetId],this.history.update(`borders`,n);break;case`SET_BORDER`:this.setBorder(e.sheetId,e.col,e.row,e.border);break;case`SET_BORDERS_ON_TARGET`:for(let t of e.target)for(let n=t.top;n<=t.bottom;n++)for(let r=t.left;r<=t.right;r++)this.setBorder(e.sheetId,r,n,e.border);break;case`SET_ZONE_BORDERS`:if(e.border){let t=e.target.map(t=>this.getters.expandZone(e.sheetId,t));this.setBorders(e.sheetId,t,e.border.position,e.border.color===``?void 0:{style:e.border.style||Oe.style,color:e.border.color||Oe.color})}break;case`CLEAR_FORMATTING`:this.clearBorders(e.sheetId,e.target);break;case`REMOVE_COLUMNS_ROWS`:let r=[...e.elements].sort((e,t)=>t-e);for(let t of rt(r))if(e.dimension===`COL`){let n=this.getters.getColsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersHorizontally(e.sheetId,t[0]+1,-t.length)}else{let n=this.getters.getRowsZone(e.sheetId,t[t.length-1],t[0]);this.clearInsideBorders(e.sheetId,[n]),this.shiftBordersVertically(e.sheetId,t[0]+1,-t.length)}break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumns(e):this.handleAddRows(e);break}}handleAddColumns(e){let t,n;e.position===`before`?(this.shiftBordersHorizontally(e.sheetId,e.base,e.quantity),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersHorizontally(e.sheetId,e.base+1,e.quantity),t=e.base,n=e.base+e.quantity+1),this.ensureColumnBorderContinuity(e.sheetId,t,n)}handleAddRows(e){let t,n;e.position===`before`?(this.shiftBordersVertically(e.sheetId,e.base,e.quantity),t=e.base-1,n=e.base+e.quantity):(this.shiftBordersVertically(e.sheetId,e.base+1,e.quantity),t=e.base,n=e.base+e.quantity+1),this.ensureRowBorderContinuity(e.sheetId,t,n)}getCellBorder({sheetId:e,col:t,row:n}){let r=this.borders[e]?.[t]?.[n];return r?.top||r?.bottom||r?.left||r?.right?x(r):null}getBordersColors(e){let t=[],n=this.borders[e];if(n){for(let e of n.filter(w))for(let n of e)if(n)for(let e of[`top`,`bottom`,`left`,`right`]){let r=n[e]?.color;r&&t.push(r)}}return t}ensureColumnBorderContinuity(e,t,n){let r=C(t+1,n);for(let i=0;i<this.getters.getNumberRows(e);i++){let a=this.getCellBorder({sheetId:e,col:t,row:i}),o=this.getCellBorder({sheetId:e,col:n,row:i});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,n,i,t)}}}ensureRowBorderContinuity(e,t,n){let r=C(t+1,n);for(let i=0;i<this.getters.getNumberCols(e);i++){let a=this.getCellBorder({sheetId:e,col:i,row:t}),o=this.getCellBorder({sheetId:e,col:i,row:n});if(a&&o){let t=this.getCommonSides(a,o);for(let n of r)this.addBorder(e,i,n,t)}}}getCommonSides(e,t){let n={};for(let r of[`top`,`bottom`,`left`,`right`])e[r]&&T(e[r],t[r])&&(n[r]=e[r]);return n}getColumnsWithBorders(e){let t=this.borders[e];return t?Object.keys(t).map(e=>parseInt(e,10)):[]}getRowsWithBorders(e){let t=this.borders[e]?.filter(w);if(!t)return[];let n=new Set;for(let e of t)for(let t in e)n.add(parseInt(t,10));return Array.from(n)}getRowsRange(e){return this.borders[e]?C(0,this.getters.getNumberRows(e)+1):[]}shiftBordersHorizontally(e,t,n){this.borders[e]&&this.getColumnsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(t=>{this.moveBordersOfColumn(e,t,n)})}shiftBordersVertically(e,t,n){this.borders[e]&&(n<0&&this.moveBordersOfRow(e,t,n,{destructive:!1}),this.getRowsWithBorders(e).filter(e=>e>=t).sort((e,t)=>n<0?e-t:t-e).forEach(t=>{this.moveBordersOfRow(e,t,n)}))}moveBordersOfRow(e,t,n,{destructive:r}={destructive:!0}){let i=this.borders[e];i&&this.getColumnsWithBorders(e).forEach(a=>{let o=i[a]?.[t+n],s=i[a]?.[t];this.history.update(`borders`,e,a,t+n,r?s:s||o),this.history.update(`borders`,e,a,t,void 0)})}moveBordersOfColumn(e,t,n,{destructive:r}={destructive:!0}){let i=this.borders[e];i&&this.getRowsRange(e).forEach(a=>{let o=i[t+n]?.[a],s=i[t]?.[a];this.history.update(`borders`,e,t+n,a,r?s:s||o),r&&this.history.update(`borders`,e,t,a,void 0)})}setBorder(e,t,n,r,i=!0){let a=this.getters.getNumberCols(e)-1,o=this.getters.getNumberRows(e)-1;(i||!this.borders[e]?.[t]?.[n]?.left)&&(this.history.update(`borders`,e,t,n,`left`,r?.left),r?.left&&t>0&&!T(this.borders[e]?.[t-1]?.[n]?.right,r?.left)&&this.history.update(`borders`,e,t-1,n,`right`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.top)&&(this.history.update(`borders`,e,t,n,`top`,r?.top),r?.top&&n>0&&!T(this.borders[e]?.[t]?.[n-1]?.bottom,r?.top)&&this.history.update(`borders`,e,t,n-1,`bottom`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.right)&&(this.history.update(`borders`,e,t,n,`right`,r?.right),r?.right&&t<a&&!T(this.borders[e]?.[t+1]?.[n]?.left,r?.right)&&this.history.update(`borders`,e,t+1,n,`left`,void 0)),(i||!this.borders[e]?.[t]?.[n]?.bottom)&&(this.history.update(`borders`,e,t,n,`bottom`,r?.bottom),r?.bottom&&n<o&&!T(this.borders[e]?.[t]?.[n+1]?.top,r?.bottom)&&this.history.update(`borders`,e,t,n+1,`top`,void 0))}clearBorders(e,t,n=!1){let r=this.getters.getNumberCols(e)-1,i=this.getters.getNumberRows(e)-1;for(let a of cn(t))for(let t=a.top;t<=a.bottom;t++){n&&(a.left>0&&this.history.update(`borders`,e,a.left-1,t,`right`,void 0),a.right<r&&this.history.update(`borders`,e,a.right+1,t,`left`,void 0));for(let r=a.left;r<=a.right;r++)this.history.update(`borders`,e,r,t,void 0),n&&(a.top>0&&this.history.update(`borders`,e,r,a.top-1,`bottom`,void 0),a.bottom<i&&this.history.update(`borders`,e,r,a.bottom+1,`top`,void 0))}}clearInsideBorders(e,t){for(let n of t)for(let t=n.top;t<=n.bottom;t++)for(let r=n.left;r<=n.right;r++)this.history.update(`borders`,e,r,t,void 0)}addBorder(e,t,n,r){this.setBorder(e,t,n,{...this.getCellBorder({sheetId:e,col:t,row:n}),...r})}setBorders(e,t,n,r){if(n===`clear`)return this.clearBorders(e,t,!0);for(let i of cn(t)){if(n===`all`)for(let t=i.top;t<=i.bottom;t++)for(let n=i.left;n<=i.right;n++)this.addBorder(e,n,t,{top:r,right:r,bottom:r,left:r});if(n===`h`||n===`hv`){if(i.top===i.bottom)continue;for(let t=i.left;t<=i.right;t++){this.addBorder(e,t,i.top,{bottom:r});for(let n=i.top+1;n<i.bottom;n++)this.addBorder(e,t,n,{top:r,bottom:r});this.addBorder(e,t,i.bottom,{top:r})}}if(n===`v`||n===`hv`){if(i.left===i.right)continue;for(let t=i.top;t<=i.bottom;t++){this.addBorder(e,i.left,t,{right:r});for(let n=i.left+1;n<i.right;n++)this.addBorder(e,n,t,{left:r,right:r});this.addBorder(e,i.right,t,{left:r})}}if(n===`left`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.left,t,{left:r});if(n===`right`||n===`external`)for(let t=i.top;t<=i.bottom;t++)this.addBorder(e,i.right,t,{right:r});if(n===`top`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.top,{top:r});if(n===`bottom`||n===`external`)for(let t=i.left;t<=i.right;t++)this.addBorder(e,t,i.bottom,{bottom:r})}}addBordersToMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t,o=this.getCellBorder({sheetId:e,col:n,row:i}),s=this.getCellBorder({sheetId:e,col:r,row:a});this.clearBorders(e,[t]),o?.top&&this.setBorders(e,[{...t,bottom:i}],`top`,o.top),o?.left&&this.setBorders(e,[{...t,right:n}],`left`,o.left),s?.bottom?this.setBorders(e,[{...t,top:a}],`bottom`,s.bottom):o?.bottom&&this.setBorders(e,[{...t,top:a}],`bottom`,o.bottom),s?.right?this.setBorders(e,[{...t,left:r}],`right`,s.right):o?.right&&this.setBorders(e,[{...t,left:r}],`right`,o.right)}checkBordersUnchanged(e){let t=this.getCellBorder(e),n=!e.border?.bottom&&!e.border?.left&&!e.border?.right&&!e.border?.top;return!t&&n||T(t,e.border)?`NoChanges`:`Success`}import(e){if(Object.keys(e.borders||{}).length)for(let t of e.sheets)for(let[n,r]of cd(t.id,t.borders)){let{sheetId:t,col:i,row:a}=n,o=e.borders[r];this.setBorder(t,i,a,o,!1)}for(let t of e.sheets)if(t.merges)for(let e of t.merges)this.addBordersToMerge(t.id,yn(e))}export(e){let t={};for(let n of e.sheets){let e={};for(let r=0;r<n.colNumber;r++)for(let i=0;i<n.rowNumber;i++){let a=this.getCellBorder({sheetId:n.id,col:r,row:i});if(a){let o=od(a,t),s={sheetId:n.id,col:r,row:i};e[o]??=[],e[o].push(s)}}n.borders=sd(e)}e.borders=t}exportForExcel(e){this.export(e)}},wI=class extends SI{static getters=[`getCarousel`,`doesCarouselExist`];carousels={};allowDispatch(e){switch(e.type){case`CREATE_CAROUSEL`:return this.getters.getFigure(e.sheetId,e.figureId)?`DuplicatedFigureId`:`Success`;case`UPDATE_CAROUSEL`:return this.carousels[e.sheetId]?.[e.figureId]?`Success`:`InvalidFigureId`}return`Success`}handle(e){switch(e.type){case`CREATE_CAROUSEL`:this.getters.getFigure(e.sheetId,e.figureId)||this.dispatch(`CREATE_FIGURE`,{...e,tag:`carousel`}),this.history.update(`carousels`,e.sheetId,e.figureId,e.definition);break;case`UPDATE_CAROUSEL`:this.removeDeletedCharts(e,this.getters.getCarousel(e.figureId).items),this.history.update(`carousels`,e.sheetId,e.figureId,e.definition);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`carousel`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.getCarousel(n.id);if(i){let t={width:n.width,height:n.height};this.dispatch(`CREATE_CAROUSEL`,{sheetId:e.sheetIdTo,figureId:r,offset:n.offset,col:n.col,row:n.row,size:t,definition:{items:i.items.map(t=>{if(t.type===`carouselDataView`)return{...t};let n=t.chartId.split(`??`).pop(),r=`${e.sheetIdTo}??${n}`;return{...t,chartId:r}})}})}}break}case`DELETE_FIGURE`:this.history.update(`carousels`,e.sheetId,e.figureId,void 0);break;case`DELETE_SHEET`:this.history.update(`carousels`,e.sheetId,void 0);break}}doesCarouselExist(e){for(let t in this.carousels)if(this.carousels[t]?.[e])return!0;return!1}getCarousel(e){for(let t in this.carousels)if(this.carousels[t]?.[e])return this.carousels[t][e];throw Error(`There is no carousel with the given figureId: ${e}`)}removeDeletedCharts(e,t){let n=new Set(e.definition.items.filter(e=>e.type===`chart`).map(e=>e.chartId));for(let r of t)r.type===`chart`&&!n.has(r.chartId)&&this.dispatch(`DELETE_CHART`,{chartId:r.chartId,sheetId:e.sheetId})}import(e){for(let t of e.sheets){let e=(t.figures||[]).filter(e=>e.tag===`carousel`);for(let n of e)this.history.update(`carousels`,t.id,n.id,{items:n.data.items,title:n.data.title})}}export(e){for(let t of e.sheets){let e=t.figures.filter(e=>e.tag===`carousel`);for(let n of e)this.carousels[t.id]?.[n.id]&&(n.data={...n.data,...this.carousels[t.id]?.[n.id]})}}},TI=class{getters;baseFormula;alreadyAppliedNumberOffsets=[];previousStrings=[];baseFormulaWasTransformed=!1;rangeToStringOptions={doNotSimplifyRange:!0};baseNumber=void 0;constructor(e){this.getters=e}buildResult(e,t,n){let r={};if(e.length&&(r.N=e.join(`|`)),t.length&&(r.S=t),n.length){let e;e=n.some(e=>e.includes(`|`))?n:n.join(`|`),r.R=e}return r}resetBaseTo(e){this.baseFormula=Rc.CopyWithDependenciesAndLiteral(e,e.sheetId,x(e.rangeDependencies),e.literalValues.numbers,e.literalValues.strings),this.alreadyAppliedNumberOffsets=e.literalValues.numbers.map(e=>0),this.previousStrings=e.literalValues.strings.map(e=>e.value),this.baseFormulaWasTransformed=!1,this.baseNumber=void 0}resetBaseFormula(){this.baseFormula&&(this.baseFormula=void 0,this.alreadyAppliedNumberOffsets=[],this.previousStrings=[],this.baseFormulaWasTransformed=!1)}squish(e,t){if(e.isFormula){let n=[],r=[],i=[];return!this.baseFormula||this.baseFormula.normalizedFormula!==e.compiledFormula.normalizedFormula?(this.resetBaseTo(e.compiledFormula),e.compiledFormula.toFormulaString(this.getters,this.rangeToStringOptions)):!this.baseFormulaWasTransformed&&T(e.compiledFormula.literalValues,this.baseFormula.literalValues)&&T(e.compiledFormula.rangeDependencies,this.baseFormula.rangeDependencies)?e.compiledFormula.toFormulaString(this.getters,this.rangeToStringOptions):(n=this.squishNumbers(e.compiledFormula.literalValues.numbers),r=this.squishStrings(e.compiledFormula.literalValues.strings),i=this.squishReferences(e.compiledFormula.rangeDependencies,t),this.baseFormulaWasTransformed=!0,this.buildResult(n,r,i))}if(typeof e.parsedValue==`number`&&e.parsedValue%1==0){this.resetBaseFormula();let t=e.parsedValue;if(this.baseNumber===void 0)return this.baseNumber=t,e.content;let n=t-this.baseNumber;return n===0?e.content:(this.baseNumber=t,{N:(n>0?`+`:``)+n.toString()})}return this.resetBaseFormula(),this.baseNumber=void 0,e.content}squishCommand(e){if(e.content){let t=Ru(this.getters,-1,e.content,e.format,e.style??void 0,e.sheetId),n=this.squish(t,e.sheetId);return typeof n==`string`?e.content:n}return e.content}squishSheet(e,t){let n=Object.keys(e),r={};for(let i=0;i<n.length;i++){let a=sn(n[i]),o=0;for(o=0;o+i+1<n.length;o++){let t=sn(n[o+i+1]);if(t.col!==a.col||t.row!==a.row+o+1||!T(e[n[o+i+1]],e[n[i]]))break}if(o>0){let t=`${n[i]}:${E(a.col,a.row+o)}`;r[t]=e[n[i]],i+=o}else{let o=this.getters.getCell({sheetId:t,col:a.col,row:a.row});!o?.isFormula&&typeof o?.parsedValue==`number`?r[n[i]]=o.content:r[n[i]]=e[n[i]]}}return r}squishReferences(e,t){if(!this.baseFormula)throw Error(`No previous cell to squish against`);return e.map((e,n)=>this.squishOneReference(e,this.baseFormula.rangeDependencies,n,t))}squishOneReference(e,t,n,r){let i=t[n];if(T(i,e))return`=`;if(i.sheetId!==e.sheetId||i.prefixSheet!==e.prefixSheet||i.invalidSheetName!==e.invalidSheetName||i.invalidXc!==e.invalidXc||i.parts.length!==e.parts.length||i.unboundedZone.bottom===void 0||i.unboundedZone.right===void 0||e.unboundedZone.bottom===void 0||e.unboundedZone.right===void 0)return t[n]=x(e),ec(e,r,this.getters.getSheetName,this.rangeToStringOptions);for(let a=0;a<e.parts.length;a++)if(i.parts[a].colFixed!==e.parts[a].colFixed||i.parts[a].rowFixed!==e.parts[a].rowFixed)return t[n]=x(e),ec(e,r,this.getters.getSheetName,this.rangeToStringOptions);let a=e.zone,o=i.zone;if(a.top!==a.bottom||a.left!==a.right||o.top!==o.bottom||o.left!==o.right)return t[n]=x(e),ec(e,r,this.getters.getSheetName,this.rangeToStringOptions);let s=e.zone.left-i.zone.left,c=e.zone.top-i.zone.top;return i.zone=x(e.zone),i.unboundedZone=x(e.unboundedZone),s!==0&&c===0?`${s>0?`+`:`-`}C${Math.abs(s)}`:c!==0&&s===0?`${c>0?`+`:`-`}R${Math.abs(c)}`:ec(e,r,this.getters.getSheetName,this.rangeToStringOptions)}squishNumbers(e){let t=e.map(e=>`=`);for(let n=0;n<e.length;n++){let r=this.baseFormula.literalValues.numbers[n].value,i=e[n].value,a=this.alreadyAppliedNumberOffsets[n]||0,o=i-(r+a);o!==0&&(t[n]=`+`+o.toString(),this.alreadyAppliedNumberOffsets[n]=a+o)}return t}squishStrings(e){let t=e.map(e=>`=`);for(let n=0;n<e.length;n++){let r=e[n].value;r!==this.previousStrings[n]&&(t[n]=r,this.previousStrings[n]=r)}return t}};function EI(e){return[sn(e)]}function*DI(e,t){let n=sn(e),r=sn(t);for(let e=Math.min(n.col,r.col);e<=Math.max(n.col,r.col);e++)for(let t=Math.min(n.row,r.row);t<=Math.max(n.row,r.row);t++)yield{col:e,row:t}}var OI=class{previousFormula;alreadyAppliedNumberOffset=[];previousString=[];alreadyAppliedReferenceOffset=[];previousOffset=void 0;previousNumber=void 0;previousNumberFormat;rebase(){this.previousFormula=void 0,this.alreadyAppliedNumberOffset=[],this.previousString=[],this.alreadyAppliedReferenceOffset=[],this.previousOffset=void 0,this.previousNumber=void 0,this.previousNumberFormat=void 0}*unsquishCommands(e,t){let n;for(let r of e){if(r.type!==`UPDATE_CELL`&&r.type!==`SQUISHED_UPDATE_CELL`){yield r;continue}let e=r.content;n=e==null||e===``?`NOT_A_FORMULA`:this.chooseStrategy(e,n,r.sheetId,t);let i;if(r.type===`SQUISHED_UPDATE_CELL`&&`targetRange`in r){let[e,t]=r.targetRange.split(`:`);i=DI(e,t)}else i=[{row:r.row,col:r.col}];for(let{position:a,compiled:o,content:s}of this.applyStrategy(n,i,e,r.sheetId,t)){let e=o?o.toFormulaString(t):s,n={type:`UPDATE_CELL`,sheetId:r.sheetId,row:a.row,col:a.col};(`content`in r||o)&&(n.content=e),`style`in r&&(n.style=r.style),`format`in r&&(n.format=r.format),yield n}}}*unsquishSheet(e,t,n){let r=Object.keys(e).map(e=>({cartesian:sn(e.split(`:`)[0]),key:e})).sort((e,t)=>e.cartesian.col===t.cartesian.col?e.cartesian.row-t.cartesian.row:e.cartesian.col-t.cartesian.col),i;for(let{key:a}of r){let r=e[a];if(r==null||r===``)continue;i=this.chooseStrategy(r,i,t,n);let o=a.split(`:`),s=o.length===1?EI(a):DI(o[0],o[1]);yield*this.applyStrategy(i,s,r,t,n)}}chooseStrategy(e,t,n,r){let i=t;if(typeof e==`string`)if(e.startsWith(`=`)){i=`NEW_FORMULA`;let t=Rc.Compile(e,n,r);this.previousFormula=t,this.alreadyAppliedNumberOffset=t.literalValues.numbers.map(e=>e.value),this.previousString=t.literalValues.strings.map(e=>e.value),this.alreadyAppliedReferenceOffset=[...t.rangeDependencies],this.previousOffset=void 0,this.previousNumber=void 0,this.previousNumberFormat=void 0}else{let t=this.parseSquishableLiteral(e,r);t?(i=`NEW_NUMBER`,this.rebase(),this.previousNumber=t.value,this.previousNumberFormat=t.format):(this.rebase(),i=`NOT_A_FORMULA`)}else if(e.N||e.S||e.R){if(!i)throw Error(`Incorrect order of commands, cannot unsquish`);switch(i){case`NEW_FORMULA`:i=`FIRST_OFFSET`;break;case`NEW_NUMBER`:if(e.R||e.S)throw Error(`Invalid squished format: cannot have string or reference offsets for a number`);i=`OFFSET_NUMBER`;break;case`FIRST_OFFSET`:i=`COMBINE_OFFSET`;break}}return i}*applyStrategy(e,t,n,r,i){let a=n;switch(e){case`NEW_FORMULA`:for(let e of t)yield{position:e,compiled:this.previousFormula};break;case`NOT_A_FORMULA`:for(let e of t)yield{position:e,content:a};break;case`FIRST_OFFSET`:{let e=a;this.previousOffset=e;for(let n of t){let t=this.unsquishFormula(e,r,i);if(t.areRangeShapesInLineWithNormalizedFormula())yield{position:n,compiled:t};else{let e=t.toFormulaString(i);yield{position:n,compiled:Rc.Compile(e,r,i)}}}break}case`COMBINE_OFFSET`:{if(!this.previousOffset)throw Error(`No previous offset to combine with`);let e=a;this.previousOffset.N=e.N??this.previousOffset.N,this.previousOffset.S=e.S??this.previousOffset.S,this.previousOffset.R=e.R??this.previousOffset.R;for(let e of t){let t=this.unsquishFormula(this.previousOffset,r,i);if(t.areRangeShapesInLineWithNormalizedFormula())yield{position:e,compiled:t};else{let n=t.toFormulaString(i);yield{position:e,compiled:Rc.Compile(n,r,i)}}}break}case`NEW_NUMBER`:for(let e of t)yield{position:e,content:a};break;case`OFFSET_NUMBER`:{let e=a.N;if(e===void 0||this.previousNumber===void 0)throw Error(`No ${e} provided for OFFSET_NUMBER strategy, previous ${this.previousNumber} for ${r}!${JSON.stringify(a)} `);let n=parseFloat(e),o={format:this.previousNumberFormat,locale:i.getLocale()};for(let e of t)this.previousNumber+=n,yield{position:e,content:H(this.previousNumber,o)};break}}}parseSquishableLiteral(e,t){let n=zu(t,-1,e,void 0,void 0);if(!(typeof n.parsedValue!=`number`||n.parsedValue%1!=0))return{value:n.parsedValue,format:n.format}}unsquishFormula(e,t,n){if(typeof e==`object`&&this.previousFormula){let r={numbers:[],strings:[],dependencies:[]};if(e.N!==void 0&&e.N.length>0?r.numbers=e.N.split(`|`).map(this.adjustNumbers):r.numbers=this.previousFormula.literalValues.numbers,e.S!==void 0&&e.S.length>0?r.strings=e.S.map(this.adjustStrings):r.strings=this.previousFormula.literalValues.strings,e.R!==void 0&&this.previousFormula){let i;i=typeof e.R==`string`?e.R.split(`|`):e.R,r.dependencies=i.map((e,r)=>{if(e===`=`)return{...this.alreadyAppliedReferenceOffset[r]};if(e.startsWith(`+`)||e.startsWith(`-`)){let t=parseInt(e.slice(2),10),n=e[0]===`+`?1:-1;if(e[1]===`R`){let e=this.alreadyAppliedReferenceOffset[r].zone.top+t*n,i={...this.alreadyAppliedReferenceOffset[r]};return i.zone=i.unboundedZone={...i.zone,top:e,bottom:e},this.alreadyAppliedReferenceOffset[r]=i,i}else if(e[1]===`C`){let e=this.alreadyAppliedReferenceOffset[r].zone.left+t*n,i=Object.assign({},this.alreadyAppliedReferenceOffset[r]);return i.zone=i.unboundedZone=Object.assign({},i.zone,{left:e,right:e}),this.alreadyAppliedReferenceOffset[r]=i,i}else throw Error(`Invalid reference offset format: ${e}`)}else{let i=n.getRangeFromSheetXC(t,e);return this.alreadyAppliedReferenceOffset[r]=i,i}})}else r.dependencies=this.previousFormula.rangeDependencies;return Rc.CopyWithDependenciesAndLiteral(this.previousFormula,t,r.dependencies,r.numbers,r.strings)}throw Error(`Invalid squished element or no previous cell to unsquish against`)}adjustStrings=(e,t)=>e===`=`?{value:this.previousString[t]}:(this.previousString[t]=e,{value:e});adjustNumbers=(e,t)=>{if(e===`=`)return{value:this.alreadyAppliedNumberOffset[t]};{let n=parseFloat(e.slice(1)),r=(this.alreadyAppliedNumberOffset[t]||0)+n;return this.alreadyAppliedNumberOffset[t]=r,{value:r}}}},kI=class extends SI{static getters=[`zoneToXC`,`getCells`,`getTranslatedCellFormula`,`getCellStyle`,`getCellById`,`getFormulaString`,`getFormulaMovedInSheet`];nextId=1;cells={};adaptRanges(e){for(let t of Object.keys(this.cells))for(let n of Object.values(this.cells[t]||{}))if(n.isFormula){let r=e.adaptCompiledFormula(n.compiledFormula);r!==n.compiledFormula&&this.history.update(`cells`,t,n.id,`compiledFormula`,r)}}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`;case`SET_FORMATTING`:return this.checkUselessSetFormatting(e);default:return`Success`}}handle(e){switch(e.type){case`SET_FORMATTING`:this.setStyleFormat(e.sheetId,e.target,e.style,e.format);break;case`CLEAR_FORMATTING`:this.clearFormatting(e.sheetId,e.target);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.handleAddColumnsRows(e,this.copyColumnStyle.bind(this)):this.handleAddColumnsRows(e,this.copyRowStyle.bind(this));break;case`UPDATE_CELL`:this.updateCell(e.sheetId,e.col,e.row,e);break;case`CLEAR_CELL`:this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col,row:e.row,content:``,style:null,format:``});break;case`CLEAR_CELLS`:this.clearCells(e.sheetId,e.target);break;case`DELETE_CONTENT`:this.clearZones(e.sheetId,e.target);break;case`DELETE_SHEET`:this.history.update(`cells`,e.sheetId,void 0)}}clearZones(e,t){for(let n of cn(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++){let n=this.getters.getCell({sheetId:e,col:t,row:r});(n?.isFormula||n?.content)&&this.dispatch(`UPDATE_CELL`,{sheetId:e,content:``,col:t,row:r})}}clearFormatting(e,t){for(let n of cn(t))for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,style:null,format:``})}clearCells(e,t){for(let n of t)for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,content:``,style:null,format:``})}handleAddColumnsRows(e,t){let n,r;e.position===`before`?(n=C(e.base,e.base+e.quantity),r=e.base+e.quantity):(n=C(e.base+1,e.base+e.quantity+1),r=e.base),t(e.sheetId,r,n)}import(e){let t=performance.now();for(let t of e.sheets){let n=t.id,r=new tN,i=new OI;for(let e of i.unsquishSheet(t.cells,t.id,this.getters))if(e.content||e.compiled){let n={sheetId:t.id,col:e.position.col,row:e.position.row};e.compiled?r.set(n,{compiledFormula:e.compiled}):r.set(n,{content:e.content})}for(let[e,n]of[[`style`,t.styles],[`format`,t.formats]])for(let[i,a]of cd(t.id,n)){let t=r.get(i);t?t[e]=a:r.set(i,{[e]:a})}for(let i of r.keysForSheet(n)){let n=r.get(i);if(n?.content||n?.format||n?.style||n?.compiledFormula){let r=this.importCell(t.id,n?.content,n?.style?e.styles[n?.style]:void 0,n?.format?e.formats[n?.format]:void 0,n?.compiledFormula);this.history.update(`cells`,t.id,r.id,r),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:r.id,...i})}}}console.debug(`cells imported in`,performance.now()-t,`ms`)}export(e,t){let n={},r={};for(let i of e.sheets){let e=new TI(this.getters),a=[],o=[],s={},c=Object.values(this.cells[i.id]||{}).map(e=>this.getters.getCellPosition(e.id)).sort((e,t)=>e.col===t.col?e.row-t.row:e.col-t.col);for(let l of c){let c=this.getters.getCell(l),u=this.extractCustomStyle(c);if(Object.keys(u).length){let e=od(u,n);a[e]??=[],a[e].push(l)}if(c.format){let e=od(c.format,r);o[e]??=[],o[e].push(l)}let d=E(l.col,l.row);c.isFormula?s[d]=t?e.squish(c,i.id):c.compiledFormula.toFormulaString(this.getters):c.content&&(s[d]=t?e.squish(c,i.id):c.content)}i.styles=sd(a),i.formats=sd(o),i.cells=t?e.squishSheet(s,i.id):s}e.styles=n,e.formats=r}importCell(e,t,n,r,i){let a=this.getNextCellId();return i?Vu(a,i,r,n):Ru(this.getters,a,t||``,r,n,e,{avoidAutomaticDateFormat:!0})}exportForExcel(e){this.export(e,!1);let t=[];for(let n in e.formats||[])ru(e.formats[n])||(t.push(Number(n)),delete e.formats[n]);if(t.length)for(let n of e.sheets)for(let e in n.formats){let r=n.formats[e];r&&t.includes(r)&&delete n.formats[e]}}extractCustomStyle(e){let t={...e.style},n=!e.isFormula&&Pa(e.content,V)?Ce:xe;for(let r in t)(r!==`align`||!e.isFormula)&&t[r]===n[r]&&delete t[r];return t}getCells(e){return Object.values(this.cells[e]||{})}getCellById(e){let t=this.getters.getCellPosition(e);return this.cells[t.sheetId][e]}getFormulaString(e,t,n,r=!1){return Rc.CopyWithDependencies(t,e,n).toFormulaString(this.getters,{useBoundedReference:r})}getTranslatedCellFormula(e,t,n,r){r instanceof Rc||(r=Rc.CompileForSerializedFormula(e,r));let i=this.getters.createAdaptedRanges(r.rangeDependencies,t,n,e);return this.getFormulaString(e,r,i)}getFormulaMovedInSheet(e,t){let n=this.getters.removeRangesSheetPrefix(e,t.rangeDependencies);return Rc.CopyWithDependencies(t,e,n).toFormulaString(this.getters)}getCellStyle(e){return this.getters.getCell(e)?.style||{}}zoneToXC(e,t,n=[{colFixed:!1,rowFixed:!1}]){t=this.getters.expandZone(e,t);let r=E(t.left,t.top,n[0]),i=E(t.right,t.bottom,n.length>1?n[1]:n[0]),a=this.getters.getMainCellPosition({sheetId:e,col:t.left,row:t.top}),o=this.getters.getMainCellPosition({sheetId:e,col:t.right,row:t.bottom}),s=a.col===o.col&&a.row===o.row;return r!==i&&!s?r+`:`+i:r}setStyleFormat(e,t,n,r){if(!(n===void 0&&r===void 0))for(let i of cn(t))for(let t=i.left;t<=i.right;t++)for(let a=i.top;a<=i.bottom;a++){let i=this.getters.getCell({sheetId:e,col:t,row:a});this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:a,style:n?{...i?.style,...n}:void 0,format:r})}}copyColumnStyle(e,t,n){for(let r=0;r<this.getters.getNumberRows(e);r++){let i=this.getFormat(e,t,r);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,...i})}}copyRowStyle(e,t,n){for(let r=0;r<this.getters.getNumberCols(e);r++){let i=this.getFormat(e,r,t);if(i.style||i.format)for(let t of n)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:r,row:t,...i})}}getFormat(e,t,n){let r={},i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.getters.getCell(i);return a&&(a.style&&(r.style=a.style),a.format&&(r.format=a.format)),r}getNextCellId(){let e=this.nextId;return this.history.update(`nextId`,this.nextId+1),e}updateCell(e,t,n,r){let i=this.getters.getCell({sheetId:e,col:t,row:n}),a=r.content!==void 0||`formula`in r,o;o=a?Mt(r?.content):i?.isFormula?i.compiledFormula.toFormulaString(this.getters):i?.content||``;let s;s=r.style===void 0?i?i.style:void 0:r.style||void 0;let c=r.format===void 0?i&&i.format:r.format;if((a&&!o&&!r.formula||!a&&(!i||!i.isFormula&&i.content===``))&&!s&&!c){i&&(this.history.update(`cells`,e,i.id,void 0),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:void 0,col:t,row:n,sheetId:e}));return}let l=i?.id||this.getNextCellId(),u=Ru(this.getters,l,o,c,s,e);this.history.update(`cells`,e,u.id,u),this.dispatch(`UPDATE_CELL_POSITION`,{cellId:u.id,col:t,row:n,sheetId:e})}checkCellOutOfSheet(e){let{sheetId:t,col:n,row:r}=e;return this.getters.tryGetSheet(t)?Fn(n,r,this.getters.getSheetZone(t))?`Success`:`TargetOutOfSheet`:`InvalidSheetId`}checkUselessClearCell(e){let t=this.getters.getCell(e);return!t||!t.isFormula&&!t.content&&!t.style&&!t.format?`NoChanges`:`Success`}checkUselessUpdateCell(e){let t=this.getters.getCell(e),n=`content`in e||`formula`in e,r=`style`in e,i=`format`in e;return(!n||t?.isFormula&&t.compiledFormula.toFormulaString(this.getters)===e.content||!t?.isFormula&&t?.content===e.content)&&(!r||T(t?.style,e.style))&&(!i||t?.format===e.format)?`NoChanges`:`Success`}checkUselessSetFormatting(e){let{sheetId:t,target:n}=e,r=`style`in e,i=`format`in e;if(!r&&!i)return`NoChanges`;for(let a of cn(n))for(let n=a.left;n<=a.right;n++)for(let o=a.top;o<=a.bottom;o++){let a={sheetId:t,col:n,row:o},s=this.getters.getCell(a);if(r&&!T(s?.style,e.style)||i&&s?.format!==e.format)return`Success`}return`NoChanges`}},AI=class extends SI{static getters=[`isChartDefined`,`getChartDefinition`,`getChartType`,`getChartIds`,`getChart`,`getFigureIdFromChartId`,`getContextCreationChart`];charts={};adaptRanges(e){for(let[t,n]of Object.entries(this.charts)){if(!n)continue;let r=yO.fromDefinition(this.getters,n.chart.sheetId,n.chart.updateRanges(e));this.history.update(`charts`,t,r?{figureId:n.figureId,chart:r}:void 0)}}allowDispatch(e){switch(e.type){case`CREATE_CHART`:return this.checkValidations(e,this.chainValidations(this.checkFigureArguments,this.checkChartDefinition,this.checkChartDuplicate));case`UPDATE_CHART`:return this.checkValidations(e,this.chainValidations(this.checkChartDefinition,this.checkChartExists,this.checkChartChanged));case`DELETE_CHART`:return`SubCommandOnly`;default:return`Success`}}handle(e){switch(e.type){case`CREATE_CHART`:let{col:t,row:n,offset:r,size:i,sheetId:a,figureId:o}=e;!this.getters.getFigure(a,o)&&r!==void 0&&t!==void 0&&n!==void 0&&this.addFigure(o,a,t,n,r,i),this.addChart(e.figureId,e.chartId,e.definition);break;case`UPDATE_CHART`:this.addChart(e.figureId,e.chartId,e.definition);break;case`DUPLICATE_SHEET`:for(let t of this.getChartIds(e.sheetId)){let{chart:n,figureId:r}=this.charts[t]||{};if(!n||!r)continue;let i=this.getters.getFigure(e.sheetId,r);if(!i)continue;let a=r.split(`??`).pop(),o=`${e.sheetIdTo}??${a}`,s=t.split(`??`).pop(),c=`${e.sheetIdTo}??${s}`,l=n.duplicateInDuplicatedSheet(e.sheetId,e.sheetIdTo);this.dispatch(`CREATE_CHART`,{figureId:o,chartId:c,col:i.col,row:i.row,offset:i.offset,size:{width:i.width,height:i.height},definition:l,sheetId:e.sheetIdTo})}break;case`DELETE_FIGURE`:for(let t in this.charts)this.charts[t]?.figureId===e.figureId&&this.dispatch(`DELETE_CHART`,{chartId:t,sheetId:e.sheetId});break;case`DELETE_CHART`:this.isChartDefined(e.chartId)&&this.history.update(`charts`,e.chartId,void 0);break;case`DELETE_SHEET`:for(let t of this.getChartIds(e.sheetId))this.history.update(`charts`,t,void 0);break}}getContextCreationChart(e){return this.charts[e]?.chart.getContextCreation()}getChart(e){return this.charts[e]?.chart}getFigureIdFromChartId(e){if(!this.charts[e])throw Error(`Chart with id ${e} does not exist.`);return this.charts[e].figureId}getChartType(e){let t=this.charts[e]?.chart.getRangeDefinition().type;if(!t)throw Error(`Chart not defined.`);return t}isChartDefined(e){return e in this.charts&&this.charts!==void 0}getChartIds(e){return Object.entries(this.charts).filter(([,t])=>t?.chart.sheetId===e).map(([e])=>e)}getChartDefinition(e){let t=this.charts[e]?.chart.getDefinition();if(!t)throw Error(`There is no chart with the given id: ${e}`);return t}import(e){for(let t of e.sheets)if(t.figures){for(let e of t.figures)if(e.tag===`chart`){let n=e.data.chartId,r={...e.data};delete r.chartId;let i=yO.fromStrDefinition(this.getters,t.id,r);this.charts[n]={chart:i,figureId:e.id}}else if(e.tag===`carousel`)for(let n in e.data.chartDefinitions||{}){let r=e.data.chartDefinitions[n],i=yO.fromStrDefinition(this.getters,t.id,r);this.charts[n]={chart:i,figureId:e.id}}}}export(e){if(e.sheets)for(let t of e.sheets){let e=this.getters.getFigures(t.id),n=[];for(let t of e){let e=t,r=Object.keys(this.charts).find(e=>this.charts[e]?.figureId===t.id);if(e&&e.tag===`chart`&&r){let t=this.charts[r]?.chart.getDefinition();t&&(e.data={...t,chartId:r},n.push(e))}else if(e&&e.tag===`carousel`){let r=Object.keys(this.charts).filter(e=>this.charts[e]?.figureId===t.id),i={};for(let e of r)i[e]=this.charts[e]?.chart.getDefinition();e.data={chartDefinitions:i},n.push(e)}else n.push(e)}t.figures=n}}addFigure(e,t,n,r,i,a={width:536,height:335}){this.dispatch(`CREATE_FIGURE`,{sheetId:t,figureId:e,col:n,row:r,offset:i,size:a,tag:`chart`})}addChart(e,t,n){let r=this.getters.getFigureSheetId(e);if(r){let i=yO.fromStrDefinition(this.getters,r,n);this.history.update(`charts`,t,{figureId:e,chart:i})}}checkChartDuplicate(e){return this.isChartDefined(e.chartId)?`DuplicatedChartId`:`Success`}checkChartDefinition(e){return yO.validate(this,e.definition)}checkChartExists(e){return this.isChartDefined(e.chartId)?`Success`:`ChartDoesNotExist`}checkChartChanged(e){return e.figureId===this.charts[e.chartId]?.figureId&&T(this.getChartDefinition(e.chartId),e.definition)?`NoChanges`:`Success`}checkFigureArguments(e){return this.getters.getFigure(e.sheetId,e.figureId)||e.offset!==void 0&&e.col!==void 0&&e.row!==void 0?`Success`:`MissingFigureArguments`}};function jI(e){return e===``?NaN:Number(e)}var MI=class extends SI{static getters=[`getConditionalFormats`,`getRulesSelection`,`getRulesByCell`,`getAdaptedCfRanges`];cfRules={};adaptCFFormulas({applyChange:e,adaptFormulaString:t}){for(let n in this.cfRules)for(let r of this.cfRules[n])if(r.rule.type===`DataBarRule`&&r.rule.rangeValues){let t=e(r.rule.rangeValues);switch(t.changeType){case`REMOVE`:this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`rangeValues`,void 0);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`rangeValues`,t.range);break}}else if(r.rule.type===`CellIsRule`)for(let e=0;e<r.rule.values.length;e++)this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,`values`,e,t(n,r.rule.values[e]));else if(r.rule.type===`IconSetRule`)for(let e of[`lowerInflectionPoint`,`upperInflectionPoint`])r.rule[e].type===`formula`&&this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,e,`value`,t(n,r.rule[e].value));else if(r.rule.type===`ColorScaleRule`)for(let e of[`minimum`,`maximum`,`midpoint`]){let i=r.rule[e];i?.type===`formula`&&i?.value&&this.history.update(`cfRules`,n,this.cfRules[n].indexOf(r),`rule`,e,`value`,t(n,i.value))}}adaptCFRanges(e,{applyChange:t}){for(let n of this.cfRules[e])for(let r of n.ranges){let i=t(r);switch(i.changeType){case`REMOVE`:let t=n.ranges.slice();t.splice(n.ranges.indexOf(r),1),t.length>=1?this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,t):this.removeConditionalFormatting(n.id,e);break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`cfRules`,e,this.cfRules[e].indexOf(n),`ranges`,n.ranges.indexOf(r),i.range);break}}}adaptRanges(e){for(let t of Object.keys(this.cfRules))this.adaptCFRanges(t,e);this.adaptCFFormulas(e)}allowDispatch(e){switch(e.type){case`ADD_CONDITIONAL_FORMAT`:return e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkValidations(e,this.checkCFRule,this.checkEmptyRange,this.checkCFHasChanged);case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:return this.checkValidPriorityChange(e.cfId,e.delta,e.sheetId)}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.cfRules[e.sheetId]=[];break;case`DUPLICATE_SHEET`:this.history.update(`cfRules`,e.sheetIdTo,[]);for(let t of this.getConditionalFormats(e.sheetId))this.addConditionalFormatting(t,e.sheetIdTo);break;case`DELETE_SHEET`:let t=Object.assign({},this.cfRules);delete t[e.sheetId],this.history.update(`cfRules`,t);break;case`ADD_CONDITIONAL_FORMAT`:let n={...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))};this.addConditionalFormatting(n,e.sheetId);break;case`REMOVE_CONDITIONAL_FORMAT`:this.removeConditionalFormatting(e.id,e.sheetId);break;case`CHANGE_CONDITIONAL_FORMAT_PRIORITY`:this.changeCFPriority(e.cfId,e.delta,e.sheetId);break}}import(e){for(let t of e.sheets)this.cfRules[t.id]=t.conditionalFormats.map(e=>this.mapToConditionalFormatInternal(t.id,e))}export(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e)))}exportForExcel(e){if(e.sheets)for(let t of e.sheets)this.cfRules[t.id]&&(t.conditionalFormats=this.cfRules[t.id].map(e=>this.mapToConditionalFormat(t.id,e,{useBoundedReference:!0})))}getConditionalFormats(e){return this.cfRules[e]?.map(t=>this.mapToConditionalFormat(e,t))||[]}getRulesSelection(e,t){let n=new Set;return t.forEach(t=>{this.getRulesByZone(e,t).forEach(e=>{n.add(e)})}),Array.from(n)}getRulesByZone(e,t){let n=new Set;for(let r=t.top;r<=t.bottom;r++)for(let i=t.left;i<=t.right;i++)this.getRulesByCell(e,i,r).forEach(e=>{n.add(e.id)});return n}getRulesByCell(e,t,n){let r=[];for(let i of this.cfRules[e])for(let e of i.ranges)Fn(t,n,e.zone)&&r.push(i);return new Set(r.map(t=>this.mapToConditionalFormat(e,t)))}getAdaptedCfRanges(e,t,n,r){if(n.length===0&&r.length===0)return;let i=this.getters.getConditionalFormats(e),a=i.findIndex(e=>e.id===t.id),o=[];a>-1&&(o=i[a].ranges.map(vn));let s=cn(o,r);return cn([...n,...s],[]).map(t=>this.getters.getRangeDataFromZone(e,t))}mapToConditionalFormat(e,t,{useBoundedReference:n}={useBoundedReference:!1}){let r=t.ranges.map(t=>this.getters.getRangeString(t,e,{useBoundedReference:n}));return t.rule.type===`DataBarRule`?{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues&&this.getters.getRangeString(t.rule.rangeValues,e,{useBoundedReference:n})},ranges:r}:{...t,rule:{...t.rule},ranges:r}}mapToConditionalFormatInternal(e,t){let n=t.ranges.map(t=>this.getters.getRangeFromSheetXC(e,t));return t.rule.type===`DataBarRule`?{...t,rule:{...t.rule,rangeValues:t.rule.rangeValues?this.getters.getRangeFromSheetXC(e,t.rule.rangeValues):void 0},ranges:n}:{...t,rule:{...t.rule},ranges:n}}addConditionalFormatting(e,t){let n=this.cfRules[t].slice(),r=n.findIndex(t=>t.id===e.id),i=this.mapToConditionalFormatInternal(t,e);r>-1?n.splice(r,1,i):n.push(i),this.history.update(`cfRules`,t,n)}checkValidPriorityChange(e,t,n){if(!this.cfRules[n])return`InvalidSheetId`;let r=this.cfRules[n].findIndex(t=>t.id===e);if(r===-1)return`InvalidConditionalFormatId`;let i=r-t;return i<0||i>=this.cfRules[n].length?`InvalidConditionalFormatId`:`Success`}checkEmptyRange(e){return e.ranges.length?`Success`:`EmptyRange`}checkCFRule(e){let t=e.cf.rule;switch(t.type){case`CellIsRule`:return Vh.has(t.operator)?this.checkValidations(t,this.checkOperatorArgsNumber,this.checkCFValues):`InvalidConditionalFormatType`;case`ColorScaleRule`:return this.checkValidations(t,this.chainValidations(this.checkThresholds(this.checkFormulaCompilation)),this.chainValidations(this.checkThresholds(this.checkNaN),this.batchValidations(this.checkMinBiggerThanMax,this.checkMinBiggerThanMid,this.checkMidBiggerThanMax)));case`IconSetRule`:return this.checkValidations(t,this.chainValidations(this.checkInflectionPoints(this.checkNaN),this.checkLowerBiggerThanUpper),this.chainValidations(this.checkInflectionPoints(this.checkFormulaCompilation)));case`DataBarRule`:return`Success`}return`InvalidConditionalFormatType`}checkCFHasChanged(e){let t=this.mapToConditionalFormatInternal(e.sheetId,{...e.cf,ranges:e.ranges.map(t=>this.getters.getRangeString(this.getters.getRangeFromRangeData(t),e.sheetId))}),n=this.cfRules[e.sheetId]?.find(t=>t.id===e.cf.id);return n&&T(t,n)?`NoChanges`:`Success`}checkOperatorArgsNumber(e){let t=X.get(e.operator).numberOfValues({type:e.operator,values:e.values});if(t===void 0||t>2)throw Error(`Checking more than 2 arguments is currently not supported. Add the appropriate CommandResult if you want to.`);let n=[],r=e=>e===void 0||e===``;return t>=1&&r(e.values[0])&&n.push(`FirstArgMissing`),t>=2&&r(e.values[1])&&n.push(`SecondArgMissing`),n.length?n:`Success`}checkNaN(e,t){if([`number`,`percentage`,`percentile`].includes(e.type)&&(e.value===``||isNaN(e.value)))switch(t){case`min`:return`MinNaN`;case`max`:return`MaxNaN`;case`mid`:return`MidNaN`;case`upperInflectionPoint`:return`ValueUpperInflectionNaN`;case`lowerInflectionPoint`:return`ValueLowerInflectionNaN`}return`Success`}checkFormulaCompilation(e,t){if(e.type!==`formula`)return`Success`;if(Rc.IsBadExpression(e.value||``))switch(t){case`min`:return`MinInvalidFormula`;case`max`:return`MaxInvalidFormula`;case`mid`:return`MidInvalidFormula`;case`upperInflectionPoint`:return`ValueUpperInvalidFormula`;case`lowerInflectionPoint`:return`ValueLowerInvalidFormula`}return`Success`}checkThresholds(e){return this.batchValidations(t=>e(t.minimum,`min`),t=>e(t.maximum,`max`),t=>t.midpoint?e(t.midpoint,`mid`):`Success`)}checkInflectionPoints(e){return this.batchValidations(t=>e(t.lowerInflectionPoint,`lowerInflectionPoint`),t=>e(t.upperInflectionPoint,`upperInflectionPoint`))}checkLowerBiggerThanUpper(e){let t=e.lowerInflectionPoint.value,n=e.upperInflectionPoint.value;return[`number`,`percentage`,`percentile`].includes(e.lowerInflectionPoint.type)&&e.lowerInflectionPoint.type===e.upperInflectionPoint.type&&Number(t)>Number(n)?`LowerBiggerThanUpper`:`Success`}checkMinBiggerThanMax(e){let t=e.minimum.value,n=e.maximum.value;return[`number`,`percentage`,`percentile`].includes(e.minimum.type)&&e.minimum.type===e.maximum.type&&jI(t)>=jI(n)?`MinBiggerThanMax`:`Success`}checkMidBiggerThanMax(e){let t=e.midpoint?.value,n=e.maximum.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.midpoint.type===e.maximum.type&&jI(t)>=jI(n)?`MidBiggerThanMax`:`Success`}checkMinBiggerThanMid(e){let t=e.minimum.value,n=e.midpoint?.value;return e.midpoint&&[`number`,`percentage`,`percentile`].includes(e.midpoint.type)&&e.minimum.type===e.midpoint.type&&jI(t)>=jI(n)?`MinBiggerThanMid`:`Success`}checkCFValues(e){for(let t of e.values)if(t.startsWith(`=`)&&Rc.IsBadExpression(t))return`ValueCellIsInvalidFormula`;return`Success`}removeConditionalFormatting(e,t){let n=this.cfRules[t].findIndex(t=>t.id===e);if(n!==-1){let e=this.cfRules[t].slice();e.splice(n,1),this.history.update(`cfRules`,t,e)}}changeCFPriority(e,t,n){let r=this.cfRules[n].findIndex(t=>t.id===e),i=this.cfRules[n][r],a=r-t,o=[...this.cfRules[n]];o.splice(r,1),o.splice(a,0,i),this.history.update(`cfRules`,n,o)}},NI=class extends SI{static getters=[`cellHasListDataValidationIcon`,`getDataValidationRule`,`getDataValidationRules`,`getValidationRuleForCell`];rules={};adaptRanges(e){for(let t in this.rules)this.adaptDVRanges(t,e);this.adaptDVFormulas(e)}adaptDVFormulas({adaptFormulaString:e}){for(let t in this.rules){let n=this.rules[t];for(let r=n.length-1;r>=0;r--){let n=this.rules[t][r];for(let i=0;i<n.criterion.values.length;i++){let a=e(t,n.criterion.values[i]);this.history.update(`rules`,t,r,`criterion`,`values`,i,a)}}}}adaptDVRanges(e,{applyChange:t}){let n=this.rules[e];for(let r=n.length-1;r>=0;r--){let n=this.rules[e][r];for(let i=n.ranges.length-1;i>=0;i--){let a=n.ranges[i],o=t(a);switch(o.changeType){case`REMOVE`:if(n.ranges.length===1)this.removeDataValidationRule(e,n.id);else{let t=n.ranges.slice();t.splice(i,1),this.history.update(`rules`,e,r,`ranges`,t)}break;case`RESIZE`:case`MOVE`:case`CHANGE`:this.history.update(`rules`,e,r,`ranges`,i,o.range);break}}}}allowDispatch(e){switch(e.type){case`ADD_DATA_VALIDATION_RULE`:return!this.getters.tryGetSheet(e.sheetId)||e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:this.checkValidations(e,this.chainValidations(this.checkEmptyRange,this.checkValidRange,this.checkCriterionTypeIsValid,this.checkCriterionHasValidNumberOfValues,this.checkCriterionValuesAreValid));case`REMOVE_DATA_VALIDATION_RULE`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;if(!this.rules[e.sheetId].find(t=>t.id===e.id))return`UnknownDataValidationRule`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`rules`,e.sheetId,[]);break;case`DUPLICATE_SHEET`:{let t=x(this.rules[e.sheetId]).map(t=>({...t,ranges:t.ranges.map(t=>tc(e.sheetId,e.sheetIdTo,t))}));this.history.update(`rules`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.rules};delete t[e.sheetId],this.history.update(`rules`,t);break}case`REMOVE_DATA_VALIDATION_RULE`:this.removeDataValidationRule(e.sheetId,e.id);break;case`ADD_DATA_VALIDATION_RULE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e));this.addDataValidationRule(e.sheetId,{...e.rule,ranges:t});break}case`DELETE_CONTENT`:{let t=cn(e.target),n=e.sheetId;for(let e of t)for(let t=e.top;t<=e.bottom;t++)for(let r=e.left;r<=e.right;r++){let e=this.getValidationRuleForCell({sheetId:n,col:r,row:t});if(!e)continue;let i=this.getters.getCell({sheetId:n,col:r,row:t});if(e.criterion.type===`isBoolean`||e.criterion.type===`isValueInList`&&!i?.isFormula&&!i?.content){let e=this.rules[n],i=[this.getters.getRangeFromSheetXC(n,E(r,t))],a=this.removeRangesFromRules(n,i,e);this.history.update(`rules`,n,a)}}}}}getDataValidationRules(e){return this.rules[e]}getDataValidationRule(e,t){return this.rules[e].find(e=>e.id===t)}getValidationRuleForCell({sheetId:e,col:t,row:n}){if(this.rules[e]){for(let r of this.rules[e])for(let e of r.ranges)if(Fn(t,n,e.zone))return r}}cellHasListDataValidationIcon(e){let t=this.getValidationRuleForCell(e);return t?(t.criterion.type===`isValueInList`||t.criterion.type===`isValueInRange`)&&(t.criterion.displayStyle===`arrow`||t.criterion.displayStyle===`chip`):!1}addDataValidationRule(e,t){let n=this.rules[e];t.criterion.type===`isBoolean`?this.setCenterStyleToBooleanCells(t):t.criterion.type===`isValueInList`&&(t.criterion.values=Array.from(new Set(t.criterion.values)));let r=this.removeRangesFromRules(e,t.ranges,n,t.id),i=r.findIndex(e=>e.id===t.id);i===-1?this.history.update(`rules`,e,[...r,t]):(r[i]=t,this.history.update(`rules`,e,r))}removeRangesFromRules(e,t,n,r){n=x(n);for(let e of n)e.id!==r&&(e.ranges=this.getters.recomputeRanges(e.ranges,t));return n.filter(e=>e.ranges.length>0)}removeDataValidationRule(e,t){let n=this.rules[e].filter(e=>e.id!==t);this.history.update(`rules`,e,n)}setCenterStyleToBooleanCells(e){for(let t of rc(e.ranges)){let e=this.getters.getCell(t),n={...e?.style,align:e?.style?.align??`center`,verticalAlign:e?.style?.verticalAlign??`middle`};this.dispatch(`UPDATE_CELL`,{...t,style:n})}}checkEmptyRange(e){return e.ranges.length?`Success`:`EmptyRange`}import(e){for(let t of e.sheets)if(this.rules[t.id]=[],t.dataValidationRules)for(let e of t.dataValidationRules)this.rules[t.id].push({...e,ranges:e.ranges.map(e=>this.getters.getRangeFromSheetXC(t.id,e))})}export(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id])t.dataValidationRules.push({...e,ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id))})}}exportForExcel(e){if(e.sheets)for(let t of e.sheets){t.dataValidationRules=[];for(let e of this.rules[t.id]){let n={...x(e),ranges:e.ranges.map(e=>this.getters.getRangeString(e,t.id,{useBoundedReference:!0}))};e.criterion.type===`isValueInRange`&&(n.criterion.values=e.criterion.values.map(e=>{let n=this.getters.getRangeFromSheetXC(t.id,e);return this.getters.getRangeString(n,t.id,{useBoundedReference:!0,useFixedReference:!0})})),t.dataValidationRules.push(n)}}}checkCriterionTypeIsValid(e){return X.contains(e.rule.criterion.type)?`Success`:`UnknownDataValidationCriterionType`}checkCriterionHasValidNumberOfValues(e){let t=e.rule.criterion,n=X.get(t.type).numberOfValues(t);return n!==void 0&&t.values.length!==n?`InvalidNumberOfCriterionValues`:`Success`}checkCriterionValuesAreValid(e){let t=e.rule.criterion,n=X.get(t.type);return t.values.some(e=>n.allowedValues===`onlyFormulas`&&!e.startsWith(`=`)?!0:e.startsWith(`=`)?n.allowedValues===`onlyLiterals`||Rc.IsBadExpression(e):!n.isCriterionValueValid(e))?`InvalidDataValidationCriterionValue`:`Success`}checkValidRange(e){return e.ranges.map(e=>this.getters.getRangeFromRangeData(e)).map(t=>this.getters.getRangeString(t,e.sheetId)).some(e=>!this.getters.isRangeValid(e))?`InvalidRange`:`Success`}},PI=class extends SI{static getters=[`getFigures`,`getFigure`,`getFigureSheetId`];figures={};insertionOrders=[];adaptRanges(e){for(let t in this.figures)this.adaptRangesOnSheet(e,t)}adaptRangesOnSheet({applyChange:e},t){for(let n of this.getFigures(t)){let r=e(this.getters.getRangeFromZone(t,{left:n.col,right:n.col,top:n.row,bottom:n.row}));if(r.changeType===`MOVE`)this.history.update(`figures`,t,n.id,`col`,r.range.zone.right),this.history.update(`figures`,t,n.id,`row`,r.range.zone.bottom);else if(r.changeType===`REMOVE`){let r=e(this.getters.getRangeFromZone(t,{left:0,right:n.col-1,top:0,bottom:n.row-1})),{offset:i,col:a,row:o}=n;r.changeType!==`NONE`&&(a=r.range.zone.right+1,o=r.range.zone.bottom+1),{offset:i,col:a,row:o}=this.getPositionInSheet(t,{...n,col:a,row:o}),this.history.update(`figures`,t,n.id,`offset`,i),this.history.update(`figures`,t,n.id,`col`,a),this.history.update(`figures`,t,n.id,`row`,o)}}}allowDispatch(e){switch(e.type){case`CREATE_FIGURE`:return this.checkValidations(e,this.checkFigureDuplicate,this.checkFigureAnchorOffset);case`UPDATE_FIGURE`:return this.checkValidations(e,this.checkFigureExists,this.checkFigureAnchorOffset);case`DELETE_FIGURE`:return this.checkFigureExists(e);default:return`Success`}}beforeHandle(e){switch(e.type){case`DELETE_SHEET`:this.getters.getFigures(e.sheetId).forEach(t=>{this.dispatch(`DELETE_FIGURE`,{figureId:t.id,sheetId:e.sheetId})});break}}handle(e){switch(e.type){case`CREATE_SHEET`:this.figures[e.sheetId]={};break;case`DELETE_SHEET`:this.deleteSheet(e.sheetId);break;case`CREATE_FIGURE`:let t={id:e.figureId,col:e.col,row:e.row,offset:e.offset,width:e.size.width,height:e.size.height,tag:e.tag};this.addFigure(t,e.sheetId);break;case`UPDATE_FIGURE`:this.updateFigure(e);break;case`DELETE_FIGURE`:this.removeFigure(e.figureId,e.sheetId);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.onColRemove(e.sheetId):this.onRowRemove(e.sheetId);break;case`DUPLICATE_SHEET`:for(let t of this.getFigures(e.sheetId)){let n=t.id,r=this.figures[e.sheetId]?.[n];if(!r)continue;let i=n.split(`??`).pop(),a=`${e.sheetIdTo}??${i}`;this.dispatch(`CREATE_FIGURE`,{figureId:a,...r,size:{width:r.width,height:r.height},sheetId:e.sheetIdTo})}break}}onColRemove(e){let t=this.getters.getNumberCols(e),n=Array(t+1);n[t]=0;for(let r=t-1;r>=0;r--)n[r]=n[r+1]+this.getters.getColSize(e,r);for(let t of this.getFigures(e))if(t.offset.x+t.width>n[t.col]){let r=t.offset.x,i=t.col;for(r=Math.min(r,n[i]-t.width);r<0&&i>0;)i--,r=n[i]-t.width;r!==t.offset.x&&this.history.update(`figures`,e,t.id,`offset`,{x:Math.max(r,0),y:t.offset.y}),i!==t.col&&this.history.update(`figures`,e,t.id,`col`,i)}}onRowRemove(e){let t=this.getters.getNumberRows(e),n=Array(t+1);n[t]=0;for(let r=t-1;r>=0;r--)n[r]=n[r+1]+(this.getters.getUserRowSize(e,r)??23);for(let t of this.getFigures(e))if(t.offset.y+t.height>n[t.row]){let r=t.offset.y,i=t.row;for(let t=this.getters.getUserRowSize(e,i)??23;t<r;t=this.getters.getUserRowSize(e,i)??23)i+=1,r-=t;for(r=Math.min(r,n[i]-t.height);r<0&&i>0;)i--,r=n[i]-t.height;r!==t.offset.y&&this.history.update(`figures`,e,t.id,`offset`,{x:t.offset.x,y:Math.max(0,r)}),i!==t.row&&this.history.update(`figures`,e,t.id,`row`,i)}else t.offset.y+t.height>n[0]&&this.history.update(`figures`,e,t.id,`offset`,{x:t.offset.x,y:Math.max(n[0]-t.height,0)})}getPositionInSheet(e,t){let{numberOfRows:n,numberOfCols:r}=this.getters.getSheetSize(e),i=0,a=0,o,s,{col:c,row:l}=t,u={...t.offset};for(o=n;i<t.height&&o>0;o--)i+=this.getters.getUserRowSize(e,o-1)??23;for(l>o?(l=o,u.y=Math.max(i-t.height,0)):l===o&&(u.y=S(u.y,0,Math.max(i-t.height,0))),s=r;a<t.width&&s>0;s--)a+=this.getters.getColSize(e,s-1);return c>s?(c=s,u.x=Math.max(a-t.width,0)):s===c&&(u.x=S(u.x,0,Math.max(a-t.width,0))),{col:c,row:l,offset:u}}updateFigure(e){if(!(`figureId`in e)||!(`sheetId`in e))return;let{figureId:t,sheetId:n,...r}=e,i={...this.getFigure(n,t),...r};for(let[e,t]of Object.entries(r))switch(e){case`tag`:this.history.update(`figures`,n,i.id,e,t);break;case`offset`:this.history.update(`figures`,n,i.id,e,t);break;case`col`:case`row`:case`width`:case`height`:t!==void 0&&this.history.update(`figures`,n,i.id,e,t);break}}addFigure(e,t){this.history.update(`figures`,t,e.id,e),this.history.update(`insertionOrders`,this.insertionOrders.length,e.id)}deleteSheet(e){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>!this.figures[e]?.[t])),this.history.update(`figures`,e,void 0)}removeFigure(e,t){this.history.update(`insertionOrders`,this.insertionOrders.filter(t=>t!==e)),this.history.update(`figures`,t,e,void 0)}checkFigureExists(e){return this.figures[e.sheetId]?.[e.figureId]===void 0?`FigureDoesNotExist`:`Success`}checkFigureDuplicate(e){return Object.values(this.figures).find(t=>t?.[e.figureId])?`DuplicatedFigureId`:`Success`}checkFigureAnchorOffset(e){return e.col<0||e.row<0||e.offset&&(e.offset.x<0||e.offset.y<0)?`WrongSheetPosition`:`Success`}getFigures(e){let t=[];for(let n of this.insertionOrders){let r=this.figures[e]?.[n];r&&t.push(r)}return t}getFigure(e,t){return this.figures[e]?.[t]}getFigureSheetId(e){return Object.keys(this.figures).find(t=>this.figures[t]?.[e]!==void 0)}import(e){for(let t of e.sheets)for(let e of t.figures)this.addFigure(e,t.id)}export(e){for(let t of e.sheets)for(let e of this.getFigures(t.id))t.figures.push({...e,data:void 0})}exportForExcel(e){return this.export(e)}},FI=class extends SI{static getters=[`getHeaderGroups`,`getGroupsLayers`,`getVisibleGroupLayers`,`getHeaderGroup`,`getHeaderGroupsInZone`,`isGroupFolded`,`isRowFolded`,`isColFolded`];groups={};allowDispatch(e){switch(e.type){case`GROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;if(this.findGroupWithStartEnd(e.sheetId,e.dimension,t,n))return`HeaderGroupAlreadyExists`;break}case`UNGROUP_HEADERS`:{let{start:t,end:n,sheetId:r}=e;if(!this.getters.tryGetSheet(r))return`InvalidSheetId`;if(!this.getters.doesHeadersExist(e.sheetId,e.dimension,[t,n])||t>n)return`InvalidHeaderGroupStartEnd`;break}case`UNFOLD_HEADER_GROUP`:case`FOLD_HEADER_GROUP`:if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);if(!t)return`UnknownHeaderGroup`;if(C(0,this.getters.getNumberHeaders(e.sheetId,e.dimension)).every(n=>n>=t.start&&n<=t.end||this.getters.isHeaderHiddenByUser(e.sheetId,e.dimension,n)))return`NotEnoughElements`;break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`groups`,e.sheetId,{ROW:[],COL:[]});break;case`GROUP_HEADERS`:this.groupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`UNGROUP_HEADERS`:this.unGroupHeaders(e.sheetId,e.dimension,e.start,e.end);break;case`DUPLICATE_SHEET`:{let t=x(this.groups[e.sheetId]);this.history.update(`groups`,e.sheetIdTo,t);break}case`DELETE_SHEET`:{let t={...this.groups};delete t[e.sheetId],this.history.update(`groups`,t);break}case`ADD_COLUMNS_ROWS`:let t=Ct(e.position,e.base);this.moveGroupsOnHeaderInsertion(e.sheetId,e.dimension,t,e.quantity);break;case`REMOVE_COLUMNS_ROWS`:this.moveGroupsOnHeaderDeletion(e.sheetId,e.dimension,e.elements);break;case`UNFOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.unfoldHeaderGroup(e.sheetId,e.dimension,t);break}case`FOLD_HEADER_GROUP`:{let t=this.findGroupWithStartEnd(e.sheetId,e.dimension,e.start,e.end);t&&this.foldHeaderGroup(e.sheetId,e.dimension,t);break}case`UNFOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.unfoldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_ALL_HEADER_GROUPS`:{let t=this.getters.getHeaderGroups(e.sheetId,e.dimension);for(let n of t)this.foldHeaderGroup(e.sheetId,e.dimension,n);break}case`FOLD_HEADER_GROUPS_IN_ZONE`:case`UNFOLD_HEADER_GROUPS_IN_ZONE`:{let t=e.type===`UNFOLD_HEADER_GROUPS_IN_ZONE`?`unfold`:`fold`,n=this.getGroupsLayers(e.sheetId,e.dimension);t===`fold`&&n.reverse();let r=n.flat(),i=e.dimension===`ROW`?e.zone.top:e.zone.left,a=e.dimension===`ROW`?e.zone.bottom:e.zone.right,o=new Set;for(let e=i;e<=a;e++){let n=r.filter(t=>t.start-1<=e&&e<=t.end);for(let e of n)if(!(t===`fold`&&e.isFolded||t===`unfold`&&!e.isFolded)){o.add(e);break}}for(let n of o)t===`unfold`?this.unfoldHeaderGroup(e.sheetId,e.dimension,n):this.foldHeaderGroup(e.sheetId,e.dimension,n);break}}}getHeaderGroups(e,t){return this.groups[e][t]}getHeaderGroup(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}getHeaderGroupsInZone(e,t,n){return this.getHeaderGroups(e,t).filter(e=>{let r=t===`ROW`?n.top:n.left,i=t===`ROW`?n.bottom:n.right;return this.doGroupOverlap(e,r,i)})}getGroupsLayers(e,t){let n=this.getHeaderGroups(e,t);return this.bricksFallingAlgorithm(n,0,0)}getVisibleGroupLayers(e,t){let n=this.getGroupsLayers(e,t);for(let r of n)for(let n=r.length-1;n>=0;n--){let i=r[n];i.start!==0&&C(i.start-1,i.end+1).every(n=>this.getters.isHeaderHiddenByUser(e,t,n))&&r.splice(n,1)}return n.filter(e=>e.length>0)}isGroupFolded(e,t,n,r){return this.getHeaderGroup(e,t,n,r)?.isFolded||!1}isRowFolded(e,t){return this.getters.getHeaderGroups(e,`ROW`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}isColFolded(e,t){return this.getters.getHeaderGroups(e,`COL`).some(e=>e.start<=t&&t<=e.end&&e.isFolded)}getGroupId(e){return`${e.start}-${e.end}}`}bricksFallingAlgorithm(e,t,n,r=0){let i={};for(let t of e)i[this.getGroupId(t)]=t.isFolded;let a={};for(let t of e)for(let e=t.start;e<=t.end;e++)a[e]=a[e]?a[e]+1:1;for(let e=t;e<=n;e++)a[e]=a[e]?a[e]+r:r;let o=Math.max(...Object.values(a),0),s=Array.from({length:o},()=>[]),c=Math.max(n,...e.map(e=>e.end)),l=Math.min(t,...e.map(e=>e.start));for(let e=l;e<=c;e++){let t=a[e]||0;for(let n=0;n<t;n++){let t=s[n].at(-1);if(t&&Nt([t.end,e]))t.end++;else{let t={start:e,end:e};s[n].push(t)}}}for(let e of s)for(let t of e)t.isFolded=i[this.getGroupId(t)];return s}groupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}unGroupHeaders(e,t,n,r){let i=this.getHeaderGroups(e,t),a=this.bricksFallingAlgorithm(i,n,r,-1).flat();this.history.update(`groups`,e,t,this.removeDuplicateGroups(a))}moveGroupsOnHeaderInsertion(e,t,n,r){let i=this.groups[e][t];for(let a=0;a<i.length;a++){let o=i[a],[s,c]=gc(n,r,[o.start,o.end]);(s!==o.start||c!==o.end)&&this.history.update(`groups`,e,t,a,{...o,start:s,end:c})}}moveGroupsOnHeaderDeletion(e,t,n){let r=this.getHeaderGroups(e,t),i=[];for(let e of r){let t=_c(n,C(e.start,e.end+1));t.length!==0&&i.push({...e,start:Math.min(...t),end:Math.max(...t)})}this.history.update(`groups`,e,t,this.bricksFallingAlgorithm(i,0,0).flat())}doGroupOverlap(e,t,n){return e.start<=n&&e.end>=t}removeDuplicateGroups(e){let t={};for(let n of e)t[this.getGroupId(n)]=n;return Object.values(t)}findGroupWithStartEnd(e,t,n,r){return this.getHeaderGroups(e,t).find(e=>e.start===n&&e.end===r)}foldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!0);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end<=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!0)}}unfoldHeaderGroup(e,t,n){let r=this.getGroupIndex(e,t,n.start,n.end);if(r===void 0)return;this.history.update(`groups`,e,t,r,`isFolded`,!1);let i=this.getters.getHeaderGroups(e,t);for(let r=0;r<i.length;r++){let a=i[r];a.start===n.start&&a.end>=n.end&&this.history.update(`groups`,e,t,r,`isFolded`,!1)}}getGroupIndex(e,t,n,r){let i=this.groups[e][t].findIndex(e=>e.start===n&&e.end===r);return i===-1?void 0:i}import(e){for(let t of e.sheets)if(this.groups[t.id]={ROW:[],COL:[]},t.headerGroups)for(let e of[`ROW`,`COL`])for(let n of t.headerGroups[e]||[])this.groups[t.id][e].push({...n})}export(e){for(let t of e.sheets)t.headerGroups=this.groups[t.id]}exportForExcel(e){for(let t of e.sheets)for(let e of[`ROW`,`COL`]){let n=this.getGroupsLayers(t.id,e);for(let r=0;r<n.length;r++){let i=n[r];for(let n of i){for(let i=n.start;i<=n.end;i++){let a=Ib(t,e,i);a.outlineLevel=r+1,n.isFolded&&(a.isHidden=!0)}if(n.isFolded){let r=Ib(t,e,n.end+1);r.collapsed=!0}}}}}},II=class extends SI{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,x(this.sizes[e.sheetId]));break;case`DELETE_SHEET`:let t={...this.sizes};delete t[e.sheetId],this.history.update(`sizes`,t);break;case`REMOVE_COLUMNS_ROWS`:{let t=this.sizes[e.sheetId][e.dimension],n=Ft(t,e.elements);this.history.update(`sizes`,e.sheetId,e.dimension,n);break}case`ADD_COLUMNS_ROWS`:{let t=this.sizes[e.sheetId][e.dimension],n=Ct(e.position,e.base),r=t[e.base],i=It(t,Array(e.quantity).fill(r),n);this.history.update(`sizes`,e.sheetId,e.dimension,i);break}case`RESIZE_COLUMNS_ROWS`:if(e.dimension===`ROW`)for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);else for(let t of e.elements)this.history.update(`sizes`,e.sheetId,e.dimension,t,e.size||void 0);break}}getColSize(e,t){return Math.round(this.sizes[e]?.COL[t]||96)}getUserRowSize(e,t){let n=this.sizes[e]?.ROW[t];return n?Math.round(n):void 0}import(e){for(let t of e.sheets){let e={COL:Array(t.colNumber).fill(void 0),ROW:Array(t.rowNumber).fill(void 0)};for(let[n,r]of Object.entries(t.rows))r.size&&(e.ROW[n]=r.size);for(let[n,r]of Object.entries(t.cols))r.size&&(e.COL[n]=r.size);this.sizes[t.id]=e}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e of C(0,this.getters.getNumberRows(n.id)))(t||this.sizes[n.id].ROW[e])&&(n.rows[e]={...n.rows[e],size:this.getUserRowSize(n.id,e)??23});n.cols===void 0&&(n.cols={});for(let e of C(0,this.getters.getNumberCols(n.id)))(t||this.sizes[n.id].COL[e])&&(n.cols[e]={...n.cols[e],size:this.getColSize(n.id,e)})}}},LI=class extends SI{static getters=[`checkElementsIncludeAllVisibleHeaders`,`getHiddenColsGroups`,`getHiddenRowsGroups`,`isHeaderHiddenByUser`,`isRowHiddenByUser`,`isColHiddenByUser`];hiddenHeaders={};allowDispatch(e){switch(e.type){case`HIDE_COLUMNS_ROWS`:{if(!this.getters.tryGetSheet(e.sheetId))return`InvalidSheetId`;let t=e.dimension===`COL`?this.getHiddenColsGroups(e.sheetId):this.getHiddenRowsGroups(e.sheetId),n=e.dimension===`COL`?this.getters.getNumberCols(e.sheetId):this.getters.getNumberRows(e.sheetId);return new Set((t||[]).flat().concat(e.elements)).size>=n?`TooManyHiddenElements`:Ht(e.elements)<0||Vt(e.elements)>n?`InvalidHeaderIndex`:`Success`}case`REMOVE_COLUMNS_ROWS`:return this.getters.tryGetSheet(e.sheetId)?this.checkElementsIncludeAllVisibleHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`:`InvalidSheetId`}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:let t={COL:Array(this.getters.getNumberCols(e.sheetId)).fill(!1),ROW:Array(this.getters.getNumberRows(e.sheetId)).fill(!1)};this.history.update(`hiddenHeaders`,e.sheetId,t);break;case`DUPLICATE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetIdTo,x(this.hiddenHeaders[e.sheetId]));break;case`DELETE_SHEET`:this.history.update(`hiddenHeaders`,e.sheetId,void 0);break;case`REMOVE_COLUMNS_ROWS`:{let t=[...this.hiddenHeaders[e.sheetId][e.dimension]];for(let n of[...e.elements].sort((e,t)=>t-e))t.splice(n,1);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t);break}case`ADD_COLUMNS_ROWS`:{let t=Ct(e.position,e.base),n=It([...this.hiddenHeaders[e.sheetId][e.dimension]],Array(e.quantity).fill(!1),t);this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,n);break}case`HIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!0);break;case`UNHIDE_COLUMNS_ROWS`:for(let t of e.elements)this.history.update(`hiddenHeaders`,e.sheetId,e.dimension,t,!1);break}}checkElementsIncludeAllVisibleHeaders(e,t,n){return Et(n,this.getAllVisibleHeaders(e,t))}isHeaderHiddenByUser(e,t,n){return t===`COL`?this.isColHiddenByUser(e,n):this.isRowHiddenByUser(e,n)}isRowHiddenByUser(e,t){return this.hiddenHeaders[e].ROW[t]||this.getters.isRowFolded(e,t)}isColHiddenByUser(e,t){return this.hiddenHeaders[e].COL[t]||this.getters.isColFolded(e,t)}getHiddenColsGroups(e){let t=[[]],n=this.hiddenHeaders[e].COL;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getHiddenRowsGroups(e){let t=[[]],n=this.hiddenHeaders[e].ROW;for(let e=0;e<n.length;e++)n[e]?t[t.length-1].push(e):t[t.length-1].length!==0&&t.push([]);return t[t.length-1].length===0&&t.pop(),t}getAllVisibleHeaders(e,t){let n=C(0,this.getters.getNumberHeaders(e,t)),r=[];return this.getters.getHeaderGroups(e,t).forEach(e=>{e.isFolded&&r.push(...C(e.start,e.end+1))}),n.filter(n=>!this.hiddenHeaders[e][t][n]&&!r.includes(n))}import(e){for(let t of e.sheets){this.hiddenHeaders[t.id]={COL:[],ROW:[]};for(let e=0;e<t.rowNumber;e++)this.hiddenHeaders[t.id].ROW[e]=!!t.rows[e]?.isHidden;for(let e=0;e<t.colNumber;e++)this.hiddenHeaders[t.id].COL[e]=!!t.cols[e]?.isHidden}}exportForExcel(e){this.exportData(e,!0)}export(e){this.exportData(e)}exportData(e,t=!1){for(let n of e.sheets){n.rows===void 0&&(n.rows={});for(let e=0;e<this.getters.getNumberRows(n.id);e++)(t||this.hiddenHeaders[n.id].ROW[e])&&(n.rows[e]===void 0&&(n.rows[e]={}),n.rows[e].isHidden||=this.hiddenHeaders[n.id].ROW[e]);n.cols===void 0&&(n.cols={});for(let e=0;e<this.getters.getNumberCols(n.id);e++)(t||this.hiddenHeaders[n.id].COL[e])&&(n.cols[e]===void 0&&(n.cols[e]={}),n.cols[e].isHidden||=this.hiddenHeaders[n.id].COL[e])}}},RI=class extends SI{static getters=[`getImage`,`getImagePath`,`getImageSize`];fileStore;images={};syncedImages=new Set;constructor(e){super(e),this.fileStore=e.external.fileStore}allowDispatch(e){switch(e.type){case`CREATE_IMAGE`:return this.getters.getFigure(e.sheetId,e.figureId)?`InvalidFigureId`:`Success`;default:return`Success`}}handle(e){switch(e.type){case`CREATE_IMAGE`:this.getters.getFigure(e.sheetId,e.figureId)||this.addFigure(e.figureId,e.sheetId,e.col,e.row,e.offset,e.size),this.history.update(`images`,e.sheetId,e.figureId,e.definition),this.syncedImages.add(e.definition.path);break;case`DUPLICATE_SHEET`:{let t=this.getters.getFigures(e.sheetId);for(let n of t)if(n.tag===`image`){let t=n.id.split(`??`).pop(),r=`${e.sheetIdTo}??${t}`,i=this.getImage(n.id);if(i){let t={width:n.width,height:n.height};this.dispatch(`CREATE_IMAGE`,{sheetId:e.sheetIdTo,figureId:r,offset:n.offset,col:n.col,row:n.row,size:t,definition:x(i)})}}break}case`DELETE_FIGURE`:this.history.update(`images`,e.sheetId,e.figureId,void 0);break;case`DELETE_SHEET`:this.history.update(`images`,e.sheetId,void 0);break}}getImage(e){for(let t of Object.values(this.images))if(t&&t[e])return t[e];throw Error(`There is no image with the given figureId: ${e}`)}getImagePath(e){return this.getImage(e).path}getImageSize(e){return this.getImage(e).size}addFigure(e,t,n,r,i,a){this.dispatch(`CREATE_FIGURE`,{sheetId:t,figureId:e,col:n,row:r,offset:i,size:a,tag:`image`})}import(e){for(let t of e.sheets){let e=(t.figures||[]).filter(e=>e.tag===`image`);for(let n of e)this.history.update(`images`,t.id,n.id,n.data),this.syncedImages.add(n.data.path)}}export(e){for(let t of e.sheets){let e=t.figures.filter(e=>e.tag===`image`);for(let n of e)n.data=this.images[t.id]?.[n.id]}}exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let t of e)if(t?.tag===`image`){let e=this.getImage(t.id);e&&n.push({...t,data:x(e)})}t.images=[...t.images,...n]}}},zI=class extends SI{static getters=[`isInMerge`,`isInSameMerge`,`isMergeHidden`,`getMainCellPosition`,`expandZone`,`doesIntersectMerge`,`doesColumnsHaveCommonMerges`,`doesRowsHaveCommonMerges`,`getMerges`,`getMerge`,`getMergesInZone`,`isSingleCellOrMerge`,`isMainCellPosition`];nextId=1;merges={};mergeCellMap={};allowDispatch(e){let t=`force`in e?!!e.force:!1;switch(e.type){case`ADD_MERGE`:return t?this.checkValidations(e,this.checkFrozenPanes):this.checkValidations(e,this.checkDestructiveMerge,this.checkOverlap,this.checkFrozenPanes);case`UPDATE_CELL`:return this.checkMergedContentUpdate(e);case`REMOVE_MERGE`:return this.checkMergeExists(e);default:return`Success`}}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DELETE_SHEET`:this.history.update(`merges`,e.sheetId,{}),this.history.update(`mergeCellMap`,e.sheetId,{});break;case`DUPLICATE_SHEET`:let t=this.merges[e.sheetId];if(!t)break;for(let n of Object.values(t).filter(w))this.addMerge(e.sheetIdTo,n.zone);break;case`ADD_MERGE`:for(let t of e.target)this.addMerge(e.sheetId,t);break;case`REMOVE_MERGE`:for(let t of e.target)this.removeMerge(e.sheetId,t);break}}adaptRanges(e){for(let t in this.merges)this.applyRangeChangeOnSheet(t,e)}getMerges(e){return Object.keys(this.merges[e]||{}).map(t=>this.getMergeById(e,parseInt(t,10))).filter(w)}getMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e],i=r?t in r&&r[t]?.[n]:void 0;return i?this.getMergeById(e,i):void 0}getMergesInZone(e,t){let n=this.mergeCellMap[e];if(!n)return[];let r=new Set;for(let e=t.left;e<=t.right;e++)for(let i=t.top;i<=t.bottom;i++){let t=n[e]?.[i];t&&r.add(t)}return Array.from(r).map(t=>this.getMergeById(e,t)).filter(w)}doesIntersectMerge(e,t){for(let n of this.getMerges(e))if(Nn(t,n))return!0;return!1}doesColumnsHaveCommonMerges(e,t,n){let r=this.getters.getSheet(e);for(let i=0;i<this.getters.getNumberRows(e);i++)if(this.isInSameMerge(r.id,t,i,n,i))return!0;return!1}doesRowsHaveCommonMerges(e,t,n){let r=this.getters.getSheet(e);for(let i=0;i<=this.getters.getNumberCols(e);i++)if(this.isInSameMerge(r.id,i,t,i,n))return!0;return!1}expandZone(e,t){let{left:n,right:r,top:i,bottom:a}=t,o={left:n,right:r,top:i,bottom:a};for(let t in this.merges[e]){let n=this.getMergeById(e,parseInt(t));n&&Nn(n,o)&&(o=kn(n,o))}return Mn(o,t)?o:this.expandZone(e,o)}isInSameMerge(e,t,n,r,i){let a=this.getMerge({sheetId:e,col:t,row:n}),o=this.getMerge({sheetId:e,col:r,row:i});return!a||!o?!1:Mn(a,o)}isInMerge({sheetId:e,col:t,row:n}){let r=this.mergeCellMap[e];return r?t in r&&!!r[t]?.[n]:!1}getMainCellPosition(e){let t=this.getMerge(e);return t?{sheetId:e.sheetId,col:t.left,row:t.top}:e}isMergeHidden(e,t){let n=this.getters.getHiddenColsGroups(e),r=this.getters.getHiddenRowsGroups(e);for(let e of n)if(t.left>=e[0]&&t.right<=e[e.length-1])return!0;for(let e of r)if(t.top>=e[0]&&t.bottom<=e[e.length-1])return!0;return!1}isSingleCellOrMerge(e,t){let n=this.getMerge({sheetId:e,col:t.left,row:t.top});if(n)return Mn(t,n);let{numberOfCols:r,numberOfRows:i}=Ln(t);return r===1&&i===1}isMainCellPosition(e){return T(this.getMainCellPosition(e),e)}isMergeDestructive(e,t){let{left:n,right:r,top:i,bottom:a}=t;r=S(r,0,this.getters.getNumberCols(e)-1),a=S(a,0,this.getters.getNumberRows(e)-1);for(let t=i;t<=a;t++)for(let a=n;a<=r;a++)if(a!==n||t!==i){let n=this.getters.getCell({sheetId:e,col:a,row:t});if(n&&(n.isFormula||n.content!==``))return!0}return!1}getMergeById(e,t){let n=this.merges[e]?.[t];return n===void 0?void 0:VI(t,n)}checkDestructiveMerge({sheetId:e,target:t}){return this.getters.tryGetSheet(e)&&t.some(t=>this.isMergeDestructive(e,t))?`MergeIsDestructive`:`Success`}checkOverlap({target:e}){for(let t of e)for(let n of e)if(t!==n&&Nn(t,n))return`MergeOverlap`;return`Success`}checkFrozenPanes({sheetId:e,target:t}){if(!this.getters.tryGetSheet(e))return`Success`;let{xSplit:n,ySplit:r}=this.getters.getPaneDivisions(e);return Qn(t,n,r)?`FrozenPaneOverlap`:`Success`}checkMergedContentUpdate(e){let{col:t,row:n,content:r}=e;if(r===void 0)return`Success`;let{col:i,row:a}=this.getMainCellPosition(e);return i===t&&a===n?`Success`:`CellIsMerged`}checkMergeExists(e){let{sheetId:t,target:n}=e;for(let e of n){let{left:n,top:r}=e,i=this.getMerge({sheetId:t,col:n,row:r});if(i===void 0||!Mn(e,i))return`InvalidTarget`}return`Success`}addMerge(e,t){let{left:n,right:r,top:i,bottom:a}=t;if(r=S(r,0,this.getters.getNumberCols(e)-1),a=S(a,0,this.getters.getNumberRows(e)-1),E(n,i)===E(r,a))return;let o=this.getters.getCell({sheetId:e,col:n,row:i}),s=this.nextId++;this.history.update(`merges`,e,s,this.getters.getRangeFromSheetXC(e,wn({left:n,top:i,right:r,bottom:a})));let c=new Set;for(let t=i;t<=a;t++)for(let a=n;a<=r;a++){(a!==n||t!==i)&&this.dispatch(`UPDATE_CELL`,{sheetId:e,col:a,row:t,style:o?o.style:null,content:``});let r=this.getMerge({sheetId:e,col:a,row:t});r&&c.add(r.id),this.history.update(`mergeCellMap`,e,a,t,s)}for(let t of c){let{top:n,bottom:r,left:i,right:a}=this.getMergeById(e,t);for(let t=n;t<=r;t++)for(let n=i;n<=a;n++){let r={sheetId:e,col:n,row:t},i=this.getMerge(r);(!i||i.id!==s)&&(this.history.update(`mergeCellMap`,e,n,t,void 0),this.dispatch(`CLEAR_CELL`,r))}this.history.update(`merges`,e,t,void 0)}}removeMerge(e,t){let{left:n,top:r,bottom:i,right:a}=t,o=this.getMerge({sheetId:e,col:n,row:r});if(!(o===void 0||!Mn(t,o))){this.history.update(`merges`,e,o.id,void 0);for(let t=r;t<=i;t++)for(let r=n;r<=a;r++)this.history.update(`mergeCellMap`,e,r,t,void 0)}}applyRangeChangeOnSheet(e,{applyChange:t}){let n=Object.entries(this.merges[e]||{});for(let[r,i]of n)if(i){let n=i.zone,a=t(i);switch(a.changeType){case`NONE`:break;case`REMOVE`:this.removeMerge(e,n);break;default:let{numberOfCols:t,numberOfRows:i}=Ln(a.range.zone);t===1&&i===1?this.removeMerge(e,n):this.history.update(`merges`,e,parseInt(r,10),a.range);break}}this.history.update(`mergeCellMap`,e,{});for(let t of this.getMerges(e))for(let{col:n,row:r}of Bn(t))this.history.update(`mergeCellMap`,e,n,r,t.id)}import(e){let t=e.sheets||[];for(let e of t)this.history.update(`merges`,e.id,{}),this.history.update(`mergeCellMap`,e.id,{}),e.merges&&this.importMerges(e.id,e.merges)}importMerges(e,t){for(let n of t)this.addMerge(e,yn(n))}export(e){for(let t of e.sheets){let e=this.merges[t.id];e&&t.merges.push(...BI(e))}}exportForExcel(e){this.export(e)}};function BI(e){return Object.entries(e).map(([e,t])=>t?VI(parseInt(e,10),t):void 0).filter(w).map(e=>E(e.left,e.top)+`:`+E(e.right,e.bottom))}function VI(e,t){return{...t.zone,id:e}}let HI=/^[\p{L}\p{N}_.]+$/u;var UI=class extends SI{static getters=[`getNamedRange`,`getNamedRangeFromZone`,`getNamedRanges`];namedRanges=[];adaptRanges({applyChange:e}){let t=[],n=!1;for(let r of this.namedRanges){let i=e(r.range);switch(i.changeType){case`REMOVE`:n=!0;break;case`RESIZE`:case`MOVE`:case`CHANGE`:n=!0,t.push({...r,range:i.range});break;case`NONE`:t.push(r)}}n&&this.history.update(`namedRanges`,t)}allowDispatch(e){switch(e.type){case`CREATE_NAMED_RANGE`:return this.checkValidNewNamedRangeName(e.name);case`UPDATE_NAMED_RANGE`:return this.checkValidations(e,()=>this.checkNamedRangeExists(e.oldRangeName),()=>e.newRangeName===e.oldRangeName?`Success`:this.checkValidNewNamedRangeName(e.newRangeName));case`DELETE_NAMED_RANGE`:return this.checkNamedRangeExists(e.name)}return`Success`}handle(e){switch(e.type){case`CREATE_NAMED_RANGE`:{let t=this.getters.getRangeFromRangeData(e.ranges[0]),n=[...this.namedRanges,{name:e.name,range:t}];this.history.update(`namedRanges`,n);break}case`UPDATE_NAMED_RANGE`:{let t=this.getNamedRangeIndex(e.oldRangeName);if(t!==-1){let n=this.getters.getRangeFromRangeData(e.ranges[0]);this.history.update(`namedRanges`,t,{name:e.newRangeName,range:n})}break}case`DELETE_NAMED_RANGE`:{let t=this.getNamedRangeIndex(e.name);if(t!==-1){let e=[...this.namedRanges];e.splice(t,1),this.history.update(`namedRanges`,e)}break}}}getNamedRange(e){return this.namedRanges[this.getNamedRangeIndex(e)]}getNamedRangeFromZone(e,t){for(let n of this.namedRanges){let r=n.range;if(r.sheetId===e&&T(r.unboundedZone,t))return n}}getNamedRanges(){return this.namedRanges}getNamedRangeIndex(e){return this.namedRanges.findIndex(t=>t&&t.name.toLowerCase()===e.toLowerCase())}import(e){for(let t in e.namedRanges||{})this.namedRanges.push({name:t,range:this.getters.getRangeFromSheetXC(void 0,e.namedRanges[t])})}export(e){e.namedRanges={};for(let t of this.namedRanges){let n=this.getters.getRangeString(t.range);e.namedRanges[t.name]=n}}checkValidNewNamedRangeName(e){return this.getNamedRange(e)?`NamedRangeNameAlreadyExists`:!HI.test(e)||Pa(e,V)||[`TRUE`,`FALSE`].includes(e.toUpperCase())?`NamedRangeInvalidName`:Uo.test(e)?`NamedRangeNameLooksLikeCellReference`:`Success`}checkNamedRangeExists(e){return this.getNamedRange(e)?`Success`:`NamedRangeNotFound`}},WI=class extends SI{static getters=[`getPivotCoreDefinition`,`getPivotDisplayName`,`getPivotId`,`getPivotFormulaId`,`getPivotIds`,`getMeasureCompiledFormula`,`getPivotName`,`isExistingPivot`,`getMeasureFullDependencies`];nextFormulaId=1;pivots={};formulaIds={};compiledMeasureFormulas={};allowDispatch(e){switch(e.type){case`ADD_PIVOT`:return e.pivotId in this.pivots?`PivotIdTaken`:this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid);case`UPDATE_PIVOT`:return e.pivotId in this.pivots?T(e.pivot,this.pivots[e.pivotId]?.definition)?`NoChanges`:e.pivot.name===``?`EmptyName`:this.checkValidations(e.pivot,this.checkDuplicatedMeasureIds,this.checkSortedColumnInMeasures,this.checkCustomFieldsAreValid):`PivotIdNotFound`;case`RENAME_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;if(e.name===``)return`EmptyName`;break;case`REMOVE_PIVOT`:case`DUPLICATE_PIVOT`:case`INSERT_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`;break;case`DUPLICATE_PIVOT`:if(!(e.pivotId in this.pivots))return`PivotIdNotFound`}return`Success`}handle(e){switch(e.type){case`ADD_PIVOT`:{let{pivotId:t,pivot:n}=e;this.addPivot(t,n);break}case`INSERT_PIVOT`:{let{sheetId:t,col:n,row:r,pivotId:i,table:a}=e,o={sheetId:t,col:n,row:r},{cols:s,rows:c,measures:l,fieldsType:u}=a,d=new jj(s,c,l,u||{}),f=this.getPivotFormulaId(i);this.insertPivot(o,f,d);break}case`RENAME_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,`name`,e.name);break;case`REMOVE_PIVOT`:{let t={...this.pivots};delete t[e.pivotId];let n=this.getPivotFormulaId(e.pivotId);this.history.update(`formulaIds`,n,void 0),this.history.update(`pivots`,t);break}case`DUPLICATE_PIVOT`:{let{pivotId:t,newPivotId:n}=e,r=x(this.getPivotCore(t).definition);r.name=e.duplicatedPivotName??r.name+` (copy)`,this.addPivot(n,r);break}case`UPDATE_PIVOT`:this.history.update(`pivots`,e.pivotId,`definition`,x(e.pivot)),this.compileCalculatedMeasures(e.pivotId,e.pivot.measures);break;case`CREATE_NAMED_RANGE`:case`UPDATE_NAMED_RANGE`:case`DELETE_NAMED_RANGE`:for(let e in this.pivots){let t=this.pivots[e];t&&this.compileCalculatedMeasures(e,t.definition.measures)}}}adaptRanges(e){let{applyChange:t,adaptFormulaString:n}=e;for(let e in this.pivots){let n=x(this.pivots[e]?.definition);if(!n)continue;let r=Uj.get(n.type)?.adaptRanges?.(this.getters,n,t);r&&!T(n,r)&&this.history.update(`pivots`,e,`definition`,r)}for(let r in this.compiledMeasureFormulas)for(let i in this.compiledMeasureFormulas[r]){let a=this.pivots[r]?.definition.measures.find(e=>e.id===i);if(!a||!a.computedBy)continue;let o=a.computedBy.sheetId,{formula:s,dependencies:c}=this.compiledMeasureFormulas[r][i],l=e.adaptCompiledFormula(s);l!==s&&this.history.update(`compiledMeasureFormulas`,r,i,`formula`,l),this.history.update(`compiledMeasureFormulas`,r,a.id,`dependencies`,c.map(e=>t(e).range));let u=a.computedBy.formula,d=n(o,u);d!==u&&this.replaceMeasureFormula(r,a,d)}}getPivotDisplayName(e){return`(#${this.getPivotFormulaId(e)}) ${this.getPivotName(e)}`}getPivotName(e){return this.getPivotCore(e).definition.name}getPivotCoreDefinition(e){return this.getPivotCore(e).definition}getPivotId(e){return this.formulaIds[e]}getPivotFormulaId(e){return this.getPivotCore(e).formulaId}getPivotIds(){return Object.keys(this.pivots)}isExistingPivot(e){return e in this.pivots}getMeasureCompiledFormula(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].formula}getMeasureFullDependencies(e,t){if(!t.computedBy)throw Error(`Measure ${t.fieldName} is not computed by formula`);return this.compiledMeasureFormulas[e][t.id].dependencies}addPivot(e,t,n=this.nextFormulaId.toString()){this.history.update(`pivots`,e,{definition:x(t),formulaId:n}),this.compileCalculatedMeasures(e,t.measures),this.history.update(`formulaIds`,n,e),this.history.update(`nextFormulaId`,this.nextFormulaId+1)}compileCalculatedMeasures(e,t){for(let n of t)if(n.computedBy){let t=Rc.Compile(n.computedBy.formula,n.computedBy.sheetId,this.getters);this.history.update(`compiledMeasureFormulas`,e,n.id,`formula`,t)}for(let n of t)if(n.computedBy){let t=this.computeMeasureFullDependencies(e,n);this.history.update(`compiledMeasureFormulas`,e,n.id,`dependencies`,t)}}computeMeasureFullDependencies(e,t,n=new Set){let r=[],i=this.getPivotCoreDefinition(e),a=this.getMeasureCompiledFormula(e,t);n.add(t.id);for(let o of a.symbols){let a=i.measures.find(e=>tt(e.id)===o&&t.id!==e.id);!a||n.has(a.id)||!a.computedBy||r.push(...this.computeMeasureFullDependencies(e,a,n))}return r.push(...a.rangeDependencies.filter(e=>!e.invalidXc)),r.push(...a.getNamedRangesInFormula(this.getters).map(e=>e.range)),r}insertPivot(e,t,n){this.resizeSheet(e.sheetId,e,n);let r=n.getPivotCells();for(let n=0;n<r.length;n++)for(let i=0;i<r[n].length;i++){let a=r[n][i];this.dispatch(`UPDATE_CELL`,{sheetId:e.sheetId,col:e.col+n,row:e.row+i,content:Eg(t,a)})}}resizeSheet(e,{col:t,row:n},r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:s-l,position:`after`})}getPivotCore(e){let t=this.pivots[e];if(!t)throw Error(`Pivot with id ${e} not found`);return t}replaceMeasureFormula(e,t,n){let r=this.pivots[e];if(!r)return;let i=r.definition.measures.indexOf(t);this.history.update(`pivots`,e,`definition`,`measures`,i,`computedBy`,{formula:n,sheetId:t.computedBy.sheetId})}checkSortedColumnInMeasures(e){let t=e.measures.map(e=>e.id);return e.sortedColumn&&!t.includes(e.sortedColumn.measure)?`InvalidDefinition`:`Success`}checkDuplicatedMeasureIds(e){let t=new Set(e.measures.map(e=>e.id));return e.measures.length===t.size?`Success`:`InvalidDefinition`}checkCustomFieldsAreValid(e){for(let t in e.customFields){let n=e.customFields[t],r=new Set,i=new Set,a=!1;for(let e of n.groups){if(!e.name||i.has(e.name)||e.values.some(e=>r.has(e))||e.isOtherGroup&&a)return`InvalidPivotCustomField`;e.values.forEach(e=>r.add(e)),i.add(e.name),a||=!!e.isOtherGroup}}return`Success`}import(e){if(e.pivots)for(let[t,n]of Object.entries(e.pivots))this.addPivot(t,n,n.formulaId);this.history.update(`nextFormulaId`,e.pivotNextId||yg(this.pivots)+1)}export(e){e.pivots={};for(let t in this.pivots)e.pivots[t]={...this.getPivotCoreDefinition(t),formulaId:this.getPivotFormulaId(t)};e.pivotNextId=this.nextFormulaId}},GI=class extends SI{static getters=[`getLocale`];locale=V;allowDispatch(e){switch(e.type){case`UPDATE_LOCALE`:return Wy(e.locale)?`Success`:`InvalidLocale`}return`Success`}handle(e){switch(e.type){case`UPDATE_LOCALE`:let t=this.locale,n=e.locale;this.history.update(`locale`,n),this.changeCellsDateFormatWithLocale(t,n);break}}getLocale(){return this.locale}changeCellsDateFormatWithLocale(e,t){for(let n of this.getters.getSheetIds())for(let r of this.getters.getCells(n)){let n;if(r.format===e.dateFormat&&(n=t.dateFormat),r.format===e.timeFormat&&(n=t.timeFormat),r.format===sb(e)&&(n=sb(t)),n){let{col:e,row:t,sheetId:i}=this.getters.getCellPosition(r.id);this.dispatch(`UPDATE_CELL`,{col:e,row:t,sheetId:i,format:n})}}}import(e){this.locale=e.settings?.locale??V}export(e){e.settings={locale:this.locale}}},KI=class extends SI{static getters=`getSheetName.tryGetSheetName.getSheet.tryGetSheet.getSheetIdByName.getSheetIds.getVisibleSheetIds.isSheetVisible.doesHeaderExist.doesHeadersExist.getCell.getCellPosition.getColsZone.getRowCellIds.getRowsZone.getNumberCols.getNumberRows.getNumberHeaders.getGridLinesVisibility.getNextSheetName.getSheetSize.getSheetZone.getPaneDivisions.checkZonesExistInSheet.getCommandZones.getUnboundedZone.checkElementsIncludeAllNonFrozenHeaders.getDuplicateSheetName.tryGetCellPosition.isSheetLocked`.split(`.`);sheetIdsMapName={};orderedSheetIds=[];sheets={};cellPosition={};allowDispatch(e){let t=this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e);if(t!==`Success`)return t;let n=!1;switch(e.type){case`CREATE_SHEET`:e.name===void 0&&(n=!0);break;case`DELETE_SHEET`:case`ADD_COLUMNS_ROWS`:case`REMOVE_COLUMNS_ROWS`:case`MOVE_RANGES`:e.sheetName===void 0&&(n=!0);break}switch(n&&console.warn(`Deprecation Warning: Sheet name is missing in the command %s payload.`,e.type),e.type){case`HIDE_SHEET`:return this.getVisibleSheetIds().length===1?`NotEnoughSheets`:`Success`;case`CREATE_SHEET`:return this.checkValidations(e,this.createSheetHasName,this.checkSheetName,this.checkSheetPosition);case`DUPLICATE_SHEET`:return this.sheets[e.sheetIdTo]?`DuplicatedSheetId`:this.orderedSheetIds.map(this.getSheetName.bind(this)).includes(e.sheetNameTo)?`DuplicatedSheetName`:`Success`;case`MOVE_SHEET`:try{let t=this.orderedSheetIds.findIndex(t=>t===e.sheetId);return this.findIndexOfTargetSheet(t,e.delta),`Success`}catch{return`WrongSheetMove`}case`RENAME_SHEET`:return this.isRenameAllowed(e);case`COLOR_SHEET`:return!e.color||Pr(e.color)?`Success`:`InvalidColor`;case`DELETE_SHEET`:return this.getVisibleSheetIds().length>1?`Success`:`NotEnoughSheets`;case`ADD_COLUMNS_ROWS`:return this.doesHeaderExist(e.sheetId,e.dimension,e.base)?e.quantity<=0?`InvalidQuantity`:`Success`:`InvalidHeaderIndex`;case`REMOVE_COLUMNS_ROWS`:{let t=Ht(e.elements),n=Vt(e.elements);return t<0||!this.doesHeaderExist(e.sheetId,e.dimension,n)?`InvalidHeaderIndex`:this.checkElementsIncludeAllNonFrozenHeaders(e.sheetId,e.dimension,e.elements)?`NotEnoughElements`:`Success`}case`FREEZE_ROWS`:return this.checkValidations(e,this.checkRowFreezeQuantity,this.checkRowFreezeOverlapMerge);case`FREEZE_COLUMNS`:return this.checkValidations(e,this.checkColFreezeQuantity,this.checkColFreezeOverlapMerge);default:return`Success`}}handle(e){switch(e.type){case`SET_GRID_LINES_VISIBILITY`:this.setGridLinesVisibility(e.sheetId,e.areGridLinesVisible);break;case`CREATE_SHEET`:let t=this.createSheet(e.sheetId,e.name||this.getNextSheetName(),e.cols||26,e.rows||100,e.position);this.history.update(`sheetIdsMapName`,bc(t.name),t.id);break;case`MOVE_SHEET`:this.moveSheet(e.sheetId,e.delta);break;case`RENAME_SHEET`:this.renameSheet(this.sheets[e.sheetId],e.newName);break;case`COLOR_SHEET`:this.history.update(`sheets`,e.sheetId,`color`,e.color);break;case`HIDE_SHEET`:this.hideSheet(e.sheetId);break;case`SHOW_SHEET`:this.showSheet(e.sheetId);break;case`DUPLICATE_SHEET`:this.duplicateSheet(e.sheetId,e.sheetIdTo,e.sheetNameTo);break;case`DELETE_SHEET`:this.deleteSheet(this.sheets[e.sheetId]);break;case`REMOVE_COLUMNS_ROWS`:e.dimension===`COL`?this.removeColumns(this.sheets[e.sheetId],[...e.elements]):this.removeRows(this.sheets[e.sheetId],[...e.elements]);break;case`ADD_COLUMNS_ROWS`:e.dimension===`COL`?this.addColumns(this.sheets[e.sheetId],e.base,e.position,e.quantity):this.addRows(this.sheets[e.sheetId],e.base,e.position,e.quantity);break;case`UPDATE_CELL_POSITION`:this.updateCellPosition(e);break;case`FREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,e.quantity,`COL`);break;case`FREEZE_ROWS`:this.setPaneDivisions(e.sheetId,e.quantity,`ROW`);break;case`UNFREEZE_ROWS`:this.setPaneDivisions(e.sheetId,0,`ROW`);break;case`UNFREEZE_COLUMNS`:this.setPaneDivisions(e.sheetId,0,`COL`);break;case`UNFREEZE_COLUMNS_ROWS`:this.setPaneDivisions(e.sheetId,0,`COL`),this.setPaneDivisions(e.sheetId,0,`ROW`);break;case`LOCK_SHEET`:this.history.update(`sheets`,e.sheetId,`isLocked`,!0);break;case`UNLOCK_SHEET`:this.history.update(`sheets`,e.sheetId,`isLocked`,!1);break}}import(e){for(let t of e.sheets)this.sheetIdsMapName[bc(t.name)]=t.id;for(let t of e.sheets){let e=t.name||`Sheet`+(Object.keys(this.sheets).length+1),{colNumber:n,rowNumber:r}=this.getImportedSheetSize(t),i={id:t.id,name:e,numberOfCols:n,rows:hc(r),areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,panes:{xSplit:t.panes?.xSplit||0,ySplit:t.panes?.ySplit||0},color:t.color,isLocked:t.isLocked};this.orderedSheetIds.push(i.id),this.sheets[i.id]=i}}exportSheets(e){e.sheets=this.orderedSheetIds.filter(w).map(e=>{let t=this.sheets[e],n={id:t.id,name:t.name,colNumber:t.numberOfCols,rowNumber:this.getters.getNumberRows(t.id),rows:{},cols:{},merges:[],cells:{},styles:{},formats:{},borders:{},conditionalFormats:[],dataValidationRules:[],figures:[],tables:[],areGridLinesVisible:t.areGridLinesVisible===void 0?!0:t.areGridLinesVisible,isVisible:t.isVisible,isLocked:t.isLocked,color:t.color};return(t.panes.xSplit||t.panes.ySplit)&&(n.panes=t.panes),n})}export(e){this.exportSheets(e)}exportForExcel(e){this.exportSheets(e)}getGridLinesVisibility(e){return this.getSheet(e).areGridLinesVisible}isSheetLocked(e){return this.tryGetSheet(e)?.isLocked||!1}tryGetSheet(e){return this.sheets[e]}getSheet(e){let t=this.sheets[e];if(!t)throw Error(`Sheet ${e} not found.`);return t}isSheetVisible(e){return this.getSheet(e).isVisible}getSheetName(e){return this.getSheet(e).name}tryGetSheetName(e){return this.tryGetSheet(e)?.name}getSheetIdByName(e){if(e)return this.sheetIdsMapName[bc(e)]}getSheetIds(){return this.orderedSheetIds}getVisibleSheetIds(){return this.orderedSheetIds.filter(this.isSheetVisible.bind(this))}doesHeaderExist(e,t,n){return t===`COL`?n>=0&&n<this.getNumberCols(e):n>=0&&n<this.getNumberRows(e)}doesHeadersExist(e,t,n){return n.every(n=>this.doesHeaderExist(e,t,n))}getCell({sheetId:e,col:t,row:n}){let r=this.tryGetSheet(e)?.rows[n]?.cells[t];if(r!==void 0)return this.getters.getCellById(r)}getColsZone(e,t,n){return{top:0,bottom:this.getNumberRows(e)-1,left:t,right:n}}getRowCellIds(e,t){return Object.values(this.getSheet(e).rows[t]?.cells).filter(w)}getRowsZone(e,t,n){return{top:t,bottom:n,left:0,right:this.getSheet(e).numberOfCols-1}}getCellPosition(e){let t=this.cellPosition[e];if(!t)throw Error(`asking for a cell position that doesn't exist, cell id: ${e}`);return t}tryGetCellPosition(e){return this.cellPosition[e]}getNumberCols(e){return this.getSheet(e).numberOfCols}getNumberRows(e){return this.getSheet(e).rows.length}getNumberHeaders(e,t){return t===`COL`?this.getNumberCols(e):this.getNumberRows(e)}getNextSheetName(e=`Sheet`){return vc(this.orderedSheetIds.map(this.getSheetName.bind(this)),e)}getSheetSize(e){return{numberOfRows:this.getNumberRows(e),numberOfCols:this.getNumberCols(e)}}getSheetZone(e){return{top:0,left:0,bottom:this.getNumberRows(e)-1,right:this.getNumberCols(e)-1}}getUnboundedZone(e,t){if(t.bottom===void 0||t.right===void 0)return t;let n=t.left===0&&t.right===this.getNumberCols(e)-1,r=t.top===0&&t.bottom===this.getNumberRows(e)-1;return{...t,bottom:r?void 0:t.bottom,right:n&&!r?void 0:t.right}}getPaneDivisions(e){return this.getSheet(e).panes}setPaneDivisions(e,t,n){let r={...this.getPaneDivisions(e)};n===`COL`?r.xSplit=t:n===`ROW`&&(r.ySplit=t),this.history.update(`sheets`,e,`panes`,r)}checkElementsIncludeAllNonFrozenHeaders(e,t,n){let r=this.getters.getPaneDivisions(e),i=t===`ROW`?r.ySplit:r.xSplit,a=this.getters.getNumberHeaders(e,t);return i?Et(n,C(i,a)):!1}getCommandZones(e){let t=[];return`zone`in e&&t.push(e.zone),`target`in e&&t.push(...e.target),`ranges`in e&&t.push(...e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone)),`col`in e&&e.col!==void 0&&`row`in e&&e.row!==void 0&&t.push({top:e.row,left:e.col,bottom:e.row,right:e.col}),t}checkZonesExistInSheet(e,t){if(!t.every(Sn))return`InvalidRange`;if(t.length){let n=this.getSheetZone(e);return t.every(e=>In(e,n))?`Success`:`TargetOutOfSheet`}return`Success`}updateCellPosition(e){let{sheetId:t,cellId:n,col:r,row:i}=e;n?this.setNewPosition(n,t,r,i):this.clearPosition(t,r,i)}setNewPosition(e,t,n,r){let i=this.cellPosition[e];i&&this.clearPosition(t,i.col,i.row),this.history.update(`cellPosition`,e,{row:r,col:n,sheetId:t}),this.history.update(`sheets`,t,`rows`,r,`cells`,n,e)}clearPosition(e,t,n){let r=this.sheets[e]?.rows[n].cells[t];r&&(this.history.update(`cellPosition`,r,void 0),this.history.update(`sheets`,e,`rows`,n,`cells`,t,void 0))}setGridLinesVisibility(e,t){this.history.update(`sheets`,e,`areGridLinesVisible`,t)}createSheet(e,t,n,r,i){let a={id:e,name:t,numberOfCols:n,rows:hc(r),areGridLinesVisible:!0,isVisible:!0,panes:{xSplit:0,ySplit:0},isLocked:!1},o=this.orderedSheetIds.slice();o.splice(i,0,a.id);let s=this.sheets;return this.history.update(`orderedSheetIds`,o),this.history.update(`sheets`,Object.assign({},s,{[a.id]:a})),a}moveSheet(e,t){let n=this.orderedSheetIds.slice(),r=n.findIndex(t=>t===e),i=n.splice(r,1),a=this.findIndexOfTargetSheet(r,t);n.splice(a,0,i[0]),this.history.update(`orderedSheetIds`,n)}findIndexOfTargetSheet(e,t){for(;t!==0&&0<=e&&e<=this.orderedSheetIds.length;)t>0?(e++,this.isSheetVisible(this.orderedSheetIds[e])&&t--):t<0&&(e--,this.isSheetVisible(this.orderedSheetIds[e])&&t++);if(t===0)return e;throw Error(`There is not enough visible sheets`)}createSheetHasName(e){return e.name!==void 0&&!e.name.trim()?`MissingSheetName`:`Success`}checkSheetName(e){let t=this.getters.tryGetSheetName(e.sheetId),n=e.type===`RENAME_SHEET`?e.newName:e.name;if(t!==void 0&&n===t)return`UnchangedSheetName`;let{orderedSheetIds:r,sheets:i}=this,a=n&&n.trim().toLowerCase();return r.find(t=>xc(i[t]?.name,a)&&t!==e.sheetId)?`DuplicatedSheetName`:Fe.test(a)?`ForbiddenCharactersInSheetName`:`Success`}checkSheetPosition(e){let{orderedSheetIds:t}=this;return e.position>t.length||e.position<0?`WrongSheetPosition`:`Success`}checkRowFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberRows(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkColFreezeQuantity(e){return e.quantity>=1&&e.quantity<this.getNumberCols(e.sheetId)?`Success`:`InvalidFreezeQuantity`}checkRowFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.top<e.quantity&&e.quantity<=n.bottom)return`MergeOverlap`;return`Success`}checkColFreezeOverlapMerge(e){let t=this.getters.getMerges(e.sheetId);for(let n of t)if(n.left<e.quantity&&e.quantity<=n.right)return`MergeOverlap`;return`Success`}isRenameAllowed(e){return e.newName&&e.newName.trim().toLowerCase()?this.checkSheetName(e):`MissingSheetName`}renameSheet(e,t){let n=e.name;this.history.update(`sheets`,e.id,`name`,t.trim());let r=Object.assign({},this.sheetIdsMapName);delete r[bc(n)],r[bc(t)]=e.id,this.history.update(`sheetIdsMapName`,r)}hideSheet(e){this.history.update(`sheets`,e,`isVisible`,!1)}showSheet(e){this.history.update(`sheets`,e,`isVisible`,!0)}duplicateSheet(e,t,n){let r=x(this.getSheet(e));r.id=t,r.name=n,r.isLocked=!1;for(let e=0;e<=r.numberOfCols;e++)for(let t=0;t<=r.rows.length;t++)r.rows[t]&&(r.rows[t].cells[e]=void 0);let i=this.orderedSheetIds.slice(),a=i.indexOf(e);i.splice(a+1,0,r.id),this.history.update(`orderedSheetIds`,i),this.history.update(`sheets`,Object.assign({},this.sheets,{[r.id]:r}));for(let t of Object.values(this.getters.getCells(e))){let{col:e,row:n}=this.getCellPosition(t.id);this.dispatch(`UPDATE_CELL`,{sheetId:r.id,col:e,row:n,content:t.isFormula?t.compiledFormula.toFormulaString(this.getters):t.content,format:t.format,style:t.style})}let o=Object.assign({},this.sheetIdsMapName);o[bc(r.name)]=r.id,this.history.update(`sheetIdsMapName`,o)}getDuplicateSheetName(e){return yc(e,this.orderedSheetIds.map(this.getSheetName.bind(this)))}deleteSheet(e){let t=e.name,n=Object.assign({},this.sheets);delete n[e.id],this.history.update(`sheets`,n);let r=this.orderedSheetIds.slice(),i=r.indexOf(e.id);r.splice(i,1),this.history.update(`orderedSheetIds`,r);let a=Object.assign({},this.sheetIdsMapName);delete a[bc(t)],this.history.update(`sheetIdsMapName`,a)}removeColumns(e,t){t.sort((e,t)=>t-e);for(let n of t)this.moveCellOnColumnsDeletion(e,n);let n=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,n-t.length);let r=t.filter(t=>t<e.panes.xSplit).length;r&&this.setPaneDivisions(e.id,e.panes.xSplit-r,`COL`)}removeRows(e,t){t.sort((e,t)=>t-e);for(let n of rt(t)){let t=n[n.length-1],r=n[0];this.moveCellOnRowsDeletion(e,t,r),this.updateRowsStructureOnDeletion(e,t,r)}let n=t.filter(t=>t<e.panes.ySplit).length;n&&this.setPaneDivisions(e.id,e.panes.ySplit-n,`ROW`)}addColumns(e,t,n,r){let i=n===`before`?t:t+1;this.moveCellsOnAddition(e,i,r,`columns`);let a=this.sheets[e.id].numberOfCols;this.history.update(`sheets`,e.id,`numberOfCols`,a+r),i<e.panes.xSplit&&this.setPaneDivisions(e.id,e.panes.xSplit+r,`COL`)}addRows(e,t,n,r){let i=n===`before`?t:t+1;this.addEmptyRows(e,r),this.moveCellsOnAddition(e,i,r,`rows`),i<e.panes.ySplit&&this.setPaneDivisions(e.id,e.panes.ySplit+r,`ROW`)}moveCellOnColumnsDeletion(e,t){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:t,top:0,right:t,bottom:e.rows.length-1}]});for(let n=0;n<e.rows.length;n++){let r=e.rows[n];for(let i in r.cells){let a=Number(i),o=r.cells[i];o&&a>t&&this.setNewPosition(o,e.id,a-1,n)}}}moveCellsOnAddition(e,t,n,r){let i=[];for(let a=0;a<e.rows.length;a++){let o=e.rows[a];if(r!==`rows`||a>=t)for(let s in o.cells){let c=Number(s),l=o.cells[s];l&&(r===`rows`||c>=t)&&i.push({sheetId:e.id,cellId:l,col:c+(r===`columns`?n:0),row:a+(r===`rows`?n:0),type:`UPDATE_CELL_POSITION`})}}for(let e of i.reverse())this.updateCellPosition(e)}moveCellOnRowsDeletion(e,t,n){this.dispatch(`CLEAR_CELLS`,{sheetId:e.id,target:[{left:0,top:t,right:this.getters.getNumberCols(e.id),bottom:n}]});let r=n-t+1;for(let t=0;t<e.rows.length;t++){let i=e.rows[t];if(t>n)for(let n in i.cells){let a=Number(n),o=i.cells[n];o&&this.setNewPosition(o,e.id,a,t-r)}}}updateRowsStructureOnDeletion(e,t,n){let r=[],i=e.rows.map(e=>e.cells).reverse();for(let a in e.rows){let e=Number(a);e>=t&&e<=n||r.push({cells:i.pop()})}this.history.update(`sheets`,e.id,`rows`,r)}addEmptyRows(e,t){let n=e.rows.slice();for(let e=0;e<t;e++)n.push({cells:{}});this.history.update(`sheets`,e.id,`rows`,n)}getImportedSheetSize(e){let t=Object.keys(e.cells).map(yn),n=e.rowNumber,r=e.colNumber;for(let{right:e,bottom:i}of t)n=Math.max(n,i+1),r=Math.max(r,e+1);return{rowNumber:n,colNumber:r}}checkSheetExists(e){return e.type!==`CREATE_SHEET`&&`sheetId`in e&&this.sheets[e.sheetId]===void 0?`InvalidSheetId`:e.type===`CREATE_SHEET`&&this.sheets[e.sheetId]!==void 0?`DuplicatedSheetId`:`Success`}checkZonesAreInSheet(e){return fu(e)&&e.ranges.length===0?`EmptyRange`:`sheetId`in e?`ranges`in e&&e.ranges.some(e=>e._sheetId!==``&&!this.getters.tryGetSheet(e._sheetId))?`InvalidSheetId`:du(e)&&e.target.length===0?`EmptyTarget`:this.checkZonesExistInSheet(e.sheetId,this.getCommandZones(e)):`Success`}},qI=class extends SI{allowDispatch(e){switch(e.type){case`ADD_PIVOT`:case`UPDATE_PIVOT`:let t=e.pivot;return this.checkDataSetValidity(t)}return`Success`}checkDataSetValidity(e){if(e.type===`SPREADSHEET`&&e.dataSet){let{zone:t,sheetId:n}=e.dataSet;return!n||!this.getters.tryGetSheet(n)||!t||!Sn(t)?`InvalidDataSet`:this.getters.checkZonesExistInSheet(n,[t])}return`Success`}},JI=class extends SI{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(!nC[e.templateName])return`InvalidTableStyle`;try{Nr(e.primaryColor)}catch{return`InvalidTableStyle`}break}return`Success`}handle(e){switch(e.type){case`CREATE_TABLE_STYLE`:let t=rC(e.tableStyleName,e.templateName,e.primaryColor);this.history.update(`styles`,e.tableStyleId,t);break;case`REMOVE_TABLE_STYLE`:let n={...this.styles};delete n[e.tableStyleId],this.history.update(`styles`,n);for(let t of this.getters.getSheetIds())for(let n of this.getters.getCoreTables(t))n.config.styleId===e.tableStyleId&&this.dispatch(`UPDATE_TABLE`,{sheetId:t,zone:n.range.zone,config:{styleId:BS.styleId}});break}}getTableStyle(e){if(_M[e])return _M[e];if(!this.styles[e])throw Error(`Table style ${e} does not exist`);return this.styles[e]}getTableStyles(){return this.styles}getNewCustomTableStyleName(){return Kt(j(`Custom Table Style`),Object.values(this.styles).map(e=>e.displayName),{compute:(e,t)=>`${e} ${t}`,start:2})}isTableStyleEditable(e){return!tC[e]&&!_M[e]}import(e){for(let e in tC)this.styles[e]=tC[e];for(let t in e.customTableStyles){let n=e.customTableStyles[t];this.styles[t]=rC(n.displayName,n.templateName,n.primaryColor)}}export(e){let t={};for(let e in this.styles)tC[e]||(t[e]={displayName:this.styles[e].displayName,templateName:this.styles[e].templateName,primaryColor:this.styles[e].primaryColor});e.customTableStyles=t}},YI=class extends SI{static getters=[`getCoreTable`,`getCoreTables`,`getCoreTableMatchingTopLeft`];tables={};nextTableId=1;adaptRanges({applyChange:e}){for(let t in this.tables)for(let n of this.getCoreTables(t))this.applyRangeChangeOnTable(t,n,e)}allowDispatch(e){switch(e.type){case`CREATE_TABLE`:if(e.ranges.some(t=>!this.getters.tryGetSheet(t._sheetId)||t._sheetId!==e.sheetId))return`InvalidSheetId`;let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e).zone);return er(t)?this.checkValidations(e,e=>this.getTablesOverlappingZones(e.sheetId,t).length?`TableOverlap`:`Success`,e=>this.checkTableConfigUpdateIsValid(e.config)):`NonContinuousTargets`;case`UPDATE_TABLE`:return this.getCoreTableMatchingTopLeft(e.sheetId,e.zone)?this.checkValidations(e,this.checkUpdatedTableZoneIsValid,e=>this.checkTableConfigUpdateIsValid(e.config)):`TableNotFound`;case`ADD_MERGE`:for(let t of this.getCoreTables(e.sheetId)){let n=t.range.zone;for(let t of e.target)if(Nn(n,t))return`MergeInTable`}break}return`Success`}handle(e){switch(e.type){case`CREATE_SHEET`:this.history.update(`tables`,e.sheetId,{});break;case`DELETE_SHEET`:{let t={...this.tables};delete t[e.sheetId],this.history.update(`tables`,t);break}case`DUPLICATE_SHEET`:{let t={};for(let n of this.getCoreTables(e.sheetId))t[n.id]=n.type===`dynamic`?this.copyDynamicTableForSheet(e.sheetIdTo,n):this.copyStaticTableForSheet(e.sheetIdTo,n);this.history.update(`tables`,e.sheetIdTo,t);break}case`CREATE_TABLE`:{let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e)),n=this.getters.getRangesUnion(t),r=this.getters.getMergesInZone(e.sheetId,n.zone);r.length&&this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:r});let i=this.consumeNextId(),a=e.config||BS,o=e.tableType===`dynamic`?this.createDynamicTable(i,n,a):this.createStaticTable(i,e.tableType,n,a);this.history.update(`tables`,e.sheetId,o.id,o);break}case`REMOVE_TABLE`:{let t={};for(let n of this.getCoreTables(e.sheetId))e.target.every(e=>!jn(n.range.zone,e))&&(t[n.id]=n);this.history.update(`tables`,e.sheetId,t);break}case`UPDATE_TABLE`:this.updateTable(e);break;case`UPDATE_CELL`:{let t=e.sheetId;for(let n of this.getCoreTables(t)){if(n.type===`dynamic`)continue;let r=this.canUpdateCellCmdExtendTable(e,n);r===`down`?this.extendTableDown(t,n):r===`right`&&this.extendTableRight(t,n)}break}case`DELETE_CONTENT`:{let t={...this.tables[e.sheetId]};for(let n in t){let r=t[n];r&&e.target.some(e=>In(r.range.zone,e))&&this.dispatch(`REMOVE_TABLE`,{sheetId:e.sheetId,target:[r.range.zone]})}break}}}getCoreTables(e){return this.tables[e]?Object.values(this.tables[e]).filter(w):[]}getCoreTable({sheetId:e,col:t,row:n}){return this.getCoreTables(e).find(e=>Fn(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getCoreTables(e).filter(e=>t.some(t=>Nn(e.range.zone,t)))}extendTableDown(e,t){let n=this.getters.extendRange(t.range,`ROW`,1);this.history.update(`tables`,e,t.id,this.updateStaticTable(t,n))}extendTableRight(e,t){let n=this.getters.extendRange(t.range,`COL`,1);this.history.update(`tables`,e,t.id,this.updateStaticTable(t,n))}canUpdateCellCmdExtendTable({content:e,sheetId:t,col:n,row:r},i){if(!e||this.isPivotFormula(e,t))return`none`;let a=i.range.zone,o=`none`;if(a.bottom+1===r&&n>=a.left&&n<=a.right?o=`down`:a.right+1===n&&r>=a.top&&r<=a.bottom&&(o=`right`),o===`none`)return`none`;let s=o===`down`?{...a,bottom:a.bottom+1,top:a.bottom+1}:{...a,right:a.right+1,left:a.right+1};for(let e=s.top;e<=s.bottom;e++)for(let n=s.left;n<=s.right;n++){let r={sheetId:t,col:n,row:e},i=this.getters.getCell(r);if(i?.isFormula||i?.content||this.getters.isInMerge(r)||this.getTablesOverlappingZones(t,[D(r)]).length)return`none`}return o}isPivotFormula(e,t){return e.startsWith(`=`)?Jj(Rc.Compile(e,t,this.getters),this.getters)?.functionName===`PIVOT`:!1}getCoreTableMatchingTopLeft(e,t){for(let n of this.getCoreTables(e)){let e=n.range.zone;if(e.left===t.left&&e.top===t.top)return n}}checkUpdatedTableZoneIsValid(e){if(!e.newTableRange)return`Success`;let t=this.getters.getRangeFromRangeData(e.newTableRange).zone,n=this.getters.checkZonesExistInSheet(e.sheetId,[t]);if(n!==`Success`)return n;let r=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);return r?this.getTablesOverlappingZones(e.sheetId,[t]).filter(e=>e.id!==r.id).length?`TableOverlap`:`Success`:`TableNotFound`}checkTableConfigUpdateIsValid(e){return e&&(e.numberOfHeaders!==void 0&&e.numberOfHeaders<0||e.hasFilters&&e.numberOfHeaders===0)?`InvalidTableConfig`:`Success`}createStaticTable(e,t,n,r,i){let a=n.zone;if(!i){i=[];for(let e of C(a.left,a.right+1)){let t={...a,left:e,right:e},o=this.consumeNextId();i.push(this.createFilterFromZone(o,n.sheetId,t,r))}}return{id:e,range:n,filters:i,config:r,type:t}}createDynamicTable(e,t,n){let r=qn(t.zone);return{id:e,range:this.getters.getRangeFromZone(t.sheetId,r),config:n,type:`dynamic`}}updateTable(e){let t=this.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return;let n=e.newTableRange?this.getters.getRangeFromRangeData(e.newTableRange):void 0;if(n){let t=this.getters.getMergesInZone(e.sheetId,n.zone);this.dispatch(`REMOVE_MERGE`,{sheetId:e.sheetId,target:t})}let r=n||t.range,i=this.updateTableConfig(e.config,t.config),a=e.tableType??t.type;if(a===`dynamic`&&t.type!==`dynamic`||a!==`dynamic`&&t.type===`dynamic`){let n=a===`dynamic`?this.createDynamicTable(t.id,r,i):this.createStaticTable(t.id,a,r,i);this.history.update(`tables`,e.sheetId,t.id,n)}else{let n=t.type===`dynamic`?this.updateDynamicTable(t,r,i):this.updateStaticTable(t,r,i,a);this.history.update(`tables`,e.sheetId,t.id,n)}}updateStaticTable(e,t,n,r=e.type){if(r===`dynamic`)throw Error(`Cannot use updateStaticTable to update a dynamic table`);let i=t||e.range,a=i.zone,o=this.updateTableConfig(n,e.config),s=o||e.config,c=[];if(t||o&&`numberOfHeaders`in o)for(let t of C(a.left,a.right+1)){let n=a.top===e.range.zone.top?e.filters.find(e=>e.col===t):void 0,r={...a,left:t,right:t},o=n?.id||this.consumeNextId();c.push(this.createFilterFromZone(o,i.sheetId,r,s))}return{...e,range:i,config:s,filters:c.length?c:e.filters,type:r}}updateDynamicTable(e,t,n){let r=t?this.getters.getRangeFromZone(t.sheetId,qn(t.zone)):e.range,i=n||e.config;return{...e,range:r,config:i}}updateTableConfig(e,t){if(!e)return t;let n={...t,...e};return e.numberOfHeaders===0?n.hasFilters=!1:e.hasFilters===!0&&(n.numberOfHeaders||=1),n}createFilterFromZone(e,t,n,r){return TM(e,this.getters.getRangeFromZone(t,n),r,this.getters.getRangeFromZone)}copyStaticTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone),r=t.filters.map(n=>{let r=this.getters.getRangeFromZone(e,n.rangeWithHeaders.zone);return TM(n.id,r,t.config,this.getters.getRangeFromZone)});return{id:t.id,range:n,filters:r,config:x(t.config),type:t.type}}copyDynamicTableForSheet(e,t){let n=this.getters.getRangeFromZone(e,t.range.zone);return{id:t.id,range:n,config:x(t.config),type:`dynamic`}}applyRangeChangeOnTable(e,t,n){let r=n(t.range),i;switch(r.changeType){case`REMOVE`:this.history.update(`tables`,e,t.id,void 0);return;case`NONE`:return;default:i=r.range}if(t.type===`dynamic`){let n=this.updateDynamicTable(t,i);this.history.update(`tables`,e,t.id,n);return}let a=[];for(let e of t.filters){let r=n(e.rangeWithHeaders);switch(r.changeType){case`REMOVE`:continue;case`NONE`:a.push(e);break;default:let n=r.range,i=TM(e.id,n,t.config,this.getters.getRangeFromZone);a.push(i)}}let o=i.zone;if(a.length<Ln(o).numberOfCols){for(let n=o.left;n<=o.right;n++)if(!a.find(e=>e.col===n)){let r=this.consumeNextId(),i={...o,left:n,right:n};a.push(this.createFilterFromZone(r,e,i,t.config))}a.sort((e,t)=>e.col-t.col)}let s=this.createStaticTable(t.id,t.type,i,t.config,a);this.history.update(`tables`,e,t.id,s)}consumeNextId(){let e=`${this.nextTableId}`;return this.history.update(`nextTableId`,this.nextTableId+1),e}import(e){for(let t of e.sheets)for(let e of t.tables||[]){let n=this.consumeNextId(),r=e.config||BS,i=this.getters.getRangeFromSheetXC(t.id,e.range),a=e.type||`static`,o=a===`dynamic`?this.createDynamicTable(n,i,r):this.createStaticTable(n,a,i,r);this.history.update(`tables`,t.id,o.id,o)}}export(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n={range:wn(e.range.zone),type:e.type};T(e.config,BS)||(n.config=e.config),t.tables.push(n)}}exportForExcel(e){for(let t of e.sheets)for(let e of this.getCoreTables(t.id)){let n=wn(e.range.zone);t.tables.push({range:n,filters:[],config:e.config})}}},XI=class extends xI{getters;constructor({getters:e,stateObserver:t}){super(t),this.getters=e}};let ZI=Fo.mapping;function QI(e,t,n){return new $I(e,t,n).getParameters()}var $I=class{getters;computeCell;evalContext;rangeCache={};constructor(e,t,n){this.getters=t,this.computeCell=n,this.evalContext=Object.assign(Object.create(ZI),e,{getters:this.getters,locale:this.getters.getLocale(),getFormulaResult:this.getFormulaResult.bind(this)})}getParameters(){return{referenceDenormalizer:this.refFn.bind(this),ensureRange:this.range.bind(this),evalContext:this.evalContext}}refFn(e){let t=this.getRangeError(e);if(t)return t;let n={sheetId:e.sheetId,col:e.zone.left,row:e.zone.top},r=this.computeCell(n);return r.position?r:{...r,position:n}}range(e){let t=this.getRangeError(e);if(t)return[[t]];let n=e.sheetId,r=e.zone,i=jn(r,this.getters.getSheetZone(n));if(!i)return[[]];let{top:a,left:o,bottom:s,right:c}=r,l=`${n}-${a}-${o}-${s}-${c}`;if(l in this.rangeCache)return this.rangeCache[l];let u=i.bottom-i.top+1,d=i.right-i.left+1,f=Array(d);for(let e=i.left;e<=i.right;e++){let t=e-i.left;f[t]=Array(u);for(let r=i.top;r<=i.bottom;r++){let a=r-i.top;f[t][a]=this.getFormulaResult({sheetId:n,col:e,row:r})}}return this.rangeCache[l]=f,f}getFormulaResult(e){let t=this.computeCell(e);return t.position?t:{...t,position:e}}getRangeError(e){if(!Sn(e.zone))return new Li;if(e.invalidSheetName)return new Li(j(`Invalid sheet name: %s`,e.invalidSheetName))}},eL=class{interval;left;right;max;constructor(e,t=null,n=null){this.interval=e,this.left=t,this.right=n,this.max=e.bottom}},tL=class{root=null;buffer=[];insert(e){this.buffer.push(e)}query(e){this.buffer.length&&this.rebuild();let t=[];return this.searchTree(this.root,e,t),t}rebuild(){let e=[];this.inOrderTraversal(this.root,e);let t=this.buffer.sort(nL),n=this.mergeSortedIntervals(e,t);this.bulkLoad(n),this.buffer=[]}compactSortedIntervals(e){let t=e[0],n=[];for(let r=1;r<e.length;r++){let i=e[r];if(i.top===t.top&&i.bottom===t.bottom&&i.dependents.zone.left===t.dependents.zone.left&&i.dependents.zone.right===t.dependents.zone.right&&i.dependents.sheetId===t.dependents.sheetId)if(i.dependents.zone.top-1===t.dependents.zone.bottom)t.dependents.zone.bottom=i.dependents.zone.bottom;else if(i.dependents.zone.top===t.dependents.zone.top&&i.dependents.zone.bottom===t.dependents.zone.bottom)continue;else n.push(t),t=i;else n.push(t),t=i}return n.push(t),n}mergeSortedIntervals(e,t){let n=[],r=0,i=0;for(;r<e.length&&i<t.length;)nL(e[r],t[i])<=0?n.push(e[r++]):n.push(t[i++]);return n.concat(r<e.length?e.slice(r):t.slice(i))}bulkLoad(e){let t=this.compactSortedIntervals(e);this.root=this.buildBalancedTree(t)}buildBalancedTree(e,t=0,n=e.length){if(t>=n)return null;let r=t+(n-t>>1),i=new eL(e[r]);return i.left=this.buildBalancedTree(e,t,r),i.right=this.buildBalancedTree(e,r+1,n),i.max=Math.max(i.interval.bottom,i.left?i.left.max:-1,i.right?i.right.max:-1),i}searchTree(e,t,n){!e||t.top>e.max||(this.isOverlapping(e.interval,t)&&n.push(e.interval),e.left&&e.left.max>=t.top&&this.searchTree(e.left,t,n),e.right&&t.bottom>=e.interval.top&&this.searchTree(e.right,t,n))}inOrderTraversal(e,t){e&&(this.inOrderTraversal(e.left,t),t.push(e.interval),this.inOrderTraversal(e.right,t))}isOverlapping(e,t){return e.top<=t.bottom&&e.bottom>=t.top}};function nL(e,t){if(e.top!==t.top)return e.top-t.top;if(e.bottom!==t.bottom)return e.bottom-t.bottom;let{zone:n,sheetId:r}=e.dependents,{zone:i,sheetId:a}=t.dependents;return r===a?n.left-i.left||n.right-i.right||n.top-i.top||n.bottom-i.bottom:r>a?1:-1}var rL=class e{profilesStartingPosition=[0];profiles=new Map([[0,[]]]);constructor(e=[]){for(let t of e)this.add(t)}isEmpty(){return this.profiles.size===1&&this.profiles.get(0)?.length===0}add(e){ln(this.profilesStartingPosition,this.profiles,[e])}delete(e){ln(this.profilesStartingPosition,this.profiles,[e],!0)}has(e){return un(this.profilesStartingPosition,this.profiles,e)}difference(e){let t=this.copy();for(let n of e)t.delete(n);return t}copy(){let t=new e;t.profilesStartingPosition=[...this.profilesStartingPosition],t.profiles=new Map;for(let[e,n]of this.profiles)t.profiles.set(e,[...n]);return t}[Symbol.iterator](){return mn(this.profilesStartingPosition,this.profiles)[Symbol.iterator]()}},iL=class e{setsBySheetId={};constructor(e=[]){for(let t of e)this.add(t)}add(e){this.setsBySheetId[e.sheetId]||(this.setsBySheetId[e.sheetId]=new rL),this.setsBySheetId[e.sheetId].add(e.zone)}addMany(e){for(let t of e)this.add(t)}addPosition(e){this.add(ac(e))}addManyPositions(e){for(let t of e)this.addPosition(t)}has(e){return this.setsBySheetId[e.sheetId]?this.setsBySheetId[e.sheetId].has(e.zone):!1}hasPosition(e){return this.has(ac(e))}delete(e){this.setsBySheetId[e.sheetId]&&this.setsBySheetId[e.sheetId].delete(e.zone)}deleteMany(e){for(let t of e)this.delete(t)}deleteManyPositions(e){for(let t of e)this.delete(ac(t))}difference(t){let n=new e;for(let e in this.setsBySheetId)n.setsBySheetId[e]=this.setsBySheetId[e];for(let e in t.setsBySheetId)n.setsBySheetId[e]&&(n.setsBySheetId[e]=n.setsBySheetId[e].difference(t.setsBySheetId[e]));return n}copy(){let t=new e;for(let e in this.setsBySheetId)t.setsBySheetId[e]=this.setsBySheetId[e].copy();return t}clear(){this.setsBySheetId={}}isEmpty(){for(let e in this.setsBySheetId)if(!this.setsBySheetId[e].isEmpty())return!1;return!0}[Symbol.iterator](){let e=[];for(let t in this.setsBySheetId)for(let n of this.setsBySheetId[t])e.push({sheetId:t,zone:n});return e[Symbol.iterator]()}},aL=class{forest={};removeAllDependencies(e){}addDependencies(e,t){let n={zone:D(e),sheetId:e.sheetId};for(let e of t){if(e.invalidSheetName||e.invalidXc)continue;let{zone:t,sheetId:r}=e;for(let e=t.left;e<=t.right;e++)this.getOrCreateIntervalTree(r,e).insert({top:t.top,bottom:t.bottom,dependents:n})}}getCellsDependingOn(e,t=new iL){t=t.copy();let n=Array.from(e).reverse();for(;n.length>0;){let e=n.pop();t.add(e);let r=e.zone,i=this.forest[e.sheetId];if(!i)continue;let a=new iL;for(let e=r.left;e<=r.right;e++){let t=i[e];if(!t)continue;let n=t.query(r);for(let e of n)a.add(e.dependents)}n.push(...a.difference(t))}for(let n of e)t.delete(n);return t}getOrCreateIntervalTree(e,t){let n=this.forest[e]?.[t];return n||(this.forest[e]||(this.forest[e]={}),n=new tL,this.forest[e][t]=n),n}},oL=class extends Uint32Array{columnOffset=0;cols=0;rows=0;static create(e,t){let n=sL(t),r=e<<n>>5,i=new this(r+1);return i.columnOffset=n,i.cols=t,i.rows=e,i}getValue(e){let[t,n]=this.getCoordinates(e);return this[t]>>n&1}setValue(e,t){let[n,r]=this.getCoordinates(e),i=(this[n]>>r&1)==0&&t===1;return this[n]=this[n]&~(1<<r)|t<<r,i}isEmpty(){return!this.some(e=>e!==0)}fillAllPositions(){this.fill(-1>>>0)}clear(){this.fill(0)}getCoordinates(e){let{row:t,col:n}=e,r=(t<<this.columnOffset)+n,i=r>>5;return[i,r-(i<<5)]}};function sL(e){return e===0?-1/0:e<0?NaN:32-Math.clz32(--e)}var cL=class{sheets={};insertions=[];maxSize=0;constructor(e){for(let t in e){let n=e[t].cols,r=e[t].rows;this.maxSize+=n*r,this.sheets[t]=oL.create(r,n)}}add(e){this.sheets[e.sheetId].setValue(e,1)&&this.insertions.push(e)}addMany(e){for(let t of e)this.add(t)}delete(e){this.sheets[e.sheetId].setValue(e,0)}deleteMany(e){for(let t of e)this.delete(t)}has(e){return this.sheets[e.sheetId].getValue(e)===1}clear(){let e=[...this];this.insertions=[];for(let e in this.sheets)this.sheets[e].clear();return e}isEmpty(){if(this.insertions.length===0)return!0;for(let e in this.sheets)if(!this.sheets[e].isEmpty())return!1;return!0}fillAllPositions(){this.insertions=Array(this.maxSize);let e=0;for(let t in this.sheets){let n=this.sheets[t];n.fillAllPositions();for(let r=0;r<n.rows;r++)for(let i=0;i<n.cols;i++)this.insertions[e++]={sheetId:t,row:r,col:i}}}*[Symbol.iterator](){for(let e of this.insertions)this.sheets[e.sheetId].getValue(e)===1&&(yield e)}},lL=d(c(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n||=self).RBush=r()})(e,function(){"use strict";function e(e,r,i,a,o){(function e(n,r,i,a,o){for(;a>i;){if(a-i>600){var s=a-i+1,c=r-i+1,l=Math.log(s),u=.5*Math.exp(2*l/3),d=.5*Math.sqrt(l*u*(s-u)/s)*(c-s/2<0?-1:1);e(n,r,Math.max(i,Math.floor(r-c*u/s+d)),Math.min(a,Math.floor(r+(s-c)*u/s+d)),o)}var f=n[r],p=i,m=a;for(t(n,i,r),o(n[a],f)>0&&t(n,i,a);p<m;){for(t(n,p,m),p++,m--;o(n[p],f)<0;)p++;for(;o(n[m],f)>0;)m--}o(n[i],f)===0?t(n,i,m):t(n,++m,a),m<=r&&(i=m+1),r<=m&&(a=m-1)}})(e,r,i||0,a||e.length-1,o||n)}function t(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function n(e,t){return e<t?-1:+(e>t)}var r=function(e){e===void 0&&(e=9),this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()};function i(e,t,n){if(!n)return t.indexOf(e);for(var r=0;r<t.length;r++)if(n(e,t[r]))return r;return-1}function a(e,t){o(e,0,e.children.length,t,e)}function o(e,t,n,r,i){i||=m(null),i.minX=1/0,i.minY=1/0,i.maxX=-1/0,i.maxY=-1/0;for(var a=t;a<n;a++){var o=e.children[a];s(i,e.leaf?r(o):o)}return i}function s(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function c(e,t){return e.minX-t.minX}function l(e,t){return e.minY-t.minY}function u(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function d(e){return e.maxX-e.minX+(e.maxY-e.minY)}function f(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function p(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function m(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function h(t,n,r,i,a){for(var o=[n,r];o.length;)if(!((r=o.pop())-(n=o.pop())<=i)){var s=n+Math.ceil((r-n)/i/2)*i;e(t,s,n,r,a),o.push(n,s,s,r)}}return r.prototype.all=function(){return this._all(this.data,[])},r.prototype.search=function(e){var t=this.data,n=[];if(!p(e,t))return n;for(var r=this.toBBox,i=[];t;){for(var a=0;a<t.children.length;a++){var o=t.children[a],s=t.leaf?r(o):o;p(e,s)&&(t.leaf?n.push(o):f(e,s)?this._all(o,n):i.push(o))}t=i.pop()}return n},r.prototype.collides=function(e){var t=this.data;if(!p(e,t))return!1;for(var n=[];t;){for(var r=0;r<t.children.length;r++){var i=t.children[r],a=t.leaf?this.toBBox(i):i;if(p(e,a)){if(t.leaf||f(e,a))return!0;n.push(i)}}t=n.pop()}return!1},r.prototype.load=function(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(var t=0;t<e.length;t++)this.insert(e[t]);return this}var n=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===n.height)this._splitRoot(this.data,n);else{if(this.data.height<n.height){var r=this.data;this.data=n,n=r}this._insert(n,this.data.height-n.height-1,!0)}else this.data=n;return this},r.prototype.insert=function(e){return e&&this._insert(e,this.data.height-1),this},r.prototype.clear=function(){return this.data=m([]),this},r.prototype.remove=function(e,t){if(!e)return this;for(var n,r,a,o=this.data,s=this.toBBox(e),c=[],l=[];o||c.length;){if(o||(o=c.pop(),r=c[c.length-1],n=l.pop(),a=!0),o.leaf){var u=i(e,o.children,t);if(u!==-1)return o.children.splice(u,1),c.push(o),this._condense(c),this}a||o.leaf||!f(o,s)?r?(n++,o=r.children[n],a=!1):o=null:(c.push(o),l.push(n),n=0,r=o,o=o.children[0])}return this},r.prototype.toBBox=function(e){return e},r.prototype.compareMinX=function(e,t){return e.minX-t.minX},r.prototype.compareMinY=function(e,t){return e.minY-t.minY},r.prototype.toJSON=function(){return this.data},r.prototype.fromJSON=function(e){return this.data=e,this},r.prototype._all=function(e,t){for(var n=[];e;)e.leaf?t.push.apply(t,e.children):n.push.apply(n,e.children),e=n.pop();return t},r.prototype._build=function(e,t,n,r){var i,o=n-t+1,s=this._maxEntries;if(o<=s)return a(i=m(e.slice(t,n+1)),this.toBBox),i;r||(r=Math.ceil(Math.log(o)/Math.log(s)),s=Math.ceil(o/s**(r-1))),(i=m([])).leaf=!1,i.height=r;var c=Math.ceil(o/s),l=c*Math.ceil(Math.sqrt(s));h(e,t,n,l,this.compareMinX);for(var u=t;u<=n;u+=l){var d=Math.min(u+l-1,n);h(e,u,d,c,this.compareMinY);for(var f=u;f<=d;f+=c){var p=Math.min(f+c-1,d);i.children.push(this._build(e,f,p,r-1))}}return a(i,this.toBBox),i},r.prototype._chooseSubtree=function(e,t,n,r){for(;r.push(t),!t.leaf&&r.length-1!==n;){for(var i=1/0,a=1/0,o=void 0,s=0;s<t.children.length;s++){var c=t.children[s],l=u(c),d=(f=e,p=c,(Math.max(p.maxX,f.maxX)-Math.min(p.minX,f.minX))*(Math.max(p.maxY,f.maxY)-Math.min(p.minY,f.minY))-l);d<a?(a=d,i=l<i?l:i,o=c):d===a&&l<i&&(i=l,o=c)}t=o||t.children[0]}var f,p;return t},r.prototype._insert=function(e,t,n){var r=n?e:this.toBBox(e),i=[],a=this._chooseSubtree(r,this.data,t,i);for(a.children.push(e),s(a,r);t>=0&&i[t].children.length>this._maxEntries;)this._split(i,t),t--;this._adjustParentBBoxes(r,i,t)},r.prototype._split=function(e,t){var n=e[t],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);var o=this._chooseSplitIndex(n,i,r),s=m(n.children.splice(o,n.children.length-o));s.height=n.height,s.leaf=n.leaf,a(n,this.toBBox),a(s,this.toBBox),t?e[t-1].children.push(s):this._splitRoot(n,s)},r.prototype._splitRoot=function(e,t){this.data=m([e,t]),this.data.height=e.height+1,this.data.leaf=!1,a(this.data,this.toBBox)},r.prototype._chooseSplitIndex=function(e,t,n){for(var r,i,a,s,c,l,d,f=1/0,p=1/0,m=t;m<=n-t;m++){var h=o(e,0,m,this.toBBox),g=o(e,m,n,this.toBBox),_=(i=h,a=g,s=void 0,c=void 0,l=void 0,d=void 0,s=Math.max(i.minX,a.minX),c=Math.max(i.minY,a.minY),l=Math.min(i.maxX,a.maxX),d=Math.min(i.maxY,a.maxY),Math.max(0,l-s)*Math.max(0,d-c)),v=u(h)+u(g);_<f?(f=_,r=m,p=v<p?v:p):_===f&&v<p&&(p=v,r=m)}return r||n-t},r.prototype._chooseSplitAxis=function(e,t,n){var r=e.leaf?this.compareMinX:c,i=e.leaf?this.compareMinY:l;this._allDistMargin(e,t,n,r)<this._allDistMargin(e,t,n,i)&&e.children.sort(r)},r.prototype._allDistMargin=function(e,t,n,r){e.children.sort(r);for(var i=this.toBBox,a=o(e,0,t,i),c=o(e,n-t,n,i),l=d(a)+d(c),u=t;u<n-t;u++){var f=e.children[u];s(a,e.leaf?i(f):f),l+=d(a)}for(var p=n-t-1;p>=t;p--){var m=e.children[p];s(c,e.leaf?i(m):m),l+=d(c)}return l},r.prototype._adjustParentBBoxes=function(e,t,n){for(var r=n;r>=0;r--)s(t[r],e)},r.prototype._condense=function(e){for(var t=e.length-1,n=void 0;t>=0;t--)e[t].children.length===0?t>0?(n=e[t-1].children).splice(n.indexOf(e[t]),1):this.clear():a(e[t],this.toBBox)},r})}))(),1),uL=class{rTrees={};constructor(e=[]){let t={};for(let n of e){let e=n.boundingBox.sheetId;t[e]||(t[e]=[]),t[e].push(n)}for(let e in t)this.rTrees[e]=new dL,this.rTrees[e].load(t[e])}insert(e){let t=e.boundingBox.sheetId;this.rTrees[t]||(this.rTrees[t]=new dL),this.rTrees[t].insert(e)}search({zone:e,sheetId:t}){return this.rTrees[t]?this.rTrees[t].search({minX:e.left,minY:e.top,maxX:e.right,maxY:e.bottom}):[]}remove(e){let t=e.boundingBox.sheetId;this.rTrees[t]&&this.rTrees[t].remove(e,this.rtreeItemComparer)}rtreeItemComparer(e,t){return e.boundingBox.sheetId===t.boundingBox.sheetId&&e.boundingBox?.zone.left===t.boundingBox.zone.left&&e.boundingBox?.zone.top===t.boundingBox.zone.top&&e.boundingBox?.zone.right===t.boundingBox.zone.right&&e.boundingBox?.zone.bottom===t.boundingBox.zone.bottom&&T(e.data,t.data)}},dL=class extends lL.default{toBBox({boundingBox:e}){let t=e.zone;return{minX:t.left,minY:t.top,maxX:t.right,maxY:t.bottom}}compareMinX(e,t){return e.boundingBox.zone.left-t.boundingBox.zone.left}compareMinY(e,t){return e.boundingBox.zone.top-t.boundingBox.zone.top}},fL=class{resultsToArrayFormulas=new uL;arrayFormulasToResults=new tN;searchFormulaPositionsSpreadingOn(e,t){return this.resultsToArrayFormulas.search({sheetId:e,zone:t}).map(e=>e.data)||pL}getArrayResultZone(e){return this.arrayFormulasToResults.get(e)}removeNode(e){let t=this.arrayFormulasToResults.get(e);t&&(this.resultsToArrayFormulas.remove({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.delete(e))}addRelation({arrayFormulaPosition:e,resultZone:t}){this.resultsToArrayFormulas.insert({boundingBox:{sheetId:e.sheetId,zone:t},data:e}),this.arrayFormulasToResults.set(e,t)}isArrayFormula(e){return this.arrayFormulasToResults.has(e)}};let pL=[],mL=new A;mL.add(`pivots`,e=>{for(let t of e.getPivotIds())e.getPivot(t).markAsDirtyForEvaluation?.()});let hL=Object.freeze(Uu({value:null}));var gL=class{context;getters;compilationParams;evaluatedCells=new tN;formulaDependencies=xt(new aL);blockedArrayFormulas=new cL({});spreadingRelations=new fL;constructor(e,t){this.context=e,this.getters=t,this.compilationParams=QI(this.context,this.getters,this.computeAndSave.bind(this))}getEvaluatedCell(e){return this.evaluatedCells.get(e)||hL}getSpreadZone(e,t={ignoreSpillError:!1}){let n=this.spreadingRelations.getArrayResultZone(e);if(!n)return;let r=this.evaluatedCells.get(e);return r?.type===`error`&&!(t.ignoreSpillError&&r?.value===M.SpilledBlocked)?D(e):kn(D(e),n)}getEvaluatedPositions(){return this.evaluatedCells.keys()}getEvaluatedPositionsInSheet(e){return this.evaluatedCells.keysForSheet(e)}getArrayFormulaSpreadingOn(e){if(this.getEvaluatedCell(e).type!==`empty`)return this.spreadingRelations.searchFormulaPositionsSpreadingOn(e.sheetId,D(e)).find(e=>!this.blockedArrayFormulas.has(e))}isArrayFormulaSpillBlocked(e){return this.blockedArrayFormulas.has(e)}updateDependencies(e){this.formulaDependencies().removeAllDependencies(e);let t=this.getDirectDependencies(e);this.formulaDependencies().addDependencies(e,t)}addDependencies(e,t){this.formulaDependencies().addDependencies(e,t),this.computeDependencies(t)}computeDependencies(e){for(let t of e)this.compilationParams.ensureRange(t)}updateCompilationParametersForIsolatedFormula(e){this.compilationParams=QI(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.__originCellPosition=e,this.compilationParams.evalContext.updateDependencies=void 0,this.compilationParams.evalContext.addDependencies=void 0,this.compilationParams.evalContext.lookupCaches=this.compilationParams.evalContext.lookupCaches||{forwardSearch:new Map,reverseSearch:new Map}}updateCompilationParameters(){this.compilationParams=QI(this.context,this.getters,this.computeAndSave.bind(this)),this.compilationParams.evalContext.updateDependencies=this.updateDependencies.bind(this),this.compilationParams.evalContext.addDependencies=this.addDependencies.bind(this),this.compilationParams.evalContext.lookupCaches={forwardSearch:new Map,reverseSearch:new Map}}createEmptyPositionSet(){let e={};for(let t of this.getters.getSheetIds())e[t]={rows:this.getters.getNumberRows(t),cols:this.getters.getNumberCols(t)};return new cL(e)}evaluateCells(e){let t=performance.now(),n=new iL;n.addManyPositions(e);let r=this.getArrayFormulasImpactedByChangesOf(e);n.addMany(this.getCellsDependingOn(n)),n.addMany(r),n.addMany(this.getCellsDependingOn(r)),this.evaluate(n),console.debug(`evaluate Cells`,performance.now()-t,`ms`)}getArrayFormulasImpactedByChangesOf(e){let t=new iL;for(let n of e){let e=this.getters.getCell(n),r=this.getArrayFormulaSpreadingOn(n);r!==void 0&&t.addPosition(r),!e?.isFormula&&!e?.content&&t.addPosition(n)}for(let e of[...t])t.addMany(this.getArrayFormulasBlockedBy(e.sheetId,e.zone));return t}buildDependencyGraph(){this.blockedArrayFormulas=this.createEmptyPositionSet(),this.spreadingRelations=new fL,this.formulaDependencies=xt(()=>{let e=new aL;for(let t of this.getters.getSheetIds())for(let n of this.getters.getCells(t))if(n.isFormula){let t=this.getters.getCellPosition(n.id);e.addDependencies(t,n.compiledFormula.rangeDependencies)}return e})}evaluateAllCells(){let e=performance.now();this.evaluatedCells=new tN;let t=[];for(let e of this.getters.getSheetIds()){let n=this.getters.getSheetZone(e);t.push({sheetId:e,zone:n})}this.evaluate(t),console.debug(`evaluate all cells`,performance.now()-e,`ms`)}evaluateFormulaResult(e,t,n){let r=Rc.Compile(t,e,this.getters);return this.updateCompilationParametersForIsolatedFormula(n),this.evaluateCompiledFormula(e,r)}evaluateCompiledFormula(e,t,n){try{let r=bL(t,this.compilationParams,e,this.buildSafeGetSymbolValue(n),this.compilationParams.evalContext.__originCellPosition);return Je(r)?co(r,vL):vL(r)}catch(e){return ko(e,``)}}getArrayFormulasBlockedBy(e,t){let n=new iL,r=this.spreadingRelations.searchFormulaPositionsSpreadingOn(e,t);n.addManyPositions(r);let i=[...r].filter(e=>!this.blockedArrayFormulas.has(e));return i.length&&n.deleteManyPositions(i),n.addMany(this.getCellsDependingOn(n)),n}nextRangesToUpdate=new iL;cellsBeingComputed=new Set;symbolsBeingComputed=new Set;evaluate(e){this.cellsBeingComputed=new Set,this.nextRangesToUpdate=new iL(e);let t=0;for(;!this.nextRangesToUpdate.isEmpty()&&t++<30;){this.updateCompilationParameters();let e=[...this.nextRangesToUpdate];this.nextRangesToUpdate.clear(),this.clearEvaluatedRanges(e);for(let t of e){let{left:e,bottom:n,right:r,top:i}=t.zone;for(let a=e;a<=r;a++)for(let e=i;e<=n;e++){let n={sheetId:t.sheetId,col:a,row:e};if(this.nextRangesToUpdate.hasPosition(n))continue;let r=this.computeCell(n);(r.value!==null||r.format!==void 0)&&this.evaluatedCells.set(n,r)}}mL.getAll().forEach(e=>e(this.getters))}t>=30&&console.warn(`Maximum iteration reached while evaluating cells`)}clearEvaluatedRanges(e){for(let t of e){let{left:e,bottom:n,right:r,top:i}=t.zone;for(let a=e;a<=r;a++)for(let e=i;e<=n;e++)this.evaluatedCells.delete({sheetId:t.sheetId,col:a,row:e})}}computeCell(e){let t=this.evaluatedCells.get(e);if(t)return t;this.blockedArrayFormulas.has(e)||this.invalidateSpreading(e),this.spreadingRelations.isArrayFormula(e)&&this.spreadingRelations.removeNode(e);let n=this.getters.getCell(e);if(n===void 0)return{...hL,position:e};let r=n.id,i={format:n.format,locale:this.getters.getLocale()};try{return this.cellsBeingComputed.has(r)?xL(e):(this.cellsBeingComputed.add(r),n.isFormula?this.computeFormulaCell(e,n):Lu(n,i,e))}catch(t){return t.value=t?.value||M.GenericError,t.message=t?.message||Mo,t.origin=e,t.errorOriginPosition=t?.errorOriginPosition,Uu(t,i.locale,e)}finally{this.cellsBeingComputed.delete(r)}}computeAndSave(e){let t=this.computeCell(e);return this.evaluatedCells.has(e)||this.evaluatedCells.set(e,t),t}computeFormulaCell(e,t){let n=bL(t.compiledFormula,this.compilationParams,e.sheetId,this.buildSafeGetSymbolValue(),e);if(!Je(n)){let r=Uu(yL(n),this.getters.getLocale(),e,t);return r.type===`error`&&(r.errorOriginPosition=n.errorOriginPosition??e),r}this.assertSheetHasEnoughSpaceToSpreadFormulaResult(e,n);let r=n.length,i=n[0].length;if(i===0)return Uu({value:0},this.getters.getLocale(),e,t);if(i===1&&r===1)return Uu(yL(n[0][0]),this.getters.getLocale(),e,t);let a={top:e.row,bottom:e.row+i-1,left:e.col,right:e.col+r-1};return this.spreadingRelations.addRelation({resultZone:a,arrayFormulaPosition:e}),this.assertNoMergedCellsInSpreadZone(e,n),_L(r,i,this.checkCollision(e)),_L(r,i,this.spreadValues(e,n)),this.invalidatePositionsDependingOnSpread(e.sheetId,a),Uu(yL(n[0][0]),this.getters.getLocale(),e,t)}invalidatePositionsDependingOnSpread(e,t){let n=this.getCellsDependingOn(zn(t).map(t=>({sheetId:e,zone:t})));n.delete({sheetId:e,zone:t}),this.nextRangesToUpdate.addMany(n)}assertSheetHasEnoughSpaceToSpreadFormulaResult({sheetId:e,col:t,row:n},r){let i=this.getters.getNumberCols(e),a=this.getters.getNumberRows(e),o=t+r.length<=i,s=n+r[0].length<=a;if(!(o&&s))throw new Bi(j(`Result couldn't be automatically expanded.`))}assertNoMergedCellsInSpreadZone({sheetId:e,col:t,row:n},r){if(this.getters.getMergesInZone(e,{top:n,bottom:n+r[0].length-1,left:t,right:t+r.length-1}).length!==0)throw new Bi(j(`Merged cells found in the spill zone. Please unmerge cells before using array formulas.`))}checkCollision(e){let{sheetId:t,col:n,row:r}=e;return(i,a)=>{let o={sheetId:t,col:i+n,row:a+r},s=this.getters.getCell(o);if(s?.isFormula||s?.content||this.getters.getEvaluatedCell(o).type!==`empty`)throw this.blockedArrayFormulas.add(e),new Bi(j(`Array result was not expanded because it would overwrite data.`),o);this.blockedArrayFormulas.delete(e)}}spreadValues({sheetId:e,col:t,row:n},r){return(i,a)=>{let o={sheetId:e,col:i+t,row:a+n},s=this.getters.getCell(o),c=Uu(yL(r[i][a]),this.getters.getLocale(),o,s);c.type===`error`&&(c.errorOriginPosition=r[i][a].errorOriginPosition??o),this.evaluatedCells.set(o,c)}}invalidateSpreading(e){let t=this.spreadingRelations.getArrayResultZone(e);if(!t)return;for(let n=t.left;n<=t.right;n++)for(let r=t.top;r<=t.bottom;r++){let t={sheetId:e.sheetId,col:n,row:r},i=this.getters.getCell(t);i?.isFormula||i?.content||this.evaluatedCells.delete(t)}let n=e.sheetId;this.invalidatePositionsDependingOnSpread(n,t),this.nextRangesToUpdate.addMany(this.getArrayFormulasBlockedBy(n,t))}buildSafeGetSymbolValue(e){return(t,n)=>{if(this.symbolsBeingComputed.has(t))return xL(this.compilationParams.evalContext.__originCellPosition);this.symbolsBeingComputed.add(t);try{let r=this.getters.getNamedRange(t);if(r){let e=this.compilationParams.evalContext;return e.__originCellPosition?this.addDependencies(e.__originCellPosition,[r.range]):this.computeDependencies([r.range]),Xn(r.range.zone)>1||n?this.compilationParams.ensureRange(r.range):this.compilationParams.referenceDenormalizer(r.range)}return e?.(t,n)||new Fi(j(`Invalid formula`))}finally{this.symbolsBeingComputed.delete(t)}}}getDirectDependencies(e){let t=this.getters.getCell(e);return t?.isFormula?t.compiledFormula.rangeDependencies:[]}getCellsDependingOn(e){return this.formulaDependencies().getCellsDependingOn(e,this.nextRangesToUpdate)}};function _L(e,t,n){for(let r=0;r<e;++r)for(let e=0;e<t;++e)r===0&&e===0||n(r,e)}function vL(e){return e.value===null||e.value===void 0?{...e,value:0}:e}function yL(e){return typeof e.value==`number`&&Math.abs(e.value)>Number.MAX_VALUE?new Hi:vL(e)}function bL(e,t,n,r,i){let a=t.evalContext,o=a.__originCellPosition,s=a.__originSheetId;a.__originCellPosition=i,a.__originSheetId=n;let c=e.execute(e.rangeDependencies,t.referenceDenormalizer,t.ensureRange,r,a);return a.__originCellPosition=o,a.__originSheetId=s,c}function xL(e){return Uu({...new Ii,origin:void 0},void 0,e)}var SL=class extends XI{static getters=[`evaluateFormula`,`evaluateFormulaResult`,`evaluateCompiledFormula`,`getCorrespondingFormulaCell`,`getVisibleRangeValues`,`getEvaluatedCell`,`getEvaluatedCells`,`getEvaluatedCellsInZone`,`getEvaluatedCellsPositions`,`getSpreadZone`,`getArrayFormulaSpreadingOn`,`isArrayFormulaSpillBlocked`,`isEmpty`];shouldRebuildDependenciesGraph=!0;evaluator;positionsToUpdate=[];constructor(e){super(e),this.evaluator=new gL(e.custom,this.getters)}beforeHandle(e){(hu.has(e.type)||_u.has(e.type))&&(this.shouldRebuildDependenciesGraph=!0)}handle(e){switch(e.type){case`UPDATE_CELL`:if(!(`content`in e||`format`in e)||this.shouldRebuildDependenciesGraph)return;let t={sheetId:e.sheetId,row:e.row,col:e.col};this.positionsToUpdate.push(t),`content`in e&&this.evaluator.updateDependencies(t);break;case`EVALUATE_CELLS`:if(e.cellIds)for(let t=0;t<e.cellIds.length;t++)this.positionsToUpdate.push(this.getters.getCellPosition(e.cellIds[t]));else this.evaluator.evaluateAllCells();break}}finalize(){this.shouldRebuildDependenciesGraph?(this.evaluator.buildDependencyGraph(),this.evaluator.evaluateAllCells(),this.shouldRebuildDependenciesGraph=!1):this.positionsToUpdate.length&&this.evaluator.evaluateCells(this.positionsToUpdate),this.positionsToUpdate=[]}evaluateFormula(e,t,n){let r=this.evaluateFormulaResult(e,t,n);return Je(r)?co(r,e=>e.value):r.value}evaluateFormulaResult(e,t,n){return this.evaluator.evaluateFormulaResult(e,t,n)}evaluateCompiledFormula(e,t,n){return this.evaluator.evaluateCompiledFormula(e,t,n)}getVisibleRangeValues(e){return this.getters.tryGetSheet(e.sheetId)===void 0?[]:this.mapVisiblePositions(e,e=>this.getters.getEvaluatedCell(e))}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 Bn(t).map(({col:t,row:n})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}))}getSpreadZone(e,t={ignoreSpillError:!1}){return this.evaluator.getSpreadZone(e,t)}getArrayFormulaSpreadingOn(e){return this.evaluator.getArrayFormulaSpreadingOn(e)}isArrayFormulaSpillBlocked(e){return this.evaluator.isArrayFormulaSpillBlocked(e)}isEmpty(e,t){return Bn(t).map(({col:t,row:n})=>this.getEvaluatedCell({sheetId:e,col:t,row:n})).every(e=>e.type===`empty`)}mapVisiblePositions(e,t){let{sheetId:n,zone:r}=e;return Bn(r).reduce((e,r)=>{let{col:i,row:a}=r;return!this.getters.isColHidden(n,i)&&!this.getters.isRowHidden(n,a)&&e.push(t({sheetId:n,...r})),e},[])}exportForExcel(e){for(let t of e.sheets)t.cellValues={},t.formulaSpillRanges={};for(let t of this.evaluator.getEvaluatedPositions()){let n=this.evaluator.getEvaluatedCell(t),r=E(t.col,t.row),i=n.value,a=!1,o,s=!0,c=e.sheets.find(e=>e.id===t.sheetId),l=this.getCorrespondingFormulaCell(t);if(l){let u=this.getters.getCell(t);if(s=l.compiledFormula.areAllFunctionsExportableToExcel(),a=s&&(u?.isFormula?u.compiledFormula.toFormulaString(this.getters):u?.content)===l.compiledFormula.toFormulaString(this.getters),!s&&i!==``){o=(i??``).toString();let t=n.format;if(t){let n=od(t,e.formats);c.formats[r]=n}}}let u=c.cells[r],d;d=s&&a&&l?.isFormula?l.compiledFormula.toFormulaString(this.getters,{useBoundedReference:!0}):s?u:o,c.cells[r]=d,c.cellValues[r]=i===M.BadExpression?void 0:i;let f=this.getSpreadZone(t);f&&(c.formulaSpillRanges[r]=this.getters.getRangeString(this.getters.getRangeFromZone(t.sheetId,f),t.sheetId))}}getCorrespondingFormulaCell(e){let t=this.getters.getCell(e);if(t&&t.isFormula)return t.compiledFormula.isBadExpression?void 0:t;if(t&&t.content)return;let n=this.getArrayFormulaSpreadingOn(e);if(n===void 0)return;let r=this.getters.getCell(n);if(r?.isFormula)return r}};let CL=new A;CL.add(`data_validation_checkbox`,(e,t)=>{if(e.isCellValidCheckbox(t)){let n=!!e.getEvaluatedCell(t).value;return{svg:n?Eb:wb,hoverSvg:n?Eb:Tb,priority:2,horizontalAlign:`center`,size:17,margin:2,position:t,type:`data_validation_checkbox`,onClick:(e,t)=>{let r=t.model.getters.getCell(e);if(t.model.getters.isReadonly()||r?.isFormula)return;let i=n?`FALSE`:`TRUE`;t.model.dispatch(`UPDATE_CELL`,{...e,content:i})}}}}),CL.add(`data_validation_list_chip_icon`,(e,t)=>{if(e.isReadonly())return;let n=e.getDataValidationChipStyle(t);if(!e.cellHasListDataValidationIcon(t)&&!n)return;let r=e.getCellComputedStyle(t),i=n||r;return{svg:xb(i),hoverSvg:Cb(i),priority:2,horizontalAlign:`right`,size:Dd(r),margin:4,position:t,onClick:(e,t)=>{let{col:n,row:r}=e;t.model.selection.selectCell(n,r),t.startCellEdition()},type:`data_validation_list_chip_icon`}}),CL.add(`conditional_formatting`,(e,t)=>{let n=e.getConditionalIcon(t);if(n){let r=e.getCellStyle(t);return{type:`conditional_formatting`,svg:kb[n].svg,priority:1,horizontalAlign:`left`,size:Dd(r),margin:4,position:t}}}),CL.add(`pivot_collapse`,(e,t)=>{let n=e.getPivotIdFromPosition(t);if(!e.isSpillPivotFormula(t)||!n)return;let r=e.getPivotCellFromPosition(t),i=e.getPivotCoreDefinition(n);if(!(i.style?.tabularForm??pg.tabularForm)&&r.type===`HEADER`&&n&&r.domain.length){let n=e.isDashboard(),a=r.dimension===`COL`?i.columns:i.rows,o=!n&&!e.shouldShowFormulas()&&r.domain.length!==a.length,s=(i.collapsedDomains?.[r.dimension]??[]).some(e=>T(e,r.domain)),c=r.dimension===`ROW`?(r.domain.length-1)*15:0;return{type:`pivot_collapse`,priority:4,horizontalAlign:`left`,size:o||!n&&r.dimension===`ROW`&&i.rows.length>1?12:0,margin:o?4+c:c,svg:o?Db(s,!1):void 0,hoverSvg:o?Db(s,!0):void 0,position:t,onClick:Hg}}}),CL.add(`pivot_dashboard_sorting`,(e,t)=>{if(!e.isDashboard()||e.getPivotCellFromPosition(t).type!==`MEASURE_HEADER`)return;let n=e.getPivotCellSortDirection(t);if(n!==`asc`&&n!==`desc`)return;let r=e.getCellComputedStyle(t);return{type:`pivot_dashboard_sorting_${n}`,priority:5,horizontalAlign:`right`,size:Dd(r),margin:0,svg:n===`asc`?Sb(r):xb(r),position:t,onClick:void 0}});var wL=class extends XI{static getters=[`doesCellHaveGridIcon`,`getCellIcons`,`getCellIconRect`];cellIconsCache={};handle(e){e.type!==`SET_VIEWPORT_OFFSET`&&(this.cellIconsCache={})}getCellIcons(e){return this.cellIconsCache[e.sheetId]||(this.cellIconsCache[e.sheetId]={}),this.cellIconsCache[e.sheetId][e.col]||(this.cellIconsCache[e.sheetId][e.col]={}),this.cellIconsCache[e.sheetId][e.col][e.row]||(this.cellIconsCache[e.sheetId][e.col][e.row]=this.computeCellIcons(e)),this.cellIconsCache[e.sheetId][e.col][e.row]}getCellIconRect(e,t){let n=e.position,r=this.getters.getCell(n);return{x:this.getIconHorizontalPosition(t,e.horizontalAlign,e),y:this.getters.computeTextYCoordinate(t,e.size,r?.style?.verticalAlign),width:e.size,height:e.size}}getIconHorizontalPosition(e,t,n){let r=e.x,i=e.x+e.width;switch(t){case`right`:return i-n.margin-n.size;case`left`:return r+n.margin;default:let e=Math.floor((i-r-n.size)/2);return i-n.size-e}}computeCellIcons(e){let t={left:void 0,right:void 0,center:void 0},n=CL.getAll();for(let r of n){let n=r(this.getters,e);n&&(!t[n.horizontalAlign]||n.priority>t[n.horizontalAlign].priority)&&(t[n.horizontalAlign]=n)}if(t.center&&(t.left||t.right)){let e=Math.max(t.left?.priority||0,t.right?.priority||0);t.center.priority<e?t.center=void 0:(t.left=void 0,t.right=void 0)}return Object.values(t).filter(w)}doesCellHaveGridIcon(e){return!!this.getCellIcons(e).length}};let TL=/"(#[0-9a-fA-F]{6})"/g;function EL(e){let t=[{leadColor:Lr(255,0,0),colors:[]},{leadColor:Lr(255,128,0),colors:[]},{leadColor:Lr(128,128,0),colors:[]},{leadColor:Lr(128,255,0),colors:[]},{leadColor:Lr(0,255,0),colors:[]},{leadColor:Lr(0,255,128),colors:[]},{leadColor:Lr(0,255,255),colors:[]},{leadColor:Lr(0,127,255),colors:[]},{leadColor:Lr(0,0,255),colors:[]},{leadColor:Lr(127,0,255),colors:[]},{leadColor:Lr(128,0,128),colors:[]},{leadColor:Lr(255,0,128),colors:[]}];for(let n of e.map(Vr)){let e=500,r=0;t.forEach((t,i)=>{let a=DL(n,t.leadColor);e>a&&(e=a,r=i)}),t[r].colors.push(n)}return t.map(e=>e.colors.sort((e,t)=>Ur(e).s-Ur(t).s)).flat().map(Br)}function DL(e,t){return Math.sqrt((e.r-t.r)**2+(e.g-t.g)**2+(e.b-t.b)**2)}var OL=class extends XI{customColors={};shouldUpdateColors=!0;static getters=[`getCustomColors`];constructor(e){super(e),this.tryToAddColors(e.customColors??[])}handle(e){switch(e.type){case`START`:for(let e of this.getters.getSheetIds()){for(let t of this.getters.getChartIds(e))this.tryToAddColors(this.getChartColors(t));for(let t of this.getters.getFigures(e))this.tryToAddColors(this.getCarouselColors(e,t.id))}break;case`UPDATE_CHART`:case`CREATE_CHART`:this.tryToAddColors(this.getChartColors(e.chartId));break;case`CREATE_CAROUSEL`:case`UPDATE_CAROUSEL`:this.tryToAddColors(this.getCarouselColors(e.sheetId,e.figureId));break;case`COLOR_SHEET`:e.color&&this.tryToAddColors([e.color]);break;case`UPDATE_CELL`:case`ADD_CONDITIONAL_FORMAT`:case`SET_BORDER`:case`SET_ZONE_BORDERS`:case`SET_FORMATTING`:case`CREATE_TABLE`:case`UPDATE_TABLE`:this.history.update(`shouldUpdateColors`,!0);break}}finalize(){this.shouldUpdateColors&&(this.history.update(`shouldUpdateColors`,!1),this.tryToAddColors(this.computeCustomColors()))}getCustomColors(){return EL(Object.keys(this.customColors))}computeCustomColors(){let e=[];for(let t of this.getters.getSheetIds())e=e.concat(this.getSheetColors(t),this.getColorsFromCells(t),this.getFormattingColors(t),this.getTableColors(t));return[...new Set([...e])]}getSheetColors(e){let t=this.getters.getSheet(e);return t.color?[t.color]:[]}getColorsFromCells(e){let t=Object.values(this.getters.getCells(e)),n=new Set;for(let e of t)e.style?.textColor&&n.add(e.style.textColor),e.style?.fillColor&&n.add(e.style.fillColor);for(let t of this.getters.getBordersColors(e))n.add(t);return[...n]}getFormattingColors(e){let t=this.getters.getConditionalFormats(e),n=[];for(let e of t){let t=e.rule;t.type===`CellIsRule`?(n.push(t.style.textColor),n.push(t.style.fillColor)):t.type===`ColorScaleRule`&&(n.push(jr(t.minimum.color)),n.push(t.midpoint?jr(t.midpoint.color):void 0),n.push(jr(t.maximum.color)))}return n.filter(w)}getChartColors(e){let t=this.getters.getChart(e);return t===void 0?[]:[...JSON.stringify(t.getRangeDefinition()).matchAll(TL)].map(e=>e[1])}getCarouselColors(e,t){if(this.getters.getFigure(e,t)?.tag!==`carousel`)return[];let n=this.getters.getCarousel(t).title?.color;return n?[n]:[]}getTableColors(e){return this.getters.getTables(e).flatMap(e=>{let t=e.config,n=this.getters.getTableStyle(t.styleId);return[this.getTableStyleElementColors(n.wholeTable),t.numberOfHeaders>0?this.getTableStyleElementColors(n.headerRow):[],t.totalRow?this.getTableStyleElementColors(n.totalRow):[],t.bandedColumns?this.getTableStyleElementColors(n.firstColumnStripe):[],t.bandedColumns?this.getTableStyleElementColors(n.secondColumnStripe):[],t.bandedRows?this.getTableStyleElementColors(n.firstRowStripe):[],t.bandedRows?this.getTableStyleElementColors(n.secondRowStripe):[],t.firstColumn?this.getTableStyleElementColors(n.firstColumn):[],t.lastColumn?this.getTableStyleElementColors(n.lastColumn):[]].flat()})}getTableStyleElementColors(e){return e?[e.style?.fillColor,e.style?.textColor,e.border?.bottom?.color,e.border?.top?.color,e.border?.left?.color,e.border?.right?.color,e.border?.horizontal?.color,e.border?.vertical?.color].filter(w):[]}tryToAddColors(e){for(let t of e){if(!Pr(t))continue;let e=Nr(t);t&&!ye.includes(e)&&this.history.update(`customColors`,e,!0)}}},kL=class extends XI{static getters=[`canCreateDynamicTableOnZones`,`doesZonesContainFilter`,`getFilter`,`getFilters`,`getTable`,`getTables`,`getTablesOverlappingZones`,`getFilterId`,`getFilterHeaders`,`isFilterHeader`];tables={};handle(e){if(hu.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tables={};return}switch(e.type){case`CREATE_TABLE`:case`REMOVE_TABLE`:case`UPDATE_TABLE`:case`DELETE_CONTENT`:case`REFRESH_PIVOT`:this.tables={};break}}finalize(){for(let e of this.getters.getSheetIds())this.tables[e]||(this.tables[e]=this.computeTables(e))}computeTables(e){let t=[],n=[...this.getters.getCoreTables(e)].filter(e=>e.type!==`dynamic`);t.push(...n);for(let r of this.getDynamicTables(e)){let i=this.coreTableToTable(e,r),a=i.range.zone,o=a.left,s=a.top;if(!n.some(e=>Fn(o,s,e.range.zone))){for(let e of n){let t=e.range.zone;Nn(a,t)&&(a=t.left>a.left?{...a,right:Math.min(a.right,t.left-1)}:{...a,bottom:Math.min(a.bottom,t.top-1)})}t.push({...i,range:this.getters.getRangeFromZone(e,a)})}}return t}getDynamicTables(e){let t=this.getters.getCoreTables(e).filter(e=>e.type===`dynamic`),n=this.getTablesFromPivots(e),r=new Set(n.map(t=>this.getters.getRangeString(t.range,e))),i=t.filter(t=>!r.has(this.getters.getRangeString(t.range,e)));return[...n,...i]}getTablesFromPivots(e){let t=[];for(let{position:n,pivotStyle:r,pivotId:i}of this.getters.getAllPivotArrayFormulas()){if(!this.getters.getPivot(i).isValid())continue;let a=this.getters.getSpreadZone(n),o=this.getters.getCell(n);n.sheetId!==e||!a||!o||r.tableStyleId===`None`||t.push({type:`dynamic`,id:`pivot_table_`+i+`_`+o.id,range:this.getters.getRangeFromZone(e,D(n)),config:this.getTableConfigFromPivotStyle(i,r),isPivotTable:!0})}return t}getTableConfigFromPivotStyle(e,t){let n=this.getters.getPivot(e).getCollapsedTableStructure(),{numberOfRows:r,numberOfHeaderRows:i}=n.getPivotTableDimensions(t),a=n.getPivotCells(t)[0]?.[r-1],o=t.displayTotals&&a?.type===`HEADER`&&a.domain.length===0;return{hasFilters:t.hasFilters,totalRow:o,firstColumn:!0,lastColumn:!0,numberOfHeaders:i,bandedRows:t.bandedRows,bandedColumns:t.bandedColumns,styleId:t.tableStyleId}}getFilters(e){return this.getTables(e).filter(e=>e.config.hasFilters).map(e=>e.filters).flat()}getTables(e){return this.tables[e]||[]}getFilter(e){let t=this.getTable(e);if(!(!t||!t.config.hasFilters))return t.filters.find(t=>t.col===e.col)}getFilterId(e){return this.getFilter(e)?.id}getTable({sheetId:e,col:t,row:n}){return this.getTables(e).find(e=>Fn(t,n,e.range.zone))}getTablesOverlappingZones(e,t){return this.getTables(e).filter(e=>t.some(t=>Nn(e.range.zone,t)))}doesZonesContainFilter(e,t){return this.getTablesOverlappingZones(e,t).some(e=>e.config.hasFilters)}getFilterHeaders(e){let t=[];for(let n of this.getTables(e)){if(!n.config.hasFilters)continue;let r=n.range.zone,i=r.top;for(let n=r.left;n<=r.right;n++)t.push({sheetId:e,col:n,row:i})}return t}isFilterHeader({sheetId:e,col:t,row:n}){return this.getFilterHeaders(e).some(e=>e.col===t&&e.row===n)}canCreateDynamicTableOnZones(e,t){if(!er(t))return!1;let n=kn(...t),r={col:n.left,row:n.top,sheetId:e},i=this.getters.getArrayFormulaSpreadingOn(r);if(!i){let e=this.getters.getEvaluatedCell(r);return e.value===M.SpilledBlocked&&!e.errorOriginPosition}else if(T(i,r)&&Xn(n)===1)return!0;return T(n,this.getters.getSpreadZone(i))}coreTableToTable(e,t){if(t.type!==`dynamic`)return t;let n=t.range.zone,r={sheetId:e,col:n.left,row:n.top},i=this.getters.getSpreadZone(r)??t.range.zone,a=this.getters.getRangeFromZone(e,i),o=this.getDynamicTableFilters(e,t,i);return{id:t.id,range:a,filters:o,config:t.config,isPivotTable:t.isPivotTable}}getDynamicTableFilters(e,t,n){let r=[],{top:i,bottom:a,left:o,right:s}=n;for(let n=o;n<=s;n++){let s=n-o,c={left:n,right:n,top:i,bottom:a},l=TM(this.getDynamicTableFilterId(t.id,s),this.getters.getRangeFromZone(e,c),t.config,this.getters.getRangeFromZone);r.push(l)}return r}getDynamicTableFilterId(e,t){return e+`_`+t}isTableExcelExportable(e,t){return t.type===`dynamic`?!1:!Bn(t.range.zone).some(t=>this.getters.getArrayFormulaSpreadingOn({sheetId:e,...t}))}exportForExcel(e){for(let t of e.sheets){let n=[];for(let r of t.tables){let i=yn(r.range),a={sheetId:t.id,col:i.left,row:i.top},o=this.getters.getCoreTable(a),s=this.getTable(a);if(!o||!s||this.isTableExcelExportable(t.id,o)){n.push(r);continue}t.styles=t.styles||{},t.borders=t.borders||{};for(let n of Bn(s.range.zone)){let r={sheetId:t.id,...n},i=this.getters.getCellComputedStyle(r),a=this.getters.getCellComputedBorder(r),o=E(n.col,n.row);if(!gt(i)){let n=od(i,e.styles);t.styles[o]=n}if(a){let n=od(a,e.borders);t.borders[o]=n}}}t.tables=n}}};function AL(e){return{...e,data:{...e.data,datasets:e.data.datasets.filter(e=>!Nf(e.xAxisID)).map(e=>({...e,pointRadius:e.showLine===!1?2:0}))},options:{...e.options,hover:{mode:null},plugins:{...e.options.plugins,title:{display:!1},legend:{display:!1},tooltip:{enabled:!1},chartShowValuesPlugin:void 0},layout:{padding:{...e.options.layout?.padding,top:5,bottom:10}},scales:{y:{...e.options.scales?.y,display:!1},y1:{...e.options.scales?.y1,display:!1},x:{...e.options.scales?.x,title:void 0,ticks:{...e.options.scales?.x?.ticks,callback:function(t){return Mf(e.options.scales?.x?.ticks?.callback?.call(this,t),5)},padding:0,font:{size:9}}}}}}}var jL=class extends XI{static getters=[`getChartRuntime`,`getStyleOfSingleCellChart`];charts={};handle(e){if(hu.has(e.type)||vu.has(e.type)||gu.has(e.type))for(let e in this.charts)this.charts[e]=void 0;switch(e.type){case`UPDATE_CHART`:case`CREATE_CHART`:this.charts[e.chartId]=void 0;break;case`DELETE_CHART`:this.charts[e.chartId]=void 0;break;case`DELETE_SHEET`:for(let e in this.charts)this.getters.isChartDefined(e)||(this.charts[e]=void 0);break}}getChartRuntime(e){if(!this.charts[e]){let t=this.getters.getChart(e);if(!t)throw Error(`No chart for the given id: ${e}`);this.charts[e]=this.createRuntimeChart(e,t)}return this.charts[e]}getStyleOfSingleCellChart(e,t){if(e)return{background:e,fontColor:xf(e)};if(!t)return{background:oe,fontColor:xf(oe)};let n=t.zone.left,r=t.zone.top,i=t.sheetId,a=this.getters.getCellComputedStyle({sheetId:i,col:n,row:r}),o=a.fillColor||`#FFFFFF`;return{background:o,fontColor:a.textColor||xf(o)}}async exportForExcel(e){for(let t of e.sheets){t.images||=[];let e=this.getters.getFigures(t.id),n=[];for(let r of e){if(!r||r.tag!==`chart`)continue;let e=this.getters.getChartIds(t.id).find(e=>this.getters.getFigureIdFromChartId(e)===r.id);if(!e)continue;let i=this.getters.getChart(e),a=i?.getDefinitionForExcel(this.getters);if(a)n.push({...r,data:a});else{if(!i)continue;let n=this.getters.getChartType(e),a=await ih(this.getters.getChartRuntime(e),r,n);a&&t.images.push({...r,tag:`image`,data:{mimetype:`image/png`,path:a,size:{width:r.width,height:r.height}}})}}t.charts=n}}createRuntimeChart(e,t){let n=t.getRangeDefinition(),r=t.getRuntime(this.getters,e);if(`chartJsConfig`in r&&/line|combo|bar|scatter|waterfall/.test(n.type)){let e=r.chartJsConfig;r.masterChartConfig=AL(e)}return r}},ML=class extends XI{static getters=[`getConditionalIcon`,`getCellConditionalFormatStyle`,`getConditionalDataBar`];isStale=!0;computedStyles={};computedIcons={};computedDataBars={};handle(e){(hu.has(e.type)||vu.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e))&&(this.isStale=!0)}finalize(){if(this.isStale){for(let e of this.getters.getSheetIds())this.computedStyles[e]=xt(()=>this.getComputedStyles(e)),this.computedIcons[e]=xt(()=>this.getComputedIcons(e)),this.computedDataBars[e]=xt(()=>this.getComputedDataBars(e));this.isStale=!1}}getCellConditionalFormatStyle(e){let{sheetId:t,col:n,row:r}=e,i=this.computedStyles[t]?.();return i&&i[n]?.[r]}getConditionalIcon({sheetId:e,col:t,row:n}){let r=this.computedIcons[e]?.();return r&&r[t]?.[n]}getConditionalDataBar({sheetId:e,col:t,row:n}){let r=this.computedDataBars[e]?.();return r&&r[t]?.[n]}getComputedStyles(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())switch(n.rule.type){case`ColorScaleRule`:for(let r of n.ranges)this.applyColorScale(e,r,n.rule,t);break;case`CellIsRule`:let r=n.rule.values.map(t=>{if(t.startsWith(`=`))return Rc.Compile(t,e,this.getters)}),i=X.get(n.rule.operator),a={...n.rule,type:n.rule.operator},o=n.ranges.map(t=>this.getters.getRangeFromSheetXC(e,t)),s=i.preComputeCriterion?.(a,o,this.getters);for(let i of n.ranges){let a=this.getters.getRangeFromSheetXC(e,i).zone;for(let i=a.top;i<=a.bottom;i++)for(let o=a.left;o<=a.right;o++){let c={sheetId:e,col:o,row:i},l=n.rule.values.map((t,n)=>{let s=r[n];return s?this.getters.getTranslatedCellFormula(e,o-a.left,i-a.top,s):t});this.getRuleResultForTarget(c,{...n.rule,values:l},s)&&(t[o]||(t[o]=[]),t[o][i]=Object.assign(t[o]?.[i]||{},n.rule.style))}}break}return t}getComputedIcons(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`IconSetRule`)for(let r of n.ranges)this.applyIcon(e,r,n.rule,t);return t}getComputedDataBars(e){let t={};for(let n of this.getters.getConditionalFormats(e).reverse())if(n.rule.type===`DataBarRule`)for(let r of n.ranges)this.applyDataBar(e,r,n.rule,t);return t}parsePoint(e,t,n,r){let i=this.getters.getRangeFromSheetXC(e,t).zone,a=this.getters.getEvaluatedCellsInZone(e,i).filter(e=>e.type===`number`).map(e=>e.value);switch(n.type){case`value`:return r===`max`?Vt(a):Ht(a);case`number`:return Number(n.value);case`percentage`:let t=Ht(a);return t+(Vt(a)-t)*Number(n.value)/100;case`percentile`:return La(a,Number(n.value)/100,!0);case`formula`:let i=n.value&&this.getters.evaluateFormula(e,n.value);return typeof i==`number`?i:null;default:return null}}applyIcon(e,t,n,r){let i=this.parsePoint(e,t,n.lowerInflectionPoint),a=this.parsePoint(e,t,n.upperInflectionPoint);if(i===null||a===null||i>a)return;let o=this.getters.getRangeFromSheetXC(e,t).zone,s=[n.icons.upper,n.icons.middle,n.icons.lower];for(let t=o.top;t<=o.bottom;t++)for(let c=o.left;c<=o.right;c++){let o=this.getters.getEvaluatedCell({sheetId:e,col:c,row:t});if(o.type!==`number`)continue;let l=this.computeIcon(o.value,a,n.upperInflectionPoint.operator,i,n.lowerInflectionPoint.operator,s);r[c]||(r[c]=[]),r[c][t]=l}}computeIcon(e,t,n,r,i,a){return n===`ge`&&e>=t||n===`gt`&&e>t?a[0]:i===`ge`&&e>=r||i===`gt`&&e>r?a[1]:a[2]}applyDataBar(e,t,n,r){let i=this.getters.getRangeFromSheetXC(e,n.rangeValues||t),a=Vt(this.getters.getEvaluatedCellsInZone(e,i.zone).filter(e=>e.type===`number`).map(e=>e.value));if(a<=0)return;let o=n.color,s=this.getters.getRangeFromSheetXC(e,t).zone,c=i.zone;for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let i=n-s.left+c.left,l=t-s.top+c.top,u=this.getters.getEvaluatedCell({sheetId:e,col:i,row:l});!Fn(i,l,c)||u.type!==`number`||u.value<=0||(r[n]||(r[n]=[]),r[n][t]={color:jr(o),percentage:u.value*100/a})}}applyColorScale(e,t,n,r){let i=this.parsePoint(e,t,n.minimum,`min`),a=n.midpoint?this.parsePoint(e,t,n.midpoint):null,o=this.parsePoint(e,t,n.maximum,`max`);if(i===null||o===null||i>=o||a!==null&&(i>=a||a>=o))return;let s=this.getters.getRangeFromSheetXC(e,t).zone,c=[{value:i,color:n.minimum.color}];n.midpoint&&a!==null&&c.push({value:a,color:n.midpoint.color}),c.push({value:o,color:n.maximum.color});let l=hi(c);for(let t=s.top;t<=s.bottom;t++)for(let n=s.left;n<=s.right;n++){let a=this.getters.getEvaluatedCell({sheetId:e,col:n,row:t});if(a.type===`number`){let e=S(a.value,i,o);r[n]||(r[n]=[]),r[n][t]=r[n]?.[t]||{},r[n][t].fillColor=l(e)}}}getRuleResultForTarget(e,t,n){let r=this.getters.getEvaluatedCell(e);if(r.type===`error`)return!1;let{sheetId:i}=e,a=X.get(t.operator),o=t.values.map(t=>t.startsWith(`=`)?this.getters.evaluateFormula(i,t,e)??``:Hu(t,V));if(o.some(Sh))return!1;let s={...t,type:t.operator,values:o.map(bh),dateValue:t.dateValue||`exactDate`};return a.isValueValid(r.value??``,s,n)}};let NL={isValid:!0};var PL=class extends XI{static getters=[`getDataValidationInvalidCriterionValueMessage`,`getInvalidDataValidationMessage`,`getValidationResultForCellValue`,`getDataValidationRangeValues`,`isCellValidCheckbox`,`getDataValidationCellStyle`,`getDataValidationChipStyle`,`isDataValidationInvalid`];validationResults={};criterionPreComputeResult={};handle(e){if(hu.has(e.type)||e.type===`EVALUATE_CELLS`||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)){this.validationResults={},this.criterionPreComputeResult={};return}switch(e.type){case`ADD_DATA_VALIDATION_RULE`:case`REMOVE_DATA_VALIDATION_RULE`:delete this.validationResults[e.sheetId],delete this.criterionPreComputeResult[e.sheetId];break}}isDataValidationInvalid(e){return!this.getValidationResultForCell(e).isValid}getDataValidationCellStyle(e){if(!this.hasChip(e))return this.getDataValidationStyle(e)}getDataValidationChipStyle(e){if(this.hasChip(e))return this.getDataValidationStyle(e)??{fillColor:`#E7E9ED`}}getInvalidDataValidationMessage(e){let t=this.getValidationResultForCell(e);return t.isValid?void 0:t.error}getDataValidationInvalidCriterionValueMessage(e,t){let n=X.get(e);return t.startsWith(`=`)?n.allowedValues===`onlyLiterals`?j(`The value must not be a formula`):this.isValidFormula(t)?void 0:By.CriterionError.validFormula:n.allowedValues===`onlyFormulas`?j(`The value must be a formula`):n.isCriterionValueValid(t)?void 0:n.criterionValueErrorString}getDataValidationRangeValues(e,t){let n=this.getters.getRangeFromSheetXC(e,String(t.values[0])),r=[],i=new Set;for(let e of Bn(n.zone)){let t=this.getters.getEvaluatedCell({...e,sheetId:n.sheetId});t.formattedValue&&!i.has(t.formattedValue)&&(i.add(t.formattedValue),r.push({label:t.formattedValue,value:t.value?.toString()||``}))}return r}isCellValidCheckbox(e){if(!this.getters.isMainCellPosition(e))return!1;let t=this.getters.getValidationRuleForCell(e);return!t||t.criterion.type!==`isBoolean`?!1:this.getValidationResultForCell(e).isValid}getValidationResultForCellValue(e,t){let n=this.getters.getValidationRuleForCell(t);if(!n)return NL;let r=this.getRuleErrorForCellValue(e,t,n);return r?{error:r,rule:n,isValid:!1}:NL}hasChip(e){let t=this.getters.getValidationRuleForCell(e);return(t?.criterion.type===`isValueInList`||t?.criterion.type===`isValueInRange`)&&t.criterion.displayStyle===`chip`}getDataValidationStyle(e){let t=this.getters.getValidationRuleForCell(e);if(!t||this.isDataValidationInvalid(e))return;let n=this.getters.getEvaluatedCell(e),r=this.getValueColor(t,n.value);if(r)return{fillColor:r,textColor:Qr(r)}}getValueColor(e,t){if(!(e.criterion.type!==`isValueInList`&&e.criterion.type!==`isValueInRange`)){for(let n in e.criterion.colors)if(n.toLowerCase()===String(t).toLowerCase())return e.criterion.colors[n]}}isValidFormula(e){return!Rc.IsBadExpression(e)}getValidationResultForCell(e){let{col:t,row:n,sheetId:r}=e;return this.validationResults[r]||(this.validationResults[r]=this.computeSheetValidationResults(r)),this.validationResults[r][t]?.[n]?.()||NL}computeSheetValidationResults(e){let t={},n=this.getters.getDataValidationRules(e).map(e=>e.ranges);for(let e of rc(n.flat())){let{col:n,row:r}=e;t[n]||(t[n]=[]),t[n][r]=xt(()=>{let t=this.getters.getEvaluatedCell(e);return t.type===`empty`?NL:this.getValidationResultForCellValue(t.value,e)})}return t}getRuleErrorForCellValue(e,t,n){let{sheetId:r}=t,i=n.criterion,a=X.get(i.type),o=this.getCellOffsetInRule(t,n),s=this.getEvaluatedCriterionValues(r,t,o,i);if(s.some(Sh))return;let c={...i,values:s.map(bh)};this.criterionPreComputeResult[r]||(this.criterionPreComputeResult[r]={});let l=this.criterionPreComputeResult[r][n.id];if(l===void 0&&(l=a.preComputeCriterion?.(n.criterion,n.ranges,this.getters),this.criterionPreComputeResult[r][n.id]=l),!a.isValueValid(e,c,l))return a.getErrorString(c,this.getters,r)}getCellOffsetInRule(e,t){let n=t.ranges.find(t=>Fn(e.col,e.row,t.zone));if(!n)throw Error(`The cell is not in any range of the rule`);return{col:e.col-n.zone.left,row:e.row-n.zone.top}}getEvaluatedCriterionValues(e,t,n,r){return r.values.map(r=>{if(!r.startsWith(`=`))return Hu(r,V);let i=Rc.Compile(r,e,this.getters),a=this.getters.getTranslatedCellFormula(e,n.col,n.row,i);return this.getters.evaluateFormula(e,a,t)})}};let FL=[`SUBTOTAL`,`PIVOT`];var IL=class extends XI{static getters=[`getCellsWithTrackedFormula`];trackedCells={};handle(e){switch(e.type){case`START`:for(let e of FL)this.trackedCells[e]={};for(let e of this.getters.getSheetIds())for(let t of this.getters.getCells(e))for(let e of FL)Yt(t,e)&&this.history.update(`trackedCells`,e,t.id,t.id);break;case`UPDATE_CELL`:{if(!(`content`in e))return;let t=this.getters.getCell(e);if(!t)return;for(let e of FL)Yt(t,e)?this.history.update(`trackedCells`,e,t.id,t.id):this.trackedCells[e][t.id]&&this.history.update(`trackedCells`,e,t.id,void 0);break}}}getCellsWithTrackedFormula(e){return Object.values(this.trackedCells[e]||{}).filter(t=>t!==void 0&&this.trackedCells[e][t]&&this.getters.tryGetCellPosition(t))}},LL=class extends XI{static getters=[`getRowSize`,`getHeaderSize`,`getMaxAnchorOffset`];tallestCellInRow={};ctx=hd();beforeHandle(e){switch(e.type){case`ADD_COLUMNS_ROWS`:if(e.dimension===`COL`)return;let t=Ct(e.position,e.base),n=Array(e.quantity).fill(void 0),r=It(this.tallestCellInRow[e.sheetId],n,t);this.history.update(`tallestCellInRow`,e.sheetId,r);break}}handle(e){switch(e.type){case`START`:case`UPDATE_LOCALE`:for(let e of this.getters.getSheetIds())this.initializeSheet(e);break;case`CREATE_SHEET`:this.initializeSheet(e.sheetId);break;case`DUPLICATE_SHEET`:{let t=x(this.tallestCellInRow[e.sheetId]);this.history.update(`tallestCellInRow`,e.sheetIdTo,t);break}case`DELETE_SHEET`:let t={...this.tallestCellInRow};delete t[e.sheetId],this.history.update(`tallestCellInRow`,t);break;case`REMOVE_COLUMNS_ROWS`:{if(e.dimension===`COL`)return;let t=Ft(this.tallestCellInRow[e.sheetId],e.elements);this.history.update(`tallestCellInRow`,e.sheetId,t);break}case`RESIZE_COLUMNS_ROWS`:{let t=e.sheetId;if(e.dimension===`ROW`)for(let n of e.elements){let e=this.getRowTallestCell(t,n);this.history.update(`tallestCellInRow`,t,n,e)}else for(let n of C(0,this.getters.getNumberRows(t)))for(let r of e.elements)this.updateRowSizeForCellChange(t,n,r)}break;case`SET_FORMATTING`:if(e.style&&(`fontSize`in e.style||`wrapping`in e.style||`rotation`in e.style))for(let t of e.target)this.updateRowSizeForZoneChange(e.sheetId,t);break;case`UPDATE_CELL`:this.updateRowSizeForCellChange(e.sheetId,e.row,e.col);break;case`ADD_MERGE`:case`REMOVE_MERGE`:for(let t of e.target)for(let n of Bn(t))this.updateRowSizeForCellChange(e.sheetId,n.row,n.col)}}getRowSize(e,t){return Math.round(this.getters.getUserRowSize(e,t)??this.tallestCellInRow[e][t]?.size??23)}getMaxAnchorOffset(e,t,n){let{numberOfRows:r,numberOfCols:i}=this.getters.getSheetSize(e),a=0;for(;a<t&&r>0;r--)a+=this.getRowSize(e,r-1);let o=0;for(;o<n&&i>0;i--)o+=this.getters.getColSize(e,i-1);return{col:i,row:r,offset:{x:o-n,y:a-t}}}getHeaderSize(e,t,n){return this.getters.isHeaderHidden(e,t,n)?0:t===`ROW`?this.getRowSize(e,n):this.getters.getColSize(e,n)}updateRowSizeForZoneChange(e,t){for(let n=t.top;n<=t.bottom;n++){let t=this.getRowTallestCell(e,n);this.history.update(`tallestCellInRow`,e,n,t)}}updateRowSizeForCellChange(e,t,n){let r=this.tallestCellInRow[e]?.[t];if(r?.cell.col===n){let n=this.getRowTallestCell(e,t);this.history.update(`tallestCellInRow`,e,t,n)}let i=this.getCellHeight({sheetId:e,col:n,row:t});if(!(i<=23)&&(!r&&i>23||r&&i>r.size)){let r={cell:{sheetId:e,col:n,row:t},size:i};this.history.update(`tallestCellInRow`,e,t,r)}}initializeSheet(e){let t=[];for(let n=0;n<this.getters.getNumberRows(e);n++){let r=this.getRowTallestCell(e,n);t.push(r)}this.history.update(`tallestCellInRow`,e,t)}getCellHeight(e){if(this.isInMultiRowMerge(e))return 23;let t=this.getters.getCell(e),n=this.getters.getColSize(e.sheetId,e.col);return gd(this.ctx,t,this.getters.getLocale(),n)}isInMultiRowMerge(e){let t=this.getters.getMerge(e);return!!t&&t.bottom!==t.top}getRowTallestCell(e,t){if(this.getters.getUserRowSize(e,t)!==void 0)return;let n=this.getters.getRowCellIds(e,t),r=0,i;for(let e=0;e<n.length;e++){let t=this.getters.getCellById(n[e]);if(!t)continue;let a=this.getters.getCellPosition(t.id),o=this.getCellHeight(a);o>r&&o>23&&(r=o,i={cell:a,size:o})}if(i&&i.size>23)return i}};let RL=`0.00%`;function zL(e){class t extends e{getters;pivotId;cache={};rankAsc={};rankDesc={};runningTotal={};runningTotalInPercent={};constructor(e,t,n){super(t,n),this.getters=n.getters,this.pivotId=e}markAsDirtyForEvaluation(){this.cache={},this.rankAsc={},this.rankDesc={},this.runningTotal={},this.runningTotalInPercent={},super.markAsDirtyForEvaluation?.()}getPivotCellValueAndFormat(e,t){return this.getMeasureDisplayValue(e,t)}_getPivotCellValueAndFormat(e,t){let n=`${e}-${t.map(e=>e.field+`=`+e.value).join(`,`)}`;if(this.cache[n])return this.cache[n];let r=this.getMeasure(e),i=r.computedBy?this.computeMeasure(r,t):super.getPivotCellValueAndFormat(e,t);return r.format?this.cache[n]={...i,format:r.format}:this.cache[n]=i,this.cache[n]}computeMeasure(e,t){if(!e.computedBy)return{value:0};let{columns:n,rows:r}=super.definition;if(e.aggregator&&n.length+r.length!==t.length){let n=this.getValuesToAggregate(e,t),r=vg[e.aggregator];if(!r)return{value:0};try{return r([n],this.getters.getLocale())}catch(t){return ko(t,e.aggregator.toUpperCase())}}let i=this.getters.getMeasureCompiledFormula(this.pivotId,e),a=this.getters.evaluateCompiledFormula(e.computedBy.sheetId,i,e=>{let{columns:n,rows:r}=this.definition;if(n.find(t=>t.nameWithGranularity===e)){let{colDomain:n}=mj(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new Ri:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}if(r.find(t=>t.nameWithGranularity===e)){let{rowDomain:n}=mj(this,t),r=n.findIndex(t=>t.field===e);return r===-1?new Ri:this.getPivotHeaderValueAndFormat(n.slice(0,r+1))}return this.getPivotCellValueAndFormat(e,t)});return Je(a)?a[0][0]:a}getValuesToAggregate(e,t){let{rowDomain:n,colDomain:r}=mj(this,t),i=super.getExpandedTableStructure(),a=[];if(r.length===0&&n.length<this.definition.rows.length&&this.definition.rows.length&&this.definition.columns.length){let t=this.treeToLeafDomains(i.getColTree()),r=this.getSubTreeMatchingDomain(i.getRowTree(),n),o=this.treeToLeafDomains(r);for(let r of t)for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t).concat(r)));return a}else if(n.length===this.definition.rows.length&&r.length===0){let t=i.getColTree(),o=this.getSubTreeMatchingDomain(t,r),s=this.treeToLeafDomains(o,r);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else if(n.length===this.definition.rows.length&&r.length&&r.length<this.definition.columns.length){let t=this.getSubTreeMatchingDomain(i.getColTree(),r),o=this.treeToLeafDomains(t,r);for(let t of o)a.push(this._getPivotCellValueAndFormat(e.id,n.concat(t)));return a}else{let t=i.getRowTree(),o=this.getSubTreeMatchingDomain(t,n),s=this.treeToLeafDomains(o,n);for(let t of s)a.push(this._getPivotCellValueAndFormat(e.id,t.concat(r)));return a}}getSubTreeMatchingDomain(e,t,n=0){if(n>t.length)return[];if(t.length===n)return e;for(let r of e){let e=Dg(this.definition.getDimension(r.field),t[n]?.value);if(r.field===t[n]?.field&&r.value===e)return this.getSubTreeMatchingDomain(r.children,t,n+1)}return[]}treeToLeafDomains(e,t=[]){let n=[];for(let r of e){let e=this.definition.getDimension(r.field),i=[...t,{field:r.field,value:r.value,type:e.type}];r.children.length===0?n.push(i):n.push(...this.treeToLeafDomains(r.children,i))}return n}getMeasureDisplayValue(e,t){let n=this.getMeasure(e),r=this._getPivotCellValueAndFormat(e,t);if(!n.display||n.display.type===`no_calculations`||r.message)return r;let i=n.display.fieldNameWithGranularity;if(i&&!this.isFieldInPivot(i))return{value:M.NotAvailable,message:j(`Field "%s" not found in pivot for measure display calculation`,i)};try{let e=n.display;switch(e.type){case`%_of_grand_total`:return this.asPercentOfGrandTotal(r,n);case`%_of_col_total`:return this.asPercentOfColumnTotal(r,n,t);case`%_of_row_total`:return this.asPercentOfRowTotal(r,n,t);case`%_of_parent_row_total`:return this.asPercentOfParentRowTotal(r,n,t);case`%_of_parent_col_total`:return this.asPercentOfParentColumnTotal(r,n,t);case`index`:return this.asIndex(r,n,t);case`%_of_parent_total`:return this.asPercentOfParentTotal(r,n,t,e);case`running_total`:return this.asRunningTotal(r,n,t,e,`running_total`);case`%_running_total`:return this.asRunningTotal(r,n,t,e,`%_running_total`);case`rank_asc`:return this.asRank(r,n,t,e,`asc`);case`rank_desc`:return this.asRank(r,n,t,e,`desc`);case`%_of`:return this.asPercentOf(r,n,t,e);case`difference_from`:return this.asDifferenceFrom(r,n,t,e);case`%_difference_from`:return this.asDifferenceFromInPercent(r,n,t,e)}return r}catch(e){return ko(e,`COMPUTE_MEASURE_DISPLAY_VALUE`)}}asPercentOfGrandTotal(e,t){let n=this.getGrandTotal(t.id);return n===0?{value:M.DivisionByZero}:{value:this.measureValueToNumber(e)/n,format:RL}}asPercentOfRowTotal(e,t,n){let r=this.getRowTotal(t.id,n);return r===0?{value:M.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:RL}}asPercentOfColumnTotal(e,t,n){let r=this.getColumnTotal(t.id,n);return r===0?{value:M.DivisionByZero}:{value:this.measureValueToNumber(e)/r,format:RL}}asPercentOfParentRowTotal(e,t,n){let r=fj(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:RL}}asPercentOfParentColumnTotal(e,t,n){let r=pj(this,n),i=this.measureValueToNumber(this._getPivotCellValueAndFormat(t.id,r));return i===0?{value:``}:{value:this.measureValueToNumber(e)/i,format:RL}}asPercentOfParentTotal(e,t,n,r){let{fieldNameWithGranularity:i}=r;if(!i)return e;if(!Sj(i,n))return{value:``};let a=bj(this,i,n),o=this._getPivotCellValueAndFormat(t.id,a),s=this.measureValueToNumber(o);return s===0?{value:``}:{value:this.measureValueToNumber(e)/s,format:RL}}asIndex(e,t,n){let r=this.measureValueToNumber(e),i=this.getRowTotal(t.id,n),a=this.getColumnTotal(t.id,n),o=this.getGrandTotal(t.id);return i===0||a===0?{value:M.DivisionByZero}:{value:r*o/(a*i),format:void 0}}asRunningTotal(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;let o=i===`running_total`?this.runningTotal:this.runningTotalInPercent,s=o[t.id]?.[a];s||(s=this.computeRunningTotal(t,a,i),o[t.id]||(o[t.id]={}),o[t.id][a]=s);let{rowDomain:c,colDomain:l}=mj(this,n),u=Tj(l),d=Tj(c),f=s[u]?.[d];return f===void 0&&(f=this.getPreviousRunningTotalValue(a,n,s)),{value:f??``,format:i===`running_total`?e.format:RL}}asPercentOf(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!Sj(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0||o===`sameValue`&&s===0?{value:M.DivisionByZero}:!o||o===`sameValue`&&!s?{value:``}:o===`sameValue`?{value:1,format:RL}:s===void 0?{value:M.NullError}:{value:s/o,format:RL}}asDifferenceFrom(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!Sj(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a)||0;return o===`sameValue`?{value:``}:{value:this.measureValueToNumber(e)-o,format:e.format}}asDifferenceFromInPercent(e,t,n,r){let{fieldNameWithGranularity:i,value:a}=r;if(a===void 0||!i)return e;if(!Sj(i,n))return{value:``};let o=this.getComparisonValue(t,n,i,a),s=this.strictMeasureValueToNumber(e);return o===0?{value:M.DivisionByZero}:!o||o===`sameValue`?{value:``}:s===void 0?{value:M.NullError}:{value:(s-o)/o,format:RL}}asRank(e,t,n,r,i){let{fieldNameWithGranularity:a}=r;if(!a)return e;if(!Sj(a,n))return{value:``};let o=i===`asc`?this.rankAsc:this.rankDesc,s=o[t.id]?.[a];s||(s=this.computeRank(t,a,i),o[t.id]||(o[t.id]={}),o[t.id][a]=s);let{rowDomain:c,colDomain:l}=mj(this,n),u=Tj(l),d=Tj(c);return{value:s[u]?.[d]??``}}computeRank(e,t,n){let r={},i=Cj(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=uo(o));for(let s of o){let o=Tj(hj(this,a,s[0].domain)),c=s.map(t=>({...t,value:this.strictMeasureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain)),rowDomain:hj(this,i,t.domain)})).filter(e=>Sj(t,e.rowDomain)),l=Object.groupBy(c,e=>Dj(e.rowDomain,t));for(let e in l)l[e]=Wt(l[e]||[],e=>e.value).filter(e=>e.value!==void 0).sort((e,t)=>n===`asc`?e.value-t.value:t.value-e.value);r[o]={};for(let e of c){let n=Tj(hj(this,i,e.domain)),a=l[Dj(e.rowDomain,t)];if(!a)continue;let s=a.findIndex(t=>t.value===e.value);s!==-1&&(r[o][n]=s+1)}}return i===`row`?r:Gt(r)}computeRunningTotal(e,t,n){let r={},i=Cj(this,t),a=i===`row`?`column`:`row`,o=this.getPivotValueCells(e.id);i===`column`&&(o=uo(o));for(let s of o){let o=Tj(hj(this,a,s[0].domain));r[o]={};let c={},l=s.map(t=>({...t,rowDomain:hj(this,i,t.domain),value:this.measureValueToNumber(this._getPivotCellValueAndFormat(e.id,t.domain))})).filter(e=>Sj(t,e.rowDomain));for(let e of l){let n=Tj(e.rowDomain),i=Oj(e.rowDomain,t),a=(c[i]||0)+e.value;c[i]=a,r[o][n]=a}if(n===`%_running_total`)for(let e of l){let n=e.rowDomain,i=Tj(n),a=Oj(n,t),s=r[o][i]||0,l=c[a];r[o][i]=l?s/l:void 0}}return i===`row`?r:Gt(r)}getPreviousRunningTotalValue(e,t,n){let r=this.definition.getDimension(e);if(r.type!==`date`&&r.type!==`datetime`)return;let i=Cj(this,e),{rowDomain:a,colDomain:o}=mj(this,t),s=i===`row`?a:o,c=i===`row`?o:a,l=s.find(t=>t.field===e)?.value;if(l===void 0)return;let u=Tj(c),d=Oj(s,e),f,p,m=this.getCollapsedTableStructure(),h=i===`row`?m.getRowTree():m.getColTree(),g=(t,n=[])=>{for(let i of t){let t=[...n,{field:i.field,value:i.value,type:i.type}];i.children.length&&g(i.children,t);let a=t.find(t=>t.field===e)?.value,o=Oj(t,e);a===void 0||o!==d||this.compareRunningTotalValues(a,l,r)>=0||(p===void 0||this.compareRunningTotalValues(p,a,r)<0)&&(p=a,f=Tj(t))}};if(g(h),f)return i===`row`?n[u]?.[f]:n[f]?.[u]}compareRunningTotalValues(e,t,n){let r=n.order??`asc`,i=e===null,a=t===null;if(i&&a)return 0;if(i)return r===`asc`?1:-1;if(a)return r===`asc`?-1:1;let o=this.getRunningTotalComparableValue(e,n)-this.getRunningTotalComparableValue(t,n);return r===`asc`?o:-o}getRunningTotalComparableValue(e,t){let n=t.granularity;if(n&&$h.contains(n)){let t=eg(n).toComparableValue?.(e);if(t!==void 0)return t}return I(e,V)}getGrandTotal(e){let t=this._getPivotCellValueAndFormat(e,[]);return this.measureValueToNumber(t)}getRowTotal(e,t){let n=mj(this,t).rowDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}getColumnTotal(e,t){let n=mj(this,t).colDomain,r=this._getPivotCellValueAndFormat(e,n);return this.measureValueToNumber(r)}isFieldInPivot(e){return this.definition.columns.some(t=>t.nameWithGranularity===e)||this.definition.rows.some(t=>t.nameWithGranularity===e)}getComparisonValue(e,t,n,r){let i=r===`(previous)`||r===`(next)`?wj(this,t,n,r):xj(t,n,r);if(T(i,t))return`sameValue`;if(!i||!_j(this,i))throw new Ri;let a=this._getPivotCellValueAndFormat(e.id,i);return this.strictMeasureValueToNumber(a)}getPivotValueCells(e){return this.getCollapsedTableStructure().getPivotCells().map(t=>t.filter(t=>t.type===`VALUE`&&t.measure===e)).filter(e=>e.length>0)}measureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(!e.value)return 0;throw Error(`Value ${e.value} is not a number`)}strictMeasureValueToNumber(e){if(typeof e.value==`number`)return e.value;if(e.value)throw Error(`Value ${e.value} is not a number`)}getCollapsedTableStructure(){let e=super.getCollapsedTableStructure();return this.sortTableStructure(e),e}getExpandedTableStructure(){let e=super.getExpandedTableStructure();return this.sortTableStructure(e),e}sortTableStructure(e){if(!this.definition.sortedColumn||e.isSorted)return;let t=this.definition.sortedColumn.measure;Fg(this.definition.sortedColumn,this)&&e.sort(t,this.definition.sortedColumn,(e,t)=>this._getPivotCellValueAndFormat(e,t))}}return t}let BL=[`ADD_PIVOT`,`UPDATE_PIVOT`,`REMOVE_PIVOT`];function VL(e){return BL.includes(e.type)}var HL=class extends XI{static getters=[`getPivot`,`getFirstPivotFunction`,`getPivotCellSortDirection`,`getPivotIdFromPosition`,`getPivotIdsFromPosition`,`getPivotCellFromPosition`,`generateNewCalculatedMeasureName`,`isPivotUnused`,`isSpillPivotFormula`,`getAllPivotArrayFormulas`,`getPivotStyleAtPosition`];pivots={};unusedPivotsInFormulas;custom;pivotPositionCache=new tN;shouldInvalidateCache=!1;constructor(e){super(e),this.custom=e.custom}beforeHandle(e){switch(e.type){case`START`:for(let e of this.getters.getPivotIds())this.setupPivot(e)}}handle(e){if(hu.has(e.type)){this.shouldInvalidateCache=!0;for(let e of this.getters.getPivotIds())this.setupPivot(e,{recreate:!0})}switch(e.type===`UPDATE_CELL`&&(this.shouldInvalidateCache=!0),e.type){case`REFRESH_PIVOT`:this.refreshPivot(e.id);break;case`ADD_PIVOT`:this.unusedPivotsInFormulas?.push(e.pivotId),this.setupPivot(e.pivotId);break;case`DUPLICATE_PIVOT`:this.unusedPivotsInFormulas?.push(e.newPivotId),this.setupPivot(e.newPivotId);break;case`UPDATE_PIVOT`:this.setupPivot(e.pivotId,{recreate:!0});break;case`DELETE_SHEET`:case`UPDATE_CELL`:this.unusedPivotsInFormulas=void 0;break;case`UNDO`:case`REDO`:{this.unusedPivotsInFormulas=void 0;let t=e.commands.filter(VL);for(let e of t){let t=e.pivotId;this.getters.isExistingPivot(t)&&this.setupPivot(t,{recreate:!0})}break}case`UPDATE_LOCALE`:Yg();break}}finalize(){this.shouldInvalidateCache&&=(this.pivotPositionCache=new tN,!1)}getPivotIdFromPosition(e){return this.getPivotIdsFromPosition(e)[0]}getPivotIdsFromPosition(e){if(!this.pivotPositionCache.has(e)){let t=this.getters.getCorrespondingFormulaCell(e);if(t&&t.isFormula){let n=this.getPivotIdsFromFormula(e.sheetId,t.compiledFormula);this.pivotPositionCache.set(e,n)}}return this.pivotPositionCache.get(e)||[]}getPivotIdsFromFormula(e,t){return this.getPivotFunctions(e,t).map(e=>{let t=e.args[0]?.toString();return t&&this.getters.getPivotId(t)}).filter(w)}isSpillPivotFormula(e){let t=this.getters.getCorrespondingFormulaCell(e);return t&&t.isFormula?this.getFirstPivotFunction(e.sheetId,t.compiledFormula)?.functionName===`PIVOT`:!1}getPivotFunctions(e,t){let n=Yj(t,this.getters);if(!n.length)return[];let r=[];for(let t of n){let{functionName:n,args:i}=t,a=i.map(t=>{if(t.type===`EMPTY`)return;if(t.type===`STRING`||t.type===`BOOLEAN`||t.type===`NUMBER`)return t.value;let n=xF(t);return this.getters.evaluateFormula(e,n)});r.push({functionName:n,args:a})}return r}getFirstPivotFunction(e,t){return this.getPivotFunctions(e,t)[0]}getPivotCellFromPosition(e){let t=this.getters.getCorrespondingFormulaCell(e);if(!t||!t.isFormula||Xj(t.compiledFormula,this.getters)===0)return Mj;let n=this.getters.getCellPosition(t.id),r=this.getters.getFirstPivotFunction(e.sheetId,t.compiledFormula);if(!r)return Mj;let{functionName:i,args:a}=r,o=a[0];if(!o)return Mj;let s=this.getters.getPivotId(o.toString());if(!s)return Mj;let c=this.getPivot(s);if(!c.isValid()||i===`PIVOT`&&!this.isMainFunctionPivotSpreadFunction(t))return Mj;try{if(i===`PIVOT`){let t=Ug(this.getters.getPivotCoreDefinition(s),bh(a[1]),bh(a[2]),bh(a[3]),bh(a[4]),bh(a[5]),this.getters.getLocale()),r=c.getCollapsedTableStructure().getPivotCells(t),i=e.col-n.col,o=e.row-n.row;return r[i][o]}let t=e.row-n.row,r=e.col-n.col;if(a=a.map(e=>Je(e)?e[r][t]:e),i===`PIVOT.HEADER`&&a.at(-2)===`measure`)return{type:`MEASURE_HEADER`,domain:c.parseArgsToPivotDomain(a.slice(1,-2).map(e=>({value:e}))),measure:a.at(-1)?.toString()||``};if(i===`PIVOT.HEADER`){let e=c.parseArgsToPivotDomain(a.slice(1).map(e=>({value:e})));return{type:`HEADER`,domain:e,dimension:mj(c,e).colDomain.length?`COL`:`ROW`}}let[o,...l]=a.slice(1);return{type:`VALUE`,domain:c.parseArgsToPivotDomain(l.map(e=>({value:e}))),measure:o?.toString()||``}}catch{return Mj}}generateNewCalculatedMeasureName(e){let t=e.map(e=>e.fieldName);return Kt(j(`Calculated measure 1`),t,{compute:(e,t)=>j(`Calculated measure %s`,t)})}getPivot(e){if(!this.getters.isExistingPivot(e))throw Error(`pivot ${e} not found`);return this.pivots[e]}isPivotUnused(e){let{type:t}=this.getters.getPivot(e);return this._getUnusedPivotsInFormulas().includes(e)&&Uj.get(t).isPivotUnused(this.getters,e)}getPivotCellSortDirection(e){let t=this.getters.getPivotIdFromPosition(e),n=this.getters.getPivotCellFromPosition(e);if(n.type===`EMPTY`||n.type===`HEADER`||n.type===`ROW_GROUP_NAME`||!t)return;let r=this.getters.getPivot(t),i=mj(r,n.domain).colDomain,a=r.definition.sortedColumn;return a?.measure===n.measure&&T(a.domain,i)?a.order:`none`}refreshPivot(e){this.getters.getPivot(e).init({reload:!0})}setupPivot(e,{recreate:t}={recreate:!1}){let n=x(this.getters.getPivotCoreDefinition(e));if(e in this.pivots)t&&this.pivots[e].onDefinitionChange(n);else{let t=zL(Uj.get(n.type).ui);this.pivots[e]=new t(e,this.custom,{definition:n,getters:this.getters})}}_getUnusedPivotsInFormulas(){if(this.unusedPivotsInFormulas!==void 0)return this.unusedPivotsInFormulas;let e=new Set(this.getters.getPivotIds());for(let t of this.getters.getSheetIds())for(let n of this.getters.getCells(t)){let t=this.getters.getCellPosition(n.id),r=this.getPivotIdsFromPosition(t);for(let t of r)if(e.delete(t),!e.size)return this.unusedPivotsInFormulas=[],[]}for(let t of this.getters.getPivotIds()){let n=this.getters.getPivotCoreDefinition(t);for(let r of n.measures)if(r.computedBy){let{sheetId:n}=r.computedBy,i=this.getters.getMeasureCompiledFormula(t,r),a=this.getPivotIdsFromFormula(n,i);for(let t of a)if(e.delete(t),!e.size)return this.unusedPivotsInFormulas=[],[]}}return this.unusedPivotsInFormulas=[...e],this.unusedPivotsInFormulas}getAllPivotArrayFormulas(){let e=[];for(let t of this.getters.getCellsWithTrackedFormula(`PIVOT`)){let n=this.getters.getCellPosition(t);if(this.getters.getEvaluatedCell(n).type===`error`)continue;let r=this.getPivotStyleAtPosition(n);r&&e.push({position:n,...r})}return e}getPivotStyleAtPosition(e){e=this.getters.getArrayFormulaSpreadingOn(e)||e;let t=this.getters.getCell(e);if(!t||!t.isFormula||!this.isMainFunctionPivotSpreadFunction(t))return;let n=this.getFirstPivotFunction(e.sheetId,t.compiledFormula);if(!n||n.functionName!==`PIVOT`)return;let r=n.args[0];if(!r)return;let i=this.getters.getPivotId(r.toString());if(i)return{pivotStyle:Ug(this.getters.getPivotCoreDefinition(i),bh(n.args[1]),bh(n.args[2]),bh(n.args[3]),bh(n.args[4]),bh(n.args[5]),this.getters.getLocale()),pivotId:i}}isMainFunctionPivotSpreadFunction(e){return e.compiledFormula.isFirstNonWhitespaceSymbol(`PIVOT`)}},UL=class{getters;dispatch;constructor(e,t){this.getters=e,this.dispatch=t}copy(e,t,n=`copyPaste`){}paste(e,t,n){}isPasteAllowed(e,t,n,r){return`Success`}isCutAllowed(e){return`Success`}getPasteTarget(e,t,n,r){return{zones:[],sheetId:e}}convertTextToClipboardData(e){}},WL=class extends UL{copy(e,t,n=`copyPaste`){}pasteFromCopy(e,t,n,r){if(t.length===1)for(let i of qT(t,n))this.pasteZone(e,i.left,i.top,n,r);else for(let i of cn(t))for(let t=i.left;t<=i.right;t++)for(let a=i.top;a<=i.bottom;a++)this.pasteZone(e,t,a,n,r)}pasteZone(e,t,n,r,i){}},GL=class extends WL{isCutAllowed(e){return e.zones.length===1?`Success`:`WrongCutSelection`}copy(e,t,n=`copyPaste`){let r=e.sheetId,{clippedZones:i,rowsIndexes:a,columnsIndexes:o}=e,s=[],c=a.length===1&&o.length===1;for(let t of a){let i=[];for(let s of o){let l={col:s,row:t,sheetId:r},u=this.getters.getCell(l),d=this.getters.getEvaluatedCell(l),f=this.getters.getPivotIdFromPosition(l),p=this.getters.getArrayFormulaSpreadingOn(l);if(n!==`shiftCells`&&f&&p){let t=this.getters.getSpreadZone(p);if((!T(p,l)||!c)&&t&&!e.zones.some(e=>In(t,e))){let e=this.getters.getPivotCellFromPosition(l),t=Eg(this.getters.getPivotFormulaId(f),e);u={id:u?.id??0,style:u?.style,format:u?.format,content:t,isFormula:!1,parsedValue:d.value}}}else if(n!==`shiftCells`&&p&&!T(p,l)){let e=a.includes(p.row)&&o.includes(p.col)?``:H(d.value,{locale:this.getters.getLocale()});u={id:u?.id??0,style:u?.style,format:d.format,content:e,isFormula:!1,parsedValue:d.value}}i.push({content:u?.isFormula?u.compiledFormula.toFormulaString(this.getters):u?.content??``,style:u?.style,format:u?.format,compiledFormula:u?.isFormula?u?.compiledFormula:void 0,border:this.getters.getCellBorder(l)||void 0,evaluatedCell:d,position:l})}s.push(i)}return{cells:s,zones:i,sheetId:e.sheetId}}isPasteAllowed(e,t,n,r){if(!n.cells)return`Success`;if(r?.isCutOperation&&r?.pasteOption!==void 0)return`WrongPasteOption`;if(t.length>1&&(n.cells.length>1||n.cells[0].length>1))return`WrongPasteSelection`;let i=n.cells.length,a=n.cells[0].length;for(let r of qT(t,n.cells))if(this.getters.doesIntersectMerge(e,r)&&(t.length>1||!this.getters.isSingleCellOrMerge(e,t[0])||i*a!==1))return`WillRemoveExistingMerge`;return`Success`}paste(e,t,n){let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t,n):this.pasteFromCopy(i,r,t.cells,n)}getPasteTarget(e,t,n,r){let i=n.cells[0].length,a=n.cells.length;return r?.isCutOperation?{sheetId:e,zones:[{left:t[0].left,top:t[0].top,right:t[0].left+i-1,bottom:t[0].top+a-1}]}:i===1&&a===1?{zones:[],sheetId:e}:{sheetId:e,zones:qT(t,n.cells)}}pasteFromCut(e,t,n,r){this.clearClippedZones(n);let i=t[0];this.pasteZone(e,i.left,i.top,n.cells,r)}clearClippedZones(e){this.dispatch(`CLEAR_CELLS`,{sheetId:e.sheetId,target:e.zones}),this.dispatch(`CLEAR_FORMATTING`,{sheetId:e.sheetId,target:e.zones})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){if(!s)continue;let o={col:t+r,row:n+a,sheetId:e};this.pasteCell(s,o,i)}}pasteCell(e,t,n){let{sheetId:r,col:i,row:a}=t,o=this.getters.getEvaluatedCell(t),s=e?.format||e.evaluatedCell.format;if(n?.pasteOption===`asValue`){this.dispatch(`UPDATE_CELL`,{...t,content:e.evaluatedCell.value?.toString()||``});return}if(n?.pasteOption===`onlyFormat`){this.dispatch(`UPDATE_CELL`,{...t,style:e?.style??null,format:s??o.format});return}let c=e?.content;e?.compiledFormula?.hasDependencies&&!n?.isCutOperation?c=this.getters.getTranslatedCellFormula(r,i-e.position.col,a-e.position.row,e.compiledFormula):e?.compiledFormula?.hasDependencies&&(c=this.getters.getFormulaMovedInSheet(r,e.compiledFormula)),c!==``||e?.format||e?.style?this.dispatch(`UPDATE_CELL`,{...t,content:c,style:e?.style||null,format:e?.format}):o&&this.dispatch(`CLEAR_CELL`,t)}convertTextToClipboardData(e){let t=this.getters.getLocale(),n={cells:[]},r=[],i=0;for(let[t,n]of e.replace(/\r/g,``).split(`
115
115
  `).entries())r.push(n.split(` `)),r[t].length>i&&(i=r[t].length);for(let e of r){let r=[];for(let n=0;n<i;n++){let i=Jy(e[n]||``,t);r.push({content:i,evaluatedCell:{formattedValue:i}})}n.cells.push(r)}return n}},KL=class extends xI{static layers=[];getters;ui;selection;dispatch;canDispatch;constructor({getters:e,stateObserver:t,dispatch:n,canDispatch:r,uiActions:i,selection:a}){super(t),this.getters=e,this.ui=i,this.selection=a,this.dispatch=n,this.canDispatch=r}drawLayer(e,t){}},qL=class extends KL{allowDispatch(e){switch(e.type){case`REMOVE_DUPLICATES`:return this.checkValidations(e,this.chainValidations(this.checkSingleRangeSelected,this.checkNoMergeInZone,this.checkRangeContainsValues,this.checkColumnsIncludedInZone),this.chainValidations(this.checkNoColumnProvided,this.checkColumnsAreUnique))}return`Success`}handle(e){switch(e.type){case`REMOVE_DUPLICATES`:this.removeDuplicates(e.columns,e.hasHeader);break;case`TRIM_WHITESPACE`:this.trimWhitespace();break}}removeDuplicates(e,t){let n=this.getters.getActiveSheetId(),r=this.getters.getSelectedZone();t&&(r.top+=1);let i=this.getUniqueRowsIndexes(n,r.top,r.bottom,e),a=i.length;if(a===Ln(r).numberOfRows){this.notifyRowsRemovedAndRemaining(0,a);return}let o=i.map(e=>({left:r.left,top:e,right:r.right,bottom:e})),s=new GL(this.getters,this.dispatch),c=s.copy(GT(n,o),!1);if(!c)return;this.dispatch(`CLEAR_CELLS`,{target:[r],sheetId:n});let l={left:r.left,top:r.top,right:r.left,bottom:r.top};s.paste({zones:[l],sheetId:n},c,{isCutOperation:!1});let u={left:r.left,top:r.top-+!!t,right:r.right,bottom:r.top+a-1};this.selection.selectZone({cell:{col:u.left,row:u.top},zone:u});let d=r.bottom-r.top+1-a;this.notifyRowsRemovedAndRemaining(d,a)}getUniqueRowsIndexes(e,t,n,r){let i=new Map;for(let a of C(t,n+1)){let t=r.map(t=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:a}).value);Object.values(i).some(e=>T(e,t))||(i[a]=t)}return Object.keys(i).map(e=>parseInt(e))}notifyRowsRemovedAndRemaining(e,t){this.ui.notifyUI({type:`info`,text:j(`%s duplicate rows found and removed.
116
- %s unique rows remain.`,e.toString(),t.toString()),sticky:!1})}checkSingleRangeSelected(){return this.getters.getSelectedZones().length===1?`Success`:`MoreThanOneRangeSelected`}checkNoMergeInZone(){let e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZone();return this.getters.getMergesInZone(e,t).length>0?`WillRemoveExistingMerge`:`Success`}checkRangeContainsValues(e){let t=this.getters.getActiveSheetId(),n=this.getters.getSelectedZone();return e.hasHeader&&(n.top+=1),this.getters.getEvaluatedCellsInZone(t,n).every(e=>e.type===`empty`)?`EmptySelectedRange`:`Success`}checkNoColumnProvided(e){return e.columns.length===0?`NoColumnsProvided`:`Success`}checkColumnsIncludedInZone(e){let t=this.getters.getSelectedZone();return e.columns.some(e=>e<t.left||e>t.right)?`ColumnsNotIncludedInZone`:`Success`}checkColumnsAreUnique(e){return e.columns.length===new Set(e.columns).size?`Success`:`DuplicatesColumnsSelected`}trimWhitespace(){let e=cn(this.getters.getSelectedZones()),t=this.getters.getActiveSheetId(),n=0;for(let{col:r,row:i}of e.map(Bn).flat()){let e=this.getters.getCell({col:r,row:i,sheetId:t});if(!e)continue;let a=e.isFormula?e.compiledFormula.toFormulaString(this.getters):e.content,o=Rt(a);o!==a&&(n+=1,this.dispatch(`UPDATE_CELL`,{sheetId:t,col:r,row:i,content:o}))}let r=n?j(`Trimmed whitespace from %s cells.`,n):j(`No selected cells had whitespace trimmed.`);this.ui.notifyUI({type:`info`,text:r,sticky:!1})}};let JL=new A;JL.add(`ALPHANUMERIC_INCREMENT_MODIFIER`,{apply:(e,t)=>{e.current+=e.increment;let n=Math.abs(e.current).toString();n=`0`.repeat(Math.max(e.numberPostfixLength-n.length,0))+n;let r=`${e.prefix}${n}`;return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:{props:{content:r}}}}}).add(`INCREMENT_MODIFIER`,{apply:(e,t,n)=>{e.current+=e.increment;let r=e.current.toString(),i=n.getLocale(),a=H(e.current,{format:t.cell?.format,locale:i});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:a}}:void 0}}}).add(`DATE_INCREMENT_MODIFIER`,{apply:(e,t,n)=>{let r=z(e.current,n.getLocale());r.setFullYear(r.getFullYear()+e.increment.years||0),r.setMonth(r.getMonth()+e.increment.months||0),r.setDate(r.getDate()+e.increment.days||0);let i=ga(r);e.current=i;let a=n.getLocale(),o=H(i,{format:t.cell?.format,locale:a});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:i.toString()},tooltip:i?{props:{content:o}}:void 0}}}).add(`COPY_MODIFIER`,{apply:(e,t,n)=>{let r=t.cell?.isFormula?t.cell?.compiledFormula.toFormulaString(n):t.cell?.content||``,i={locale:n.getLocale(),format:t.cell?.format},a={sheetId:t.sheetId,col:t.col,row:t.row};return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:t.cell?Lu(t.cell,i,a).formattedValue:``}}:void 0}}}).add(`FORMULA_MODIFIER`,{apply:(e,t,n,r)=>{e.current+=e.increment;let i=0,a=0;switch(r){case`up`:i=0,a=-e.current;break;case`down`:i=0,a=e.current;break;case`left`:i=-e.current,a=0;break;case`right`:i=e.current,a=0;break}let o=t.cell;if(!o||!o.isFormula)return{cellData:{}};let s=t.sheetId,c=n.getTranslatedCellFormula(s,i,a,o.compiledFormula);return{cellData:{border:t.border,style:o.style,format:o.format,content:c},tooltip:c?{props:{content:c}}:void 0}}});let YL=new A,XL=/(\d+)$/,ZL=/^(.*\D+)/,QL=/^(.*\D+)(\d+)$/,$L=/^0*/;function eR(e,t,n){let r=[],i=!1;for(let a of t){a===e&&(i=!0);let t=a===void 0||a.isFormula?void 0:Lu(a,{locale:V,format:a.format});if(t&&n(t))r.push(t);else{if(i)return r;r=[]}}return r}function tR(e){let t=[],n=e[0];for(let r=1;r<e.length;r++){let i=e[r];t.push(i-n),n=i}return t.reduce((e,t)=>e+t,0)/t.length}function nR(e){let t=1;return e.length>=2&&(t=tR(e)*e.length),t}function rR(e){return e.length<2?e[0]||{years:0,months:0,days:0}:e.every(t=>t.years===e[0].years&&t.months===e[0].months&&t.days===e[0].days)?e[0]:void 0}function iR(e){if(e.length<2)return 1;let t=e.map(e=>z(e,V)),n=rR(aR(t));if(n===void 0)return;let r=Object.values(n).filter(e=>e!==0).length===1,i=Object.values(n).every(e=>e===0);if(!r||i){let n=t.map((e,n)=>{if(n===0)return 0;let r=t[n-1];return Math.floor(e.getTime())-Math.floor(r.getTime())}).slice(1);if(n.every(e=>e===n[0]))return e.length*(e[1]-e[0])}return{years:n.years*e.length,months:n.months*e.length,days:n.days*e.length}}YL.add(`simple_value_copy`,{condition:(e,t)=>t.length===1&&!e.isFormula&&!(e.format&&Il(e.format)),generateRule:()=>({type:`COPY_MODIFIER`}),sequence:10}).add(`increment_alphanumeric_value`,{condition:e=>!e.isFormula&&Lu(e,{locale:V}).type===`text`&&QL.test(e.content),generateRule:(e,t,n)=>{let r=parseInt(e.content.match(XL)[0]),i=e.content.match(ZL)[0],a=eR(e,t,e=>e.type===`text`&&QL.test(e.value)).filter(e=>i===(e.value??``).toString().match(ZL)[0]).map(e=>(e.value??``).toString().match(XL)[0]),o=a.reduce((e,t)=>{let n=t.match($L)[0].length;return n>e[1]?[t,n]:e},[a[0],0]),s=o[1]?o[0].length:0,c=nR(a.map(e=>parseInt(e)));return[`up`,`left`].includes(n)&&a.length===1&&(c=-c),{type:`ALPHANUMERIC_INCREMENT_MODIFIER`,prefix:i,current:r,increment:c,numberPostfixLength:s}},sequence:15}).add(`copy_text`,{condition:e=>!e.isFormula&&Lu(e,{locale:V}).type===`text`,generateRule:()=>({type:`COPY_MODIFIER`}),sequence:20}).add(`update_formula`,{condition:e=>e.isFormula,generateRule:(e,t)=>({type:`FORMULA_MODIFIER`,increment:t.length,current:0}),sequence:30}).add(`increment_dates`,{condition:(e,t)=>!e.isFormula&&Lu(e,{locale:V}).type===`number`&&!!e.format&&Il(e.format),generateRule:(e,t)=>{let n=iR(eR(e,t,e=>e.type===`number`&&!!e.format&&Il(e.format)).map(e=>Number(e.value)));if(n===void 0)return{type:`COPY_MODIFIER`};let r=Lu(e,{locale:V});return typeof n==`object`?{type:`DATE_INCREMENT_MODIFIER`,increment:n,current:r.type===`number`?r.value:0}:{type:`INCREMENT_MODIFIER`,increment:n,current:r.type===`number`?r.value:0}},sequence:25}).add(`increment_number`,{condition:e=>!e.isFormula&&Lu(e,{locale:V}).type===`number`,generateRule:(e,t,n)=>{let r=eR(e,t,e=>e.type===`number`&&!Il(e.format||``)).map(e=>Number(e.value)),i=nR(r);[`up`,`left`].includes(n)&&r.length===1&&(i=-i);let a=Lu(e,{locale:V});return{type:`INCREMENT_MODIFIER`,increment:i,current:a.type===`number`?a.value:0}},sequence:40});function aR(e){return e.length<2?[{years:0,months:0,days:0}]:e.map((t,n)=>{if(n===0)return{years:0,months:0,days:0};let r=P.fromTimestamp(e[n-1].getTime()),i=wa(r,t),a=Sa(r,t)%12;return r.setFullYear(r.getFullYear()+i),r.setMonth(r.getMonth()+a),{years:i,months:a,days:Ca(r,t)}}).slice(1)}var oR=class{cells;getters;index=0;direction;constructor(e,t,n){this.cells=e,this.getters=t,this.direction=n}next(){let e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:n,tooltip:r}=JL.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:n,tooltip:r,origin:{col:e.data.col,row:e.data.row}}}},sR=class extends KL{static layers=[`Autofill`];static getters=[`getAutofillTooltip`];autofillZone;steps;lastCellSelected={};direction;tooltip;allowDispatch(e){switch(e.type){case`AUTOFILL_SELECT`:let t=this.getters.getActiveSheetId();return this.lastCellSelected.col=e.col===-1?this.lastCellSelected.col:S(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=e.row===-1?this.lastCellSelected.row:S(e.row,0,this.getters.getNumberRows(t)),this.lastCellSelected.col!==void 0&&this.lastCellSelected.row!==void 0?`Success`:`InvalidAutofillSelection`}return`Success`}handle(e){switch(e.type){case`AUTOFILL`:this.autofill(!0);break;case`AUTOFILL_SELECT`:this.select(e.col,e.row);break;case`AUTOFILL_AUTO`:this.autofillAuto();break}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||this.direction===void 0){this.tooltip=void 0;return}let t=this.getters.getSelectedZone(),n=this.autofillZone,r=[];switch(this.direction){case`down`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.top;n<=t.bottom;n++)i.push(E(e,n));let a=this.createGenerator(i);for(let t=n.top;t<=n.bottom;t++)r.push(this.computeNewCell(a,e,t))}break;case`up`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.bottom;n>=t.top;n--)i.push(E(e,n));let a=this.createGenerator(i);for(let t=n.bottom;t>=n.top;t--)r.push(this.computeNewCell(a,e,t))}break;case`left`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.right;n>=t.left;n--)i.push(E(n,e));let a=this.createGenerator(i);for(let t=n.right;t>=n.left;t--)r.push(this.computeNewCell(a,t,e))}break;case`right`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.left;n<=t.right;n++)i.push(E(n,e));let a=this.createGenerator(i);for(let t=n.left;t<=n.right;t++)r.push(this.computeNewCell(a,t,e))}break}if(e){let e={},t={},n={},i=this.getters.getActiveSheetId();for(let a of r)this.collectBordersData(a,e),this.autofillMerge(i,a),this.autofillCell(i,a),this.collectConditionalFormatsData(i,a,t),this.collectDataValidationsData(i,a,n);this.autofillBorders(i,e),this.autofillConditionalFormats(i,t),this.autofillDataValidations(i,n),this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0}}collectBordersData(e,t){let n=JSON.stringify(e.border);n in t||(t[n]=[]),t[n].push(D({col:e.col,row:e.row}))}collectConditionalFormatsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s=this.getters.getRulesByCell(e,r,i),c=E(a,o);for(let e of s)e.id in n||(n[e.id]=[]),n[e.id].push(c)}collectDataValidationsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s={sheetId:e,col:r,row:i},c=this.getters.getValidationRuleForCell(s);c&&(c.id in n||(n[c.id]=[]),n[c.id].push(D({col:a,row:o})))}autofillCell(e,t){this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t.col,row:t.row,content:t.content||``,style:t.style||null,format:t.format||``}),this.dispatch(`AUTOFILL_CELL`,t)}autofillBorders(e,t){for(let n in t){let r=n===`undefined`?void 0:JSON.parse(n);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,border:r,target:cn(t[n])})}}autofillConditionalFormats(e,t){for(let n in t){let r=t[n],i=this.getters.getConditionalFormats(e).find(e=>e.id===n);if(!i)continue;let a=this.getters.getAdaptedCfRanges(e,i,r.map(yn),[]);a&&this.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{id:i.id,rule:i.rule,stopIfTrue:i.stopIfTrue},ranges:a,sheetId:e})}}autofillDataValidations(e,t){for(let n in t){let r=t[n],i=this.getters.getDataValidationRule(e,n);if(!i)continue;let a=cn(i.ranges.map(e=>e.zone).concat(r),[]);this.dispatch(`ADD_DATA_VALIDATION_RULE`,{rule:i,ranges:a.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e})}}select(e,t){let n=this.getters.getSelectedZone();if(Fn(e,t,n)){this.autofillZone=void 0;return}switch(this.direction=this.getDirection(e,t),this.direction){case`up`:this.saveZone(t,n.top-1,n.left,n.right),this.steps=n.top-t;break;case`down`:this.saveZone(n.bottom+1,t,n.left,n.right),this.steps=t-n.bottom;break;case`left`:this.saveZone(n.top,n.bottom,e,n.left-1),this.steps=n.left-e;break;case`right`:this.saveZone(n.top,n.bottom,n.right+1,e),this.steps=e-n.right;break}this.autofill(!1)}autofillAuto(){let e=this.getters.getActivePosition(),t=this.getters.getTable(e),n=t?t.range.zone.bottom:this.getAutofillAutoLastRow(),r=this.getters.getSelectedZone();for(let t=r.bottom+1;t<=n;t++)if(this.getters.getEvaluatedCell({...e,row:t}).type!==`empty`){n=t-1;break}n>r.bottom&&(this.select(e.col,n),this.autofill(!0))}getAutofillAutoLastRow(){let e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId(),n=e.left,r=e.bottom;if(n>0){let e={sheetId:t,col:n-1,row:r};for(;this.getters.getEvaluatedCell(e).type!==`empty`;)r+=1,e={sheetId:t,col:n-1,row:r}}if(r===e.bottom&&(n=e.right,n<=this.getters.getNumberCols(t))){let e={sheetId:t,col:n+1,row:r};for(;this.getters.getEvaluatedCell(e).type!==`empty`;)r+=1,e={sheetId:t,col:n+1,row:r}}return r-1}computeNewCell(e,t,n){let{cellData:r,tooltip:i,origin:a}=e.next(),{content:o,style:s,border:c,format:l}=r;return this.tooltip=i,{originCol:a.col,originRow:a.row,col:t,row:n,content:o,style:s,border:c,format:l}}getRule(e,t){let n=YL.getAll().sort((e,t)=>e.sequence-t.sequence).find(n=>n.condition(e,t));return n&&this.direction&&n.generateRule(e,t,this.direction)}createGenerator(e){let t=[],n=[],r=this.getters.getActiveSheetId();for(let t of e){let{col:e,row:i}=sn(t),a=this.getters.getCell({sheetId:r,col:e,row:i});n.push({col:e,row:i,cell:a,sheetId:r})}let i=n.map(e=>e.cell);for(let e of n){let n={type:`COPY_MODIFIER`};e&&e.cell&&(n=this.getRule(e.cell,i)||n);let r=this.getters.getCellBorder(e)??void 0;t.push({data:{...e,border:r},rule:n})}return new oR(t,this.getters,this.direction)}saveZone(e,t,n,r){this.autofillZone={top:e,bottom:t,left:n,right:r}}getDirection(e,t){let n=this.getters.getSelectedZone(),r={up:{number:n.top-t,value:`up`},down:{number:t-n.bottom,value:`down`},left:{number:n.left-e,value:`left`},right:{number:e-n.right,value:`right`}};if(Object.values(r).map(e=>+(e.number>0)).reduce((e,t)=>e+t)===1)return Object.values(r).find(e=>+(e.number>0)).value;let i=r.up.number>0?`up`:`down`,a=r.left.number>0?`left`:`right`;return Math.abs(r[i].number)>=Math.abs(r[a].number)?r[i].value:r[a].value}autofillMerge(e,t){let{originCol:n,originRow:r,col:i,row:a}=t,o={sheetId:e,col:i,row:a},s={sheetId:e,col:n,row:r};if(this.getters.isInMerge(o)&&!this.getters.isInMerge(s)){let t=this.getters.getMerge(o);t&&this.dispatch(`REMOVE_MERGE`,{sheetId:e,target:[t]})}let c=this.getters.getMerge(s);c?.left===n&&c?.top===r&&this.dispatch(`ADD_MERGE`,{sheetId:e,target:[{top:a,bottom:a+c.bottom-c.top,left:i,right:i+c.right-c.left}]})}drawLayer(e){if(!this.autofillZone)return;let{ctx:t,thinLineWidth:n,viewports:r,sheetId:i}=e,{x:a,y:o,width:s,height:c}=r.getVisibleRect(i,this.autofillZone);s>0&&c>0&&(t.strokeStyle=`black`,t.lineWidth=n,t.setLineDash([3]),t.strokeRect(a,o,s,c),t.setLineDash([]))}},cR=class extends KL{static getters=[`getAutomaticSums`];handle(e){switch(e.type){case`SUM_SELECTION`:let e=this.getters.getActiveSheetId(),{zones:t,anchor:n}=this.getters.getSelection();for(let r of t){let t=this.getAutomaticSums(e,r,n.cell);this.dispatchCellUpdates(e,t)}break}}getAutomaticSums(e,t,n){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,n):this.sumData(e,t)}sumData(e,t){let n=this.dimensionsToSum(e,t),r=this.sumDimensions(e,t,n).filter(({zone:t})=>!this.getters.isEmpty(e,t));return n.has(`ROW`)&&n.has(`COL`)&&r.push(this.sumTotal(t)),r}sumAdjacentData(e,t,n){let{col:r,row:i}=Fn(n.col,n.row,t)?n:{col:t.left,row:t.top},a=this.findAdjacentData(e,r,i);return a?this.getters.isSingleCellOrMerge(e,t)||Rn(kn(a,t))?[{position:{col:r,row:i},zone:a}]:this.sumDimensions(e,kn(a,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,n){let r=this.getters.getSheet(e),i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.findSuitableZoneToSum(r,i.col,i.row);if(a)return this.getters.expandZone(e,a)}findSuitableZoneToSum(e,t,n){let r=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:n-1}),i=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:n});if(this.isNumber(i)&&!this.isNumber(r))return this.findHorizontalZone(e,t,n);let a=this.findVerticalZone(e,t,n);if(this.isZoneValid(a))return a;let o=this.findHorizontalZone(e,t,n);if(this.isZoneValid(o))return o}findVerticalZone(e,t,n){let r={top:0,bottom:n-1,left:t,right:t},i=this.reduceZoneStart(e,r,r.bottom);return{...r,top:i}}findHorizontalZone(e,t,n){let r={top:n,bottom:n,left:0,right:t-1},i=this.reduceZoneStart(e,r,r.right);return{...r,left:i}}reduceZoneStart(e,t,n){let r=this.getters.getEvaluatedCellsInZone(e.id,t),i=C(n,-1,-1),a=Vt(i.filter(e=>r[e]&&!r[e].isAutoSummable)),o=rt(i.filter(e=>this.isNumber(r[e])))[0]||[];return Vt(o)<a?1/0:Ht(o)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===`number`&&!(e.format&&Il(e.format))}isZoneValid(e){return e.bottom>=e.top&&e.right>=e.left}lastColIsEmpty(e,t){return this.getters.isEmpty(e,{...t,left:t.right})}lastRowIsEmpty(e,t){return this.getters.isEmpty(e,{...t,top:t.bottom})}dimensionsToSum(e,t){let n=new Set;return Rn(t)?(n.add(Ln(t).numberOfCols===1?`COL`:`ROW`),n):(this.lastColIsEmpty(e,t)&&n.add(`ROW`),this.lastRowIsEmpty(e,t)&&n.add(`COL`),n.size===0&&n.add(`COL`),n)}sumDimensions(e,t,n){return[...n.has(`COL`)?this.sumColumns(t,e):[],...n.has(`ROW`)?this.sumRows(t,e):[]]}sumTotal(e){let{bottom:t,right:n}=e;return{position:{col:n,row:t},zone:{...e,top:t,right:n-1}}}sumColumns(e,t){let n=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,n.bottom-1)},Bn(n).map(t=>({position:t,zone:{...e,right:t.col,left:t.col}}))}sumRows(e,t){let n=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,n.right-1)},Bn(n).map(t=>({position:t,zone:{...e,top:t.row,bottom:t.row}}))}dispatchCellUpdates(e,t){for(let n of t){let{col:t,row:r}=n.position;this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,content:`=SUM(${this.getters.zoneToXC(e,n.zone)})`})}}nextEmptyRow(e,t){let n=t.bottom+1,{left:r,right:i}=t;for(;!this.getters.isEmpty(e,{bottom:n,top:n,left:r,right:i});)n++;return{...t,top:n,bottom:n}}nextEmptyCol(e,t){let n=t.right+1,{top:r,bottom:i}=t;for(;!this.getters.isEmpty(e,{left:n,right:n,top:r,bottom:i});)n++;return{...t,left:n,right:n}}transpose(e){return new Set([...e.values()].map(e=>e===`COL`?`ROW`:`COL`))}},lR=class extends KL{static getters=[`getCellTableStyle`,`getCellTableBorder`];tableStyles={};handle(e){if(hu.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tableStyles={};return}if(dR(e)){`sheetId`in e?delete this.tableStyles[e.sheetId]:this.tableStyles={};return}}finalize(){for(let e of this.getters.getSheetIds()){this.tableStyles[e]||(this.tableStyles[e]={});for(let t of this.getters.getTables(e))this.tableStyles[e][t.id]||(this.tableStyles[e][t.id]=this.computeTableStyle(e,t))}}getCellTableStyle(e){let t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().styles[e.col]?.[e.row]}getCellTableBorder(e){let t=this.getters.getTable(e);if(t)return this.tableStyles[e.sheetId][t.id]().borders[e.col]?.[e.row]}computeTableStyle(e,t){return xt(()=>{let n=this.getters.getTableStyle(t.config.styleId),r=this.getTableMetaData(e,t);if(!r)return{borders:{},styles:{}};let{tableMetaData:i,config:a}=r,o=DM(a,n,i),s=this.getTableMapping(e,t),c={borders:{},styles:{}};for(let e=0;e<i.numberOfCols;e++){let t=s.colMapping[e];c.borders[t]={},c.styles[t]={};for(let n=0;n<i.numberOfRows;n++){let r=s.rowMapping[n];c.borders[t][r]=o.borders[e][n],c.styles[t][r]=o.styles[e][n]}}return c})}getTableMetaData(e,t){let{config:n,numberOfCols:r,numberOfRows:i}=this.getTableRuntimeConfig(e,t);if(!t.isPivotTable)return{tableMetaData:{numberOfCols:r,numberOfRows:i,mode:`table`},config:n};let a={sheetId:e,col:t.range.zone.left,row:t.range.zone.top},o=this.getters.getPivotStyleAtPosition(a);if(!o)throw Error(`No dynamic pivot info found at pivot table position`);let s=this.getters.getPivot(o.pivotId);if(!s.isValid())return;let c=o.pivotStyle,l=s.getExpandedTableStructure().getNumberOfRowGroupBys(),u=s.getCollapsedTableStructure(),d=u.getPivotCells(c),f=new Set,p=new Set,m=new Set,h=u.getNumberOfRowGroupBys();if(c.tabularForm){let n=0;for(let r=0;r<h;r++){if(this.getters.isColHidden(e,r+t.range.zone.left)){n++;continue}r===0&&l>1?f.add(0):r%2==1?p.add(r-n):r%2==0&&m.add(r-n)}}else{let n=0;for(let r=0;r<d[0].length;r++){if(this.getters.isRowHidden(e,r+t.range.zone.top)){n++;continue}let i=d[0][r];i.type!==`HEADER`||i.domain.length===0||(i.domain.length===1&&l>1?f.add(r-n):i.domain.length%2==0&&l>i.domain.length?p.add(r-n):i.domain.length%2==1&&l>i.domain.length&&m.add(r-n))}}return{tableMetaData:{mode:`pivot`,numberOfCols:r,numberOfRows:i,mainSubHeaderRows:f,firstAlternatingSubHeaderIndexes:p,secondAlternatingSubHeaderIndexes:m,measureRow:n.numberOfHeaders&&c.displayMeasuresRow&&!this.getters.isRowHidden(e,n.numberOfHeaders-1+t.range.zone.top)?n.numberOfHeaders-1:void 0,isTabular:c.tabularForm},config:n}}getTableRuntimeConfig(e,t){let n=t.range.zone,r={...t.config},i=n.right-n.left+1,a=n.bottom-n.top+1;for(let i=n.top;i<=n.bottom;i++)this.getters.isRowHidden(e,i)&&(a--,i-n.top<t.config.numberOfHeaders&&(r.numberOfHeaders--,r.numberOfHeaders<0&&(r.numberOfHeaders=0)),i===n.bottom&&(r.totalRow=!1));for(let t=n.left;t<=n.right;t++)this.getters.isColHidden(e,t)&&(i--,t===n.left&&(r.firstColumn=!1),t===n.right&&(r.lastColumn=!1));return{config:r,numberOfCols:i,numberOfRows:a}}getTableMapping(e,t){let n={},r={},i=0,a=0,o=t.range.zone;for(let t=o.left;t<=o.right;t++)if(!this.getters.isColHidden(e,t)){n[i]=t,i++;for(let t=o.top;t<=o.bottom;t++)this.getters.isRowHidden(e,t)||(r[a]=t,a++)}return{colMapping:n,rowMapping:r}}};let uR=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`,`DELETE_CONTENT`]);function dR(e){return uR.has(e.type)}var fR=class extends KL{static getters=[`getCellComputedBorder`,`getCellComputedStyle`];styles=new tN;borders=new tN;handle(e){if(hu.has(e.type)||e.type===`UPDATE_CELL`||e.type===`SET_FORMATTING`||e.type===`CLEAR_FORMATTING`||e.type===`ADD_DATA_VALIDATION_RULE`||e.type===`REMOVE_DATA_VALIDATION_RULE`||e.type===`EVALUATE_CELLS`){this.styles=new tN,this.borders=new tN;return}if(dR(e)){`sheetId`in e?(this.styles.clearSheet(e.sheetId),this.borders.clearSheet(e.sheetId)):(this.styles=new tN,this.borders=new tN);return}if(vu.has(e.type)){this.styles=new tN;return}if(yu.has(e.type)){this.borders=new tN;return}}getCellComputedBorder(e){let t=this.borders.get(e);return t===void 0&&(t=this.computeCellBorder(e),this.borders.set(e,t)),t}getCellComputedStyle(e){let t=this.styles.get(e);return t===void 0&&(t=this.computeCellStyle(e),this.styles.set(e,t)),t}computeCellStyle(e){let t=this.getters.getEvaluatedCell(e),n=this.getComputedStyle(e);return t.link&&!n.textColor&&(n.textColor=ce),n}getComputedStyle(e){let t=this.getters.getCell(e),n=this.getters.getCellConditionalFormatStyle(e),r=this.getters.getCellTableStyle(e),i=this.getters.getDataValidationCellStyle(e);return{...Dt(r),...Dt(i),...Dt(t?.style),...Dt(n)}}exportForExcel(e){for(let t of e.sheets){let n={},r=[];for(let e in t.cells){let i={sheetId:t.id,...sn(e)},a=this.getters.getEvaluatedCell(i),o=this.getComputedStyle(i);if(!a.link||o.textColor)continue;let s=Object.keys(t.styles).find(t=>In(yn(e),yn(t)));s?(n[s]||(n[s]=[]),n[s].push(e)):r.push(e)}for(let[r,i]of Object.entries(n)){let n=t.styles[r];if(e.styles[n].textColor)continue;let a=e.styles[n],o=i.map(yn),s=cn([yn(r)],o);delete t.styles[r];for(let e of s)t.styles[wn(e)]=n;let c=od({...a,textColor:ce},e.styles);for(let e of i)t.styles[e]=c}for(let n of r){let r=this.getters.getCell({sheetId:t.id,...sn(n)});t.styles[n]=od({...r?.style,textColor:ce},e.styles)}}}computeCellBorder(e){let t=this.getters.getCellBorder(e)||{},n={...Dt(this.getters.getCellTableBorder(e)||{}),...Dt(t)};return gt(n)?null:n}},pR=class extends KL{static getters=[`hasBooleanValidationInZones`];handle(e){switch(e.type){case`TOGGLE_CHECKBOX`:this.toggleCheckbox(e.sheetId,e.target);break}}hasBooleanValidationInZones(e){let t=this.getters.getActiveSheetId();for(let n of e)for(let e=n.left;e<=n.right;e++)for(let r=n.top;r<=n.bottom;r++)if(this.getters.isCellValidCheckbox({col:e,row:r,sheetId:t}))return!0;return!1}toggleCheckbox(e,t){for(let n of t)for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++){let n={col:t,row:r,sheetId:e};if(this.getters.isCellValidCheckbox(n)){let e=this.getters.getEvaluatedCell(n).value?`FALSE`:`TRUE`;this.dispatch(`UPDATE_CELL`,{...n,content:e})}}}};function mR(e){let t=sc.get(e.type)?.(e),n=_R(e);if(!t&&!n)return;let r=t||gR(),i=n||(e=>e),a=hR(r.applyChange);return{applyChange:a,adaptRangeString:(e,t)=>wc(e,t,r),adaptFormulaString:(e,t)=>Sc(e,t,r,i),adaptCompiledFormula:e=>e.adaptCompiledFormula(a,i)}}function hR(e){return t=>{let n=e(t);return n.changeType!==`NONE`&&!Sn(n.range.zone)?{range:n.range,changeType:`REMOVE`}:n}}function gR(){return{applyChange:e=>({changeType:`NONE`,range:e}),sheetId:`ignoredSheetId`,sheetName:{old:`ignoredSheetName`,current:`ignoredSheetName`}}}function _R(e){if(e.type!==`UPDATE_NAMED_RANGE`)return;let t=e.oldRangeName.toLowerCase();return n=>n.toLowerCase()===t?e.newRangeName:n}let vR=new class extends A{addTransformation(e,t,n){this.content[e]||(this.content[e]=new Map);for(let r of t)this.content[e].set(r,n);return this}getTransformation(e,t){return this.content[t]&&this.content[t].get(e)}},yR=new class extends A{add(e,t){return super.add(e,t),this}replace(e,t){return super.replace(e,t),this}get(e){return this.content[e]}};vR.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],MR),vR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],MR),vR.addTransformation(`DELETE_SHEET`,[`MOVE_RANGES`],CR),vR.addTransformation(`DELETE_FIGURE`,[`UPDATE_FIGURE`,`UPDATE_CHART`,`UPDATE_CAROUSEL`],wR),vR.addTransformation(`DELETE_CHART`,[`UPDATE_CHART`],TR),vR.addTransformation(`DELETE_CHART`,[`UPDATE_CAROUSEL`],ER),vR.addTransformation(`CREATE_SHEET`,[`CREATE_SHEET`],DR),vR.addTransformation(`ADD_MERGE`,[`ADD_MERGE`,`REMOVE_MERGE`],OR),vR.addTransformation(`ADD_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],kR),vR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],kR),vR.addTransformation(`ADD_COLUMNS_ROWS`,[`UPDATE_TABLE`],AR),vR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`UPDATE_TABLE`],AR),vR.addTransformation(`REMOVE_TABLE_STYLE`,[`CREATE_TABLE`,`UPDATE_TABLE`],jR),vR.addTransformation(`ADD_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],NR),vR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],NR),vR.addTransformation(`REMOVE_PIVOT`,[`RENAME_PIVOT`,`DUPLICATE_PIVOT`,`INSERT_PIVOT`,`UPDATE_PIVOT`],SR),vR.addTransformation(`DELETE_SHEET`,[`ADD_PIVOT`,`UPDATE_PIVOT`],xR),vR.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],bR),vR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],bR),vR.addTransformation(`UPDATE_NAMED_RANGE`,[`UPDATE_NAMED_RANGE`,`DELETE_NAMED_RANGE`],PR);function bR(e,t){if(e.pivot.type!==`SPREADSHEET`||e.pivot.dataSet?.sheetId!==t.sheetId)return e;let n=sr(e.pivot.dataSet.zone,t),r=n?{...e.pivot.dataSet,zone:n}:void 0;return{...e,pivot:{...e.pivot,dataSet:r}}}function xR(e,t){return e.pivot.type===`SPREADSHEET`&&e.pivot.dataSet?.sheetId===t.sheetId?{...e,pivot:{...e.pivot,dataSet:void 0}}:e}function SR(e,t){if(e.pivotId!==t.pivotId)return e}function CR(e,t){let n=t.sheetId;if(!(e.targetSheetId===n||e.sheetId===n))return e}function wR(e,t){if(e.figureId!==t.figureId)return e}function TR(e,t){if(e.chartId!==t.chartId)return e}function ER(e,t){return{...e,definition:{...e.definition,items:e.definition.items.filter(e=>!(e.type===`chart`&&e.chartId===t.chartId))}}}function DR(e,t){return e.sheetId===t.sheetId&&(e={...e,sheetId:`${e.sheetId}~`}),e.name===t.name?{...e,name:e.name?.match(/\d+/)?e.name.replace(/\d+/,e=>(parseInt(e)+1).toString()):`${e.name}~`,position:e.position+1}:e}function OR(e,t){if(e.sheetId!==t.sheetId)return e;let n=[];for(let r of e.target)t.target.every(e=>!Nn(r,e))&&n.push(r);if(n.length)return{...e,target:n}}function kR(e,t){if(e.sheetId!==t.sheetId||(e.type===`FREEZE_COLUMNS`?`COL`:`ROW`)!==t.dimension)return e;let n=e.quantity;if(t.type===`REMOVE_COLUMNS_ROWS`){let e=[...t.elements].sort((e,t)=>t-e);for(let t of e)n>t&&n--}if(t.type===`ADD_COLUMNS_ROWS`){let e=t.position===`before`?t.base-1:t.base;n=n>e?n+t.quantity:n}return n>0?{...e,quantity:n}:void 0}function AR(e,t){if(e.sheetId!==t.sheetId)return e;let n=sr(e.zone,t);if(!n)return;let r=e.newTableRange?cr(e.newTableRange,t):void 0;return{...e,newTableRange:r,zone:n}}function jR(e,t){return e.config?.styleId===t.tableStyleId?{...e,config:{...e.config,styleId:BS.styleId}}:e}function MR(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n;if(t.type===`REMOVE_COLUMNS_ROWS`?n=_c(t.elements,[e.base])[0]:t.type===`ADD_COLUMNS_ROWS`&&(n=gc(Ct(t.position,t.base),t.quantity,[e.base])[0]),n!==void 0)return{...e,base:n}}function NR(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n=C(e.start,e.end+1),r=[];if(t.type===`REMOVE_COLUMNS_ROWS`?r=_c(t.elements,n):t.type===`ADD_COLUMNS_ROWS`&&(r=gc(Ct(t.position,t.base),t.quantity,n)),r.length!==0)return{...e,start:Math.min(...r),end:Math.max(...r)}}function PR(e,t){return t.newRangeName===t.oldRangeName?e:e.type===`DELETE_NAMED_RANGE`&&e.name===t.oldRangeName?{...e,name:t.newRangeName}:e.type===`UPDATE_NAMED_RANGE`&&e.oldRangeName===t.oldRangeName?{...e,oldRangeName:t.newRangeName}:e}function FR(e,{adaptFormulaString:t}){let n=e.content&&t(e.sheetId,e.content);return{...e,content:n}}yR.add(`UPDATE_CELL`,FR);function IR(e,{adaptRangeString:t,adaptFormulaString:n}){let r=e.cf.rule;if(e={...e,cf:{...e.cf}},r.type===`CellIsRule`)e.cf.rule={...r,values:r.values.map(t=>n(e.sheetId,t))};else if(r.type===`ColorScaleRule`){let{minimum:t,maximum:i,midpoint:a}=r;e.cf.rule={...r,minimum:{...t,value:t.value&&n(e.sheetId,t.value)},maximum:{...i,value:i.value&&n(e.sheetId,i.value)},midpoint:a?{...a,value:n(e.sheetId,a.value)}:void 0}}else if(r.type===`IconSetRule`){let{upperInflectionPoint:t,lowerInflectionPoint:i}=r;e.cf.rule={...r,upperInflectionPoint:{...t,value:n(e.sheetId,t.value)},lowerInflectionPoint:{...i,value:n(e.sheetId,i.value)}}}else r.type===`DataBarRule`&&(e.cf.rule={...r,rangeValues:r.rangeValues?t(e.sheetId,r.rangeValues).range:void 0});return e}yR.add(`ADD_CONDITIONAL_FORMAT`,IR);function LR(e,{adaptFormulaString:t}){return e={...e,rule:{...e.rule,criterion:{...e.rule.criterion}}},e.rule.criterion.values=e.rule.criterion.values.map(n=>t(e.sheetId,n)),e}yR.add(`ADD_DATA_VALIDATION_RULE`,LR);function RR(e,{adaptFormulaString:t}){return e=x(e),e.pivot.measures.map(e=>{e.computedBy&&(e.computedBy.formula=t(e.computedBy.sheetId,e.computedBy.formula))}),e}yR.add(`ADD_PIVOT`,RR),yR.add(`UPDATE_PIVOT`,RR),yR.add(`CREATE_CHART`,zR),yR.add(`UPDATE_CHART`,zR);function zR(e,t){return{...e,definition:yO.transformDefinition(e.sheetId,e.definition,t)}}let BR=[{match:lu,fn:GR},{match:du,fn:KR},{match:mu,fn:qR},{match:pu,fn:XR},{match:uu,fn:YR},{match:fu,fn:JR}];function VR(e,t){let n=vR.getTransformation(e.type,t.type),r=n?n(e,t):WR(e,t);return r&&HR(r,t)}function HR(e,t){let n=yR.get(e.type);if(!n)return e;let r=mR(t);return r?n(e,r):e}function UR(e,t){let n=[...e],r=new Set(vR.getKeys());for(let e of t)(r.has(e.type)||sc.contains(e.type))&&(n=n.reduce((t,n)=>{let r=VR(n,e);return r&&t.push(r),t},[]));return n}function WR(e,t){for(let{match:n,fn:r}of BR)if(n(e)){let n=r(e,t);if(n===`SKIP_TRANSFORMATION`)continue;if(n===`IGNORE_COMMAND`)return;e=n}return e}function GR(e,t){if(!(`sheetId`in t))return e;let n=t.type===`DELETE_SHEET`&&t.sheetId,r=t.type===`LOCK_SHEET`&&t.sheetId;return e.sheetId===n||e.sheetId===r?`IGNORE_COMMAND`:e.type===`CREATE_SHEET`||t.type===`CREATE_SHEET`||e.sheetId!==t.sheetId?e:`SKIP_TRANSFORMATION`}function KR(e,t){let n=GR(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=[];for(let n of e.target){let e=sr(n,t);e&&r.push(e)}return r.length?{...e,target:r}:`IGNORE_COMMAND`}function qR(e,t){let n=GR(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=sr(e.zone,t);return r?{...e,zone:r}:`IGNORE_COMMAND`}function JR(e,t){if(!(`sheetId`in t))return e;let n=e.ranges.map(e=>cr(e,t)).filter(w);return n.length?{...e,ranges:n}:`IGNORE_COMMAND`}function YR(e,t){let n=GR(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;if(t.type!==`ADD_COLUMNS_ROWS`&&t.type!==`REMOVE_COLUMNS_ROWS`)return`SKIP_TRANSFORMATION`;if(t.dimension!==e.dimension)return e;let r=[];return t.type===`REMOVE_COLUMNS_ROWS`?r=_c(t.elements,e.elements):t.type===`ADD_COLUMNS_ROWS`&&(r=gc(Ct(t.position,t.base),t.quantity,e.elements)),r.length===0?`IGNORE_COMMAND`:{...e,elements:r}}function XR(e,t){let n=GR(e,t);return n===`SKIP_TRANSFORMATION`?t.type===`ADD_COLUMNS_ROWS`||t.type===`REMOVE_COLUMNS_ROWS`?ZR(e,t):t.type===`ADD_MERGE`?QR(e,t):`SKIP_TRANSFORMATION`:n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e}function ZR(e,t){let n=t.dimension===`COL`?`col`:`row`,r=e[n];if(t.type===`REMOVE_COLUMNS_ROWS`){let e=[...t.elements].sort((e,t)=>t-e);if(e.includes(r))return`IGNORE_COMMAND`;for(let t of e)r>=t&&r--}return t.type===`ADD_COLUMNS_ROWS`&&(r>t.base||r===t.base&&t.position===`before`)&&(r+=t.quantity),{...e,[n]:r}}function QR(e,t){for(let n of t.target)if(!(e.col===n.left&&e.row===n.top)&&Fn(e.col,e.row,n))return`IGNORE_COMMAND`;return e}var $R=class{rootCommand;timestamp;id;clientId;_commands=[];_changes=[];constructor(e,t,n,r,i,a){this.rootCommand=r,this.timestamp=a,this.id=e,this.clientId=t,this._commands=[...n],this._changes=i?[...i]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}},ez=class extends Error{},tz=class extends lr{revisions;transportService;serverRevisionId;commandSquisher;clients={};clientId=`local`;pendingMessages=[];awaitingClientPosition;waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;uuidGenerator=new Rd;lastLocalOperation;constructor(e,t,n=ke,r){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=n,this.commandSquisher=r}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,n){if(!t.length||!n.length||!this.canApplyOptimisticUpdate())return;let r=new $R(this.uuidGenerator.uuidv4(),this.clientId,t,e,n,Date.now());this.revisions.append(r.id,r),e.type!==`REQUEST_REDO`&&(this.lastLocalOperation=r),this.trigger(`new-local-state-update`,{id:r.id}),this.sendUpdateMessage({type:`REMOTE_REVISION`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:r.id,clientId:r.clientId,commands:r.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_UNDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_REDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}join(e){e?(this.clients[e.id]=e,this.clientId=e.id):(this.clients.local={id:`local`,name:`local`},this.clientId=`local`),this.transportService.onNewMessage(this.clientId,this.onMessageReceived.bind(this)),this.awaitingClientPosition&&=(this.move(this.awaitingClientPosition),void 0)}loadInitialMessages(e){let t=performance.now(),n=e.reduce((e,t)=>e+(t.type===`REMOTE_REVISION`?t.commands.length:1),0);this.isReplayingInitialRevisions=!0;for(let t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1,console.debug(`Replayed`,n,`commands in`,performance.now()-t,`ms`)}async leave(e){e&&Object.keys(this.clients).length===1&&this.lastRevisionMessage&&this.lastRevisionMessage?.type!==`SNAPSHOT_CREATED`&&await this.snapshot(e()),delete this.clients[this.clientId],this.transportService.leave(this.clientId),await this.sendToTransport({type:`CLIENT_LEFT`,clientId:this.clientId,version:1})}async snapshot(e){if(this.pendingMessages.length!==0)return;let t=this.uuidGenerator.uuidv4();await this.sendToTransport({type:`SNAPSHOT`,nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getCurrentClient(){return this.getClient(this.clientId)}getClient(e){let t=this.clients[e];if(!t)throw new ez(`The client left the session`);return t}getConnectedClients(){return new Set(Object.values(this.clients).filter(w))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return this.pendingMessages.length===0}getLastLocalNonEmptyRevision(){return this.lastLocalOperation}move(e){if(!this.clients[this.clientId]){this.awaitingClientPosition=e;return}let t=this.clients[this.clientId]?.position;if(t?.col===e.col&&t.row===e.row&&t.sheetId===e.sheetId)return;let n=t?`CLIENT_MOVED`:`CLIENT_JOINED`,r=this.getCurrentClient();this.clients[this.clientId]={...r,position:e},this.sendToTransport({type:n,version:1,client:{...r,position:e}}).then(()=>{this.pendingMessages.length>0&&!this.waitingAck&&this.sendPendingMessage()})}onMessageReceived(e){if(!this.isAlreadyProcessed(e)){if(this.isWrongServerRevisionId(e)){this.trigger(`unexpected-revision-id`);return}switch(e.type){case`CLIENT_MOVED`:this.onClientMoved(e);break;case`CLIENT_JOINED`:this.onClientJoined(e);break;case`CLIENT_LEFT`:this.onClientLeft(e);break;case`REVISION_REDONE`:this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger(`revision-redone`,{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case`REVISION_UNDONE`:this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger(`revision-undone`,{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case`REMOTE_REVISION`:let{clientId:t,timestamp:n}=e,r=this.commandSquisher.unsquish(e.commands),i=new $R(e.nextRevisionId,t,r,void 0,void 0,n);if(i.clientId!==this.clientId){this.revisions.insert(i.id,i,e.serverRevisionId);let t=this.pendingMessages.filter(e=>e.type===`REMOTE_REVISION`).map(e=>e.commands).flat();this.trigger(`remote-revision-received`,{commands:UR(r,t)})}break;case`SNAPSHOT_CREATED`:{let t=new $R(e.nextRevisionId,`server`,[],void 0,void 0,Date.now());this.revisions.insert(t.id,t,e.serverRevisionId),this.dropPendingHistoryMessages(),this.trigger(`snapshot`),this.lastLocalOperation=void 0;break}}this.acknowledge(e),this.trigger(`collaborative-event-received`)}}onClientMoved(e){e.client.id!==this.clientId&&(this.clients[e.client.id]=e.client)}onClientJoined(e){if(e.client.id!==this.clientId){this.clients[e.client.id]=e.client;let t=this.clients[this.clientId];if(t){let{position:e}=t;e&&this.sendToTransport({type:`CLIENT_MOVED`,version:1,client:{...t,position:e}})}}}onClientLeft(e){e.clientId!==this.clientId&&delete this.clients[e.clientId]}sendUpdateMessage(e){this.pendingMessages.push(e),!this.waitingAck&&this.sendPendingMessage()}async sendToTransport(e){return this.transportService.sendMessage(e)}sendPendingMessage(){let e=this.pendingMessages[0];if(e){if(e.type===`REMOTE_REVISION`){let t=this.revisions.get(e.nextRevisionId);t.commands.length===0&&(this.revisions.rebase(t.id),t=this.revisions.get(e.nextRevisionId)),e={...e,commands:this.commandSquisher.squish(t.commands)}}if(this.isReplayingInitialRevisions)throw Error(`Trying to send a new revision while replaying initial revision. This can lead to endless dispatches every time the spreadsheet is open.
117
- ${JSON.stringify(e)}`);this.waitingAck=!0,this.sendToTransport({...e,serverRevisionId:this.serverRevisionId}).catch(e=>{if(!(e instanceof ez))throw e.cause||e;this.waitingAck=!1})}}acknowledge(e){switch((e.type===`REVISION_UNDONE`||e.type===`REVISION_REDONE`)&&(this.waitingUndoRedoAck=!1),e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`SNAPSHOT_CREATED`:this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter(t=>t.nextRevisionId!==e.nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.lastRevisionMessage=e,this.sendPendingMessage();break;case`REVISION_UNDONE`:{this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter(t=>t.nextRevisionId!==e.nextRevisionId);let t=this.pendingMessages.findIndex(e=>e.type===`REMOTE_REVISION`);t!==-1&&this.revisions.rebase(this.pendingMessages[t].nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.sendPendingMessage();break}}}isAlreadyProcessed(e){if(e.type===`CLIENT_MOVED`&&e.client.id===this.clientId)return!0;switch(e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`REVISION_UNDONE`:case`SNAPSHOT_CREATED`:return this.processedRevisions.has(e.nextRevisionId);default:return!1}}isWrongServerRevisionId(e){switch(e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`REVISION_UNDONE`:case`SNAPSHOT_CREATED`:return e.serverRevisionId!==this.serverRevisionId;default:return!1}}dropPendingHistoryMessages(){this.waitingUndoRedoAck=!1,this.pendingMessages=this.pendingMessages.filter(({type:e})=>e!==`REVISION_REDONE`&&e!==`REVISION_UNDONE`)}},nz=class extends KL{static getters=[`getClientsToDisplay`,`getClient`,`getCurrentClient`,`getConnectedClients`,`isFullySynchronized`];static layers=[`Selection`];colors=new fi(12);session;constructor(e){super(e),this.session=e.session}isPositionValid(e){return e.row<this.getters.getNumberRows(e.sheetId)&&e.col<this.getters.getNumberCols(e.sheetId)}getClient(e){return this.session.getClient(e)}getCurrentClient(){return this.session.getCurrentClient()}getConnectedClients(){return[...this.session.getConnectedClients()].map(e=>({...e,color:this.colors.get(e.id)}))}isFullySynchronized(){return this.session.isFullySynchronized()}getClientsToDisplay(){try{this.getters.getCurrentClient()}catch(e){if(e instanceof ez)return[];throw e}let e=this.getters.getActiveSheetId(),t=[];for(let n of this.getters.getConnectedClients())n.id!==this.getters.getCurrentClient().id&&n.position&&n.position.sheetId===e&&this.isPositionValid(n.position)&&t.push({...n,position:n.position});return t}drawLayer(e){if(this.getters.isDashboard())return;let{ctx:t,thinLineWidth:n,viewports:r,sheetId:i}=e;for(let e of this.getClientsToDisplay()){let{row:a,col:o}=e.position,s=this.getters.expandZone(i,{top:a,bottom:a,left:o,right:o}),{x:c,y:l,width:u,height:d}=r.getVisibleRect(i,s);if(u<=0||d<=0)continue;let f=e.color;t.fillStyle=`${f}10`,t.lineWidth=4*n,t.strokeStyle=f,t.globalCompositeOperation=`multiply`,t.fillRect(c,l,u,d),t.globalCompositeOperation=`source-over`,t.strokeRect(c,l,u,d),t.font=`bold ${Ee+1}px ${De}`}}},rz=class extends KL{handle(e){switch(e.type){case`ADD_DATA_VALIDATION_RULE`:if(e.rule.criterion.type===`isBoolean`){let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e));for(let e of rc(t)){let t=this.getters.getCell(e),n=this.getters.getEvaluatedCell(e);if(!t?.isFormula&&!t?.content)this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`});else if((t?.isFormula||t?.content)&&n.type===`empty`){let n;if(t.isFormula){let r=this.getters.evaluateCompiledFormula(e.sheetId,t.compiledFormula);n=(Je(r)?r[0][0]:r)?.toString()}else n=t.content;(!n||!at(n))&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}else n.type!==`boolean`&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}}}}},iz=class extends KL{static getters=[`dynamicTranslate`];dynamicTranslate(e){return e}},az=class extends KL{handle(e){switch(e.type){case`SET_DECIMAL`:this.setDecimal(e.sheetId,e.target,e.step);break;case`SET_FORMATTING_WITH_PIVOT`:this.setContextualFormat(e.sheetId,e.target,e.format);break}}setContextualFormat(e,t,n){let r=[],i={};for(let n of cn(t))for(let t=n.left;t<=n.right;t++)for(let a=n.top;a<=n.bottom;a++){let n={sheetId:e,col:t,row:a},o=this.getters.getPivotCellFromPosition(n);if(this.isSpilledPivotValueFormula(n,o)){r.push(n);let e=this.getters.getPivotIdFromPosition(n)||``;i[e]??=new Set,i[e].add(o.measure)}}let a=cn(r.map(D));for(let e in i){let t=i[e],r=this.getters.getPivotCoreDefinition(e);this.dispatch(`UPDATE_PIVOT`,{pivotId:e,pivot:{...r,measures:r.measures.map(e=>t.has(e.id)?{...e,format:n}:e)}})}this.dispatch(`SET_FORMATTING`,{sheetId:e,target:a,format:``}),this.dispatch(`SET_FORMATTING`,{sheetId:e,target:cn(t,a),format:n})}isSpilledPivotValueFormula(e,t){let n=this.getters.getCell(e);return t.type===`VALUE`&&!n?.isFormula}setDecimal(e,t,n){let r={};for(let i of cn(t))for(let t of Bn(i)){let i=this.getCellNumberFormat({sheetId:e,...t});if(i!==void 0){let e=$l(i,n);r[e]=r[e]||[],r[e].push(t)}}for(let t in r){let n=cn(r[t].map(e=>D(e)));this.setContextualFormat(e,n,t)}}getCellNumberFormat(e){for(let t of[e]){let e=this.getters.getEvaluatedCell(t);if(e.type===`number`&&!(e.format&&Il(e.format)))return e.format||Bl(e.value)}}},oz=class extends KL{static getters=[`getGeoJsonFeatures`,`geoFeatureNameToId`,`getGeoChartAvailableRegions`,`getAvailableChartRegions`];geoJsonService;geoJsonCache={};initialRegions={};constructor(e){super(e),this.geoJsonService=e.external.geoJsonService}handle(e){switch(e.type){case`START`:for(let e of this.getters.getSheetIds())for(let t of this.getters.getChartIds(e))this.trackInitialRegion(t);break;case`CREATE_CHART`:this.trackInitialRegion(e.chartId);break;case`UPDATE_CHART_REGION`:{let t=this.getters.getChart(e.chartId),n=this.getters.getChartDefinition(e.chartId);if(!t||n.type!==`geo`)break;this.dispatch(`UPDATE_CHART`,{chartId:e.chartId,sheetId:t.sheetId,figureId:this.getters.getFigureIdFromChartId(e.chartId),definition:{...n,region:e.region}});break}}}trackInitialRegion(e){let t=this.getters.getChartDefinition(e);if(t?.type===`geo`){let n=this.getGeoChartAvailableRegions();this.initialRegions[e]=t.region||n[0]?.id||``}}getGeoChartAvailableRegions(){return this.geoJsonService?this.geoJsonService.getAvailableRegions()||[]:(console.error(`No geoJsonService provided to the model`),[])}getAvailableChartRegions(e){if(!this.geoJsonService)return[];let t=this.getters.getChartDefinition(e);if(!t||t.type!==`geo`)return[];let n=this.initialRegions[e];return n&&this.geoJsonService.getAlternativeRegions?.(n)||[]}getGeoJsonFeatures(e){if(!this.geoJsonService){console.error(`No geoJsonService provided to the model`);return}let t=this.geoJsonCache[e];if(!(t instanceof Promise)){if(t!==void 0)return t??void 0;this.geoJsonCache[e]=new Promise(async t=>{let n=await this.geoJsonService?.getTopoJson(e);this.geoJsonCache[e]=this.convertToGeoJson(n),this.dispatch(`EVALUATE_CHARTS`),t()})}}geoFeatureNameToId(e,t){if(!this.geoJsonService){console.error(`No geoJsonService provided to the model`);return}return this.geoJsonService.geoFeatureNameToId(e,t)}convertToGeoJson(e){if(!e)return null;if(e.type===`Topology`){let t=globalThis.ChartGeo.topojson.feature(e,Object.values(e.objects)[0]);return t.type===`FeatureCollection`?t.features:[t]}else if(e.type===`FeatureCollection`)return e.features;throw Error(`Invalid TopoJSON`)}},sz=class extends KL{static getters=[`getNextVisibleCellPosition`,`findVisibleHeader`,`findLastVisibleColRowIndex`,`findFirstVisibleColRowIndex`,`isRowHidden`,`isColHidden`,`isHeaderHidden`];isRowHidden(e,t){return this.getters.isRowHiddenByUser(e,t)||this.getters.isRowFiltered(e,t)}isColHidden(e,t){return this.getters.isColHiddenByUser(e,t)}isHeaderHidden(e,t,n){return t===`COL`?this.isColHidden(e,n):this.isRowHidden(e,n)}getNextVisibleCellPosition({sheetId:e,col:t,row:n}){return{sheetId:e,col:this.findVisibleHeader(e,`COL`,t,this.getters.getNumberCols(e)-1),row:this.findVisibleHeader(e,`ROW`,n,this.getters.getNumberRows(e)-1)}}findVisibleHeader(e,t,n,r){if(n<=r){for(let i=n;i<=r;i++)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}if(n>r){for(let i=n;i>=r;i--)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}}findLastVisibleColRowIndex(e,t,{last:n,first:r}){return C(n,r,-1).find(n=>!this.isHeaderHidden(e,t,n))||r}findFirstVisibleColRowIndex(e,t){let n=this.getters.getNumberHeaders(e,t);for(let r=0;r<n;r++)if(t===`COL`&&!this.isColHidden(e,r)||t===`ROW`&&!this.isRowHidden(e,r))return r}exportForExcel(e){for(let t of e.sheets)for(let[e,n]of Object.entries(t.rows))n.isHidden=this.isRowHidden(t.id,Number(e))}},cz=class extends KL{static getters=[];allowDispatch(e){switch(e.type){case`DUPLICATE_PIVOT_IN_NEW_SHEET`:if(!this.getters.isExistingPivot(e.pivotId))return`PivotIdNotFound`;if(!this.getters.getPivot(e.pivotId).isValid())return`PivotInError`;break}return`Success`}handle(e){switch(e.type){case`INSERT_NEW_PIVOT`:this.insertNewPivot(e.pivotId,e.newSheetId);break;case`DUPLICATE_PIVOT_IN_NEW_SHEET`:this.duplicatePivotInNewSheet(e.pivotId,e.newPivotId,e.newSheetId);break;case`INSERT_PIVOT_WITH_TABLE`:this.insertPivotWithTable(e.sheetId,e.col,e.row,e.pivotId,e.table,e.pivotMode);break;case`SPLIT_PIVOT_FORMULA`:this.splitPivotFormula(e.sheetId,e.col,e.row,e.pivotId)}}insertNewPivot(e,t){Xn(this.getters.getSelectedZone())===1&&this.selection.selectTableAroundSelection();let n=this.getters.getActiveSheetId();this.dispatch(`ADD_PIVOT`,{pivotId:e,pivot:{dataSet:{zone:this.getters.getSelectedZone(),sheetId:n},columns:[],rows:[],measures:[],name:j(`New pivot`),type:`SPREADSHEET`,style:{tableStyleId:Ve}}});let r=this.getters.getSheetIds().findIndex(e=>e===n)+1,i=this.getters.getPivotFormulaId(e);this.dispatch(`CREATE_SHEET`,{sheetId:t,name:j(`Pivot #%(formulaId)s`,{formulaId:i}),position:r}),this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:n,sheetIdTo:t});let a=this.getters.getPivot(e);this.insertPivotWithTable(t,0,0,e,a.getCollapsedTableStructure().export(),`dynamic`)}duplicatePivotInNewSheet(e,t,n){this.dispatch(`DUPLICATE_PIVOT`,{pivotId:e,newPivotId:t,duplicatedPivotName:j(`%s (copy)`,this.getters.getPivotCoreDefinition(e).name)});let r=this.getters.getActiveSheetId(),i=this.getters.getSheetIds().indexOf(r)+1,a=this.getters.getPivotFormulaId(t),o=this.getters.getPivotName(t);if(this.dispatch(`CREATE_SHEET`,{sheetId:n,name:this.getPivotDuplicateSheetName(j(`%(newPivotName)s (Pivot #%(formulaId)s)`,{newPivotName:o,formulaId:a})),position:i}).isSuccessful){this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:r,sheetIdTo:n});let i=this.getters.getPivot(e);this.insertPivotWithTable(n,0,0,t,i.getCollapsedTableStructure().export(),`dynamic`)}}getPivotDuplicateSheetName(e){let t=this.getters.getSheetIds().map(e=>this.getters.getSheetName(e));return Kt(nt(e),t)}insertPivotWithTable(e,t,n,r,i,a){let{cols:o,rows:s,measures:c,fieldsType:l}=i,u=new jj(o,s,c,l||{}),d=u.columns.length-1;if(this.resizeSheet(e,t,n,u),a===`dynamic`)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:n,content:`=PIVOT(${this.getters.getPivotFormulaId(r)})`});else{this.dispatch(`INSERT_PIVOT`,{sheetId:e,col:t,row:n,pivotId:r,table:u.export()});let i={left:t,right:t+u.getNumberOfDataColumns(),top:n,bottom:n+d+u.rows.length};this.dispatch(`CREATE_TABLE`,{tableType:`static`,sheetId:e,ranges:[this.getters.getRangeDataFromZone(e,i)],config:{...Be,numberOfHeaders:d}})}}resizeSheet(e,t,n,r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:s-l,position:`after`})}splitPivotFormula(e,t,n,r){let i={sheetId:e,col:t,row:n},a=this.getters.getSpreadZone(i),o=this.getters.getTable(i);if(!a)return;let s=this.getters.getPivotFormulaId(r),c=this.getters.getPivotStyleAtPosition(i);if(!c)return;let l={...c.pivotStyle,tabularForm:!1},u=this.getters.getPivot(r).getCollapsedTableStructure(),d=u.getPivotCells(l),{numberOfCols:f,numberOfRows:p}=u.getPivotTableDimensions(l);if(!(p===0||f===0)){for(let t of C(0,f))for(let n of C(0,p)){let r=d[t][n];if(r){let i={sheetId:e,col:a.left+t,row:a.top+n};this.dispatch(`UPDATE_CELL`,{...i,content:Eg(s,r)})}}if(this.getters.getCoreTable(i)&&this.dispatch(`REMOVE_TABLE`,{sheetId:e,target:[D(i)]}),o?.isPivotTable){let t=this.getters.getRangeDataFromZone(e,{left:a.left,right:a.left+f-1,top:a.top,bottom:a.top+p-1});this.dispatch(`CREATE_TABLE`,{tableType:`static`,sheetId:e,ranges:[t],config:{...o.config,styleId:xM(o.config.styleId)}})}}}};let lz=new A,uz=new A;function dz(e,t){if(t&&lz.contains(t.type))return lz.get(t.type)(e,t)}function fz(e,t,n){if(uz.contains(t.type))return uz.get(t.type)(e,t,n)}function pz(e){return!e||!e.rootCommand||typeof e.rootCommand!=`object`?!1:wu(e.rootCommand)?lz.contains(e.rootCommand.type):uz.contains(e.rootCommand.type)}function mz(e,t){if(!(!e.rootCommand||typeof e.rootCommand!=`object`))return wu(e.rootCommand)?dz(t,e.rootCommand):fz(t,e.rootCommand,e.commands)}var hz=class extends KL{static getters=[`canUndo`,`canRedo`];undoStack=[];redoStack=[];session;constructor(e){super(e),this.session=e.session,this.session.on(`new-local-state-update`,this,this.onNewLocalStateUpdate),this.session.on(`snapshot`,this,()=>{this.undoStack=[],this.redoStack=[]})}allowDispatch(e){switch(e.type){case`REQUEST_UNDO`:if(!this.canUndo())return`EmptyUndoStack`;break;case`REQUEST_REDO`:if(!this.canRedo())return`EmptyRedoStack`;break}return`Success`}handle(e){switch(e.type){case`REQUEST_UNDO`:case`REQUEST_REDO`:this.requestHistoryChange(e.type===`REQUEST_UNDO`?`UNDO`:`REDO`)}}finalize(){}requestHistoryChange(e){let t=e===`UNDO`?this.undoStack.pop():this.redoStack.pop();if(!t){let e=this.getPossibleRevisionToRepeat();if(!e)return;let t=mz(e,this.getters);if(!t)return;if(!Array.isArray(t)){this.dispatch(t.type,t);return}for(let e of t)this.dispatch(e.type,e);return}e===`UNDO`?(this.session.undo(t),this.redoStack.push(t)):(this.session.redo(t),this.undoStack.push(t))}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0?!0:pz(this.getPossibleRevisionToRepeat())}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}getPossibleRevisionToRepeat(){return this.session.getLastLocalNonEmptyRevision()}},gz=class extends KL{static getters=[`isCurrentSheetLocked`];allowDispatch(e){return Su.has(e.type)||this.getters.isDashboard()?`Success`:`sheetId`in e&&this.getters.isSheetLocked(e.sheetId)||!wu(e)&&this.isCurrentSheetLocked()?`SheetLocked`:`Success`}isCurrentSheetLocked(){return this.getters.isSheetLocked(this.getters.getActiveSheetId())}},_z=class{trackedValues=new Set;domainToArray(e){return e.flatMap(e=>[e.field,L(e.value)])}isValuePresent(e,t){let n=JSON.stringify({measure:e,domain:this.domainToArray(t)});return this.trackedValues.has(n)}isHeaderPresent(e){let t=JSON.stringify({domain:this.domainToArray(e)});return this.trackedValues.has(t)}trackValue(e,t){let n=JSON.stringify({measure:e,domain:this.domainToArray(t)});this.trackedValues.add(n)}trackHeader(e){let t=JSON.stringify({domain:this.domainToArray(e)});this.trackedValues.add(t)}},vz=class extends KL{static getters=[`getPivotPresenceTracker`];trackPresencePivotId;tracker;handle(e){switch(e.type){case`PIVOT_START_PRESENCE_TRACKING`:this.tracker=new _z,this.trackPresencePivotId=e.pivotId;break;case`PIVOT_STOP_PRESENCE_TRACKING`:this.trackPresencePivotId=void 0;break}}getPivotPresenceTracker(e){if(this.trackPresencePivotId===e){if(!this.tracker)throw Error(`Tracker not initialized`);return this.tracker}}};let yz=[`number`,`error`,`text`,`boolean`];function bz(e){let t=e===`asc`?1:-1;return(e,n)=>{if(e.type===`empty`)return n.type===`empty`?0:1;if(n.type===`empty`)return-1;let r=yz.indexOf(e.type)-yz.indexOf(n.type);return r===0&&(r=e.type===`text`||e.type===`error`?e.value.localeCompare(n.value):e.value-n.value),t*r}}function xz(e,t,n){let r=e.map((e,t)=>({index:t,type:e.type,value:e.value}));return(n?r.map(e=>e.type===`empty`?{...e,type:`number`,value:0}:e):r).sort(bz(t))}var Sz=class extends KL{allowDispatch(e){switch(e.type){case`SORT_CELLS`:return Fn(e.col,e.row,e.zone)?this.checkValidations(e,this.checkMerge,this.checkMergeSizes,this.checkArrayFormulaInSortZone):`InvalidSortAnchor`}return`Success`}handle(e){switch(e.type){case`SORT_CELLS`:this.sortZone(e.sheetId,e,e.zone,e.sortDirection,e.sortOptions||{});break}}checkMerge({sheetId:e,zone:t}){return this.getters.doesIntersectMerge(e,t)&&Bn(t).some(({col:t,row:n})=>!this.getters.isInMerge({sheetId:e,col:t,row:n}))?`InvalidSortZone`:`Success`}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return`Success`;let n=this.getters.getMerges(e).filter(e=>Nn(e,t)),r=Ln(n[0]),[i,a]=[r.numberOfCols,r.numberOfRows];return n.every(e=>{let[t,n]=[e.right-e.left+1,e.bottom-e.top+1];return t===i&&n===a})?`Success`:`InvalidSortZone`}checkArrayFormulaInSortZone({sheetId:e,zone:t}){return Bn(t).some(({col:t,row:n})=>{let r=this.getters.getArrayFormulaSpreadingOn({sheetId:e,col:t,row:n});return r&&!T(r,{sheetId:e,col:t,row:n})})?`SortZoneWithArrayFormulas`:`Success`}hasHeader(e,t){if(t[0].length===1)return!1;let n=t.map(t=>t.map(({col:t,row:n})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).type));return n[0][0]===`empty`&&(n=n.slice(1)),n.some(e=>e[0]===`empty`)?!1:!!n.some(e=>e[1]!==`empty`&&e[0]!==e[1])}sortZone(e,t,n,r,i){let[a,o]=this.mainCellsSteps(e,n),s=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,c=Object.assign({},n),l=this.mainCells(e,n);!i.sortHeaders&&this.hasHeader(e,l)&&(c.top+=o),l=this.mainCells(e,c);let u=l[s-c.left],d=xz(u.map(e=>this.getters.getEvaluatedCell(e)),r,!!i.emptyCellAsZero).map(e=>e.index),[f,p]=[l.length,l[0].length],m=[];for(let e=0;e<f;e++)for(let t=0;t<p;t++){let{col:n,row:r,sheetId:i}=l[e][d[t]],s=this.getters.getCell({sheetId:i,col:n,row:r}),u=c.left+e*a,f=c.top+t*o,p={sheetId:i,col:u,row:f,content:``};if(s){let e;if(s.isFormula){let t=this.getters.getCellPosition(s.id);e=this.getters.getTranslatedCellFormula(i,0,f-t.row,s.compiledFormula)}else e=s.content;p.style=s.style,p.content=e,p.format=s.format}m.push(p)}m.forEach(e=>this.dispatch(`UPDATE_CELL`,e))}mainCellsSteps(e,t){let n=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[n?n.right-n.left+1:1,n?n.bottom-n.top+1:1]}mainCells(e,t){let[n,r]=this.mainCellsSteps(e,t),i=[],a=C(t.left,t.right+1,n),o=C(t.top,t.bottom+1,r);for(let t of a){let n=[];i.push(n);for(let r of o)n.push({sheetId:e,col:t,row:r})}return i}},Cz=class extends KL{static getters=[`getAutomaticSeparator`];allowDispatch(e){switch(e.type){case`SPLIT_TEXT_INTO_COLUMNS`:return this.chainValidations(this.batchValidations(this.checkSingleColSelected,this.checkNonEmptySelector),this.batchValidations(this.checkNotOverwritingContent,this.checkSeparatorInSelection))(e)}return`Success`}handle(e){switch(e.type){case`SPLIT_TEXT_INTO_COLUMNS`:this.splitIntoColumns(e);break}}getAutomaticSeparator(){let e=this.getters.getSelectedCells();for(let t of e)if(t.value&&t.type===`text`){let e=this.getAutoSeparatorForString(t.value);if(e)return e}return` `}getAutoSeparatorForString(e){for(let t of[`
116
+ %s unique rows remain.`,e.toString(),t.toString()),sticky:!1})}checkSingleRangeSelected(){return this.getters.getSelectedZones().length===1?`Success`:`MoreThanOneRangeSelected`}checkNoMergeInZone(){let e=this.getters.getActiveSheetId(),t=this.getters.getSelectedZone();return this.getters.getMergesInZone(e,t).length>0?`WillRemoveExistingMerge`:`Success`}checkRangeContainsValues(e){let t=this.getters.getActiveSheetId(),n=this.getters.getSelectedZone();return e.hasHeader&&(n.top+=1),this.getters.getEvaluatedCellsInZone(t,n).every(e=>e.type===`empty`)?`EmptySelectedRange`:`Success`}checkNoColumnProvided(e){return e.columns.length===0?`NoColumnsProvided`:`Success`}checkColumnsIncludedInZone(e){let t=this.getters.getSelectedZone();return e.columns.some(e=>e<t.left||e>t.right)?`ColumnsNotIncludedInZone`:`Success`}checkColumnsAreUnique(e){return e.columns.length===new Set(e.columns).size?`Success`:`DuplicatesColumnsSelected`}trimWhitespace(){let e=cn(this.getters.getSelectedZones()),t=this.getters.getActiveSheetId(),n=0;for(let{col:r,row:i}of e.map(Bn).flat()){let e=this.getters.getCell({col:r,row:i,sheetId:t});if(!e)continue;let a=e.isFormula?e.compiledFormula.toFormulaString(this.getters):e.content,o=Rt(a);o!==a&&(n+=1,this.dispatch(`UPDATE_CELL`,{sheetId:t,col:r,row:i,content:o}))}let r=n?j(`Trimmed whitespace from %s cells.`,n):j(`No selected cells had whitespace trimmed.`);this.ui.notifyUI({type:`info`,text:r,sticky:!1})}};let JL=new A;JL.add(`ALPHANUMERIC_INCREMENT_MODIFIER`,{apply:(e,t)=>{e.current+=e.increment;let n=Math.abs(e.current).toString();n=`0`.repeat(Math.max(e.numberPostfixLength-n.length,0))+n;let r=`${e.prefix}${n}`;return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:{props:{content:r}}}}}).add(`INCREMENT_MODIFIER`,{apply:(e,t,n)=>{e.current+=e.increment;let r=e.current.toString(),i=n.getLocale(),a=H(e.current,{format:t.cell?.format,locale:i});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:a}}:void 0}}}).add(`DATE_INCREMENT_MODIFIER`,{apply:(e,t,n)=>{let r=z(e.current,n.getLocale());r.setFullYear(r.getFullYear()+e.increment.years||0),r.setMonth(r.getMonth()+e.increment.months||0),r.setDate(r.getDate()+e.increment.days||0);let i=ga(r);e.current=i;let a=n.getLocale(),o=H(i,{format:t.cell?.format,locale:a});return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:i.toString()},tooltip:i?{props:{content:o}}:void 0}}}).add(`COPY_MODIFIER`,{apply:(e,t,n)=>{let r=t.cell?.isFormula?t.cell?.compiledFormula.toFormulaString(n):t.cell?.content||``,i={locale:n.getLocale(),format:t.cell?.format},a={sheetId:t.sheetId,col:t.col,row:t.row};return{cellData:{border:t.border,style:t.cell&&t.cell.style,format:t.cell&&t.cell.format,content:r},tooltip:r?{props:{content:t.cell?Lu(t.cell,i,a).formattedValue:``}}:void 0}}}).add(`FORMULA_MODIFIER`,{apply:(e,t,n,r)=>{e.current+=e.increment;let i=0,a=0;switch(r){case`up`:i=0,a=-e.current;break;case`down`:i=0,a=e.current;break;case`left`:i=-e.current,a=0;break;case`right`:i=e.current,a=0;break}let o=t.cell;if(!o||!o.isFormula)return{cellData:{}};let s=t.sheetId,c=n.getTranslatedCellFormula(s,i,a,o.compiledFormula);return{cellData:{border:t.border,style:o.style,format:o.format,content:c},tooltip:c?{props:{content:c}}:void 0}}});let YL=new A,XL=/(\d+)$/,ZL=/^(.*\D+)/,QL=/^(.*\D+)(\d+)$/,$L=/^0*/;function eR(e,t,n){let r=[],i=!1;for(let a of t){a===e&&(i=!0);let t=a===void 0||a.isFormula?void 0:Lu(a,{locale:V,format:a.format});if(t&&n(t))r.push(t);else{if(i)return r;r=[]}}return r}function tR(e){let t=[],n=e[0];for(let r=1;r<e.length;r++){let i=e[r];t.push(i-n),n=i}return t.reduce((e,t)=>e+t,0)/t.length}function nR(e){let t=1;return e.length>=2&&(t=tR(e)*e.length),t}function rR(e){return e.length<2?e[0]||{years:0,months:0,days:0}:e.every(t=>t.years===e[0].years&&t.months===e[0].months&&t.days===e[0].days)?e[0]:void 0}function iR(e){if(e.length<2)return 1;let t=e.map(e=>z(e,V)),n=rR(aR(t));if(n===void 0)return;let r=Object.values(n).filter(e=>e!==0).length===1,i=Object.values(n).every(e=>e===0);if(!r||i){let n=t.map((e,n)=>{if(n===0)return 0;let r=t[n-1];return Math.floor(e.getTime())-Math.floor(r.getTime())}).slice(1);if(n.every(e=>e===n[0]))return e.length*(e[1]-e[0])}return{years:n.years*e.length,months:n.months*e.length,days:n.days*e.length}}YL.add(`simple_value_copy`,{condition:(e,t)=>t.length===1&&!e.isFormula&&!(e.format&&Il(e.format)),generateRule:()=>({type:`COPY_MODIFIER`}),sequence:10}).add(`increment_alphanumeric_value`,{condition:e=>!e.isFormula&&Lu(e,{locale:V}).type===`text`&&QL.test(e.content),generateRule:(e,t,n)=>{let r=parseInt(e.content.match(XL)[0]),i=e.content.match(ZL)[0],a=eR(e,t,e=>e.type===`text`&&QL.test(e.value)).filter(e=>i===(e.value??``).toString().match(ZL)[0]).map(e=>(e.value??``).toString().match(XL)[0]),o=a.reduce((e,t)=>{let n=t.match($L)[0].length;return n>e[1]?[t,n]:e},[a[0],0]),s=o[1]?o[0].length:0,c=nR(a.map(e=>parseInt(e)));return[`up`,`left`].includes(n)&&a.length===1&&(c=-c),{type:`ALPHANUMERIC_INCREMENT_MODIFIER`,prefix:i,current:r,increment:c,numberPostfixLength:s}},sequence:15}).add(`copy_text`,{condition:e=>!e.isFormula&&Lu(e,{locale:V}).type===`text`,generateRule:()=>({type:`COPY_MODIFIER`}),sequence:20}).add(`update_formula`,{condition:e=>e.isFormula,generateRule:(e,t)=>({type:`FORMULA_MODIFIER`,increment:t.length,current:0}),sequence:30}).add(`increment_dates`,{condition:(e,t)=>!e.isFormula&&Lu(e,{locale:V}).type===`number`&&!!e.format&&Il(e.format),generateRule:(e,t)=>{let n=iR(eR(e,t,e=>e.type===`number`&&!!e.format&&Il(e.format)).map(e=>Number(e.value)));if(n===void 0)return{type:`COPY_MODIFIER`};let r=Lu(e,{locale:V});return typeof n==`object`?{type:`DATE_INCREMENT_MODIFIER`,increment:n,current:r.type===`number`?r.value:0}:{type:`INCREMENT_MODIFIER`,increment:n,current:r.type===`number`?r.value:0}},sequence:25}).add(`increment_number`,{condition:e=>!e.isFormula&&Lu(e,{locale:V}).type===`number`,generateRule:(e,t,n)=>{let r=eR(e,t,e=>e.type===`number`&&!Il(e.format||``)).map(e=>Number(e.value)),i=nR(r);[`up`,`left`].includes(n)&&r.length===1&&(i=-i);let a=Lu(e,{locale:V});return{type:`INCREMENT_MODIFIER`,increment:i,current:a.type===`number`?a.value:0}},sequence:40});function aR(e){return e.length<2?[{years:0,months:0,days:0}]:e.map((t,n)=>{if(n===0)return{years:0,months:0,days:0};let r=P.fromTimestamp(e[n-1].getTime()),i=wa(r,t),a=Sa(r,t)%12;return r.setFullYear(r.getFullYear()+i),r.setMonth(r.getMonth()+a),{years:i,months:a,days:Ca(r,t)}}).slice(1)}var oR=class{cells;getters;index=0;direction;constructor(e,t,n){this.cells=e,this.getters=t,this.direction=n}next(){let e=this.cells[this.index++%this.cells.length],t=e.rule,{cellData:n,tooltip:r}=JL.get(t.type).apply(t,e.data,this.getters,this.direction);return{cellData:n,tooltip:r,origin:{col:e.data.col,row:e.data.row}}}},sR=class extends KL{static layers=[`Autofill`];static getters=[`getAutofillTooltip`];autofillZone;steps;lastCellSelected={};direction;tooltip;allowDispatch(e){switch(e.type){case`AUTOFILL_SELECT`:let t=this.getters.getActiveSheetId();return this.lastCellSelected.col=e.col===-1?this.lastCellSelected.col:S(e.col,0,this.getters.getNumberCols(t)),this.lastCellSelected.row=e.row===-1?this.lastCellSelected.row:S(e.row,0,this.getters.getNumberRows(t)),this.lastCellSelected.col!==void 0&&this.lastCellSelected.row!==void 0?`Success`:`InvalidAutofillSelection`}return`Success`}handle(e){switch(e.type){case`AUTOFILL`:this.autofill(!0);break;case`AUTOFILL_SELECT`:this.select(e.col,e.row);break;case`AUTOFILL_AUTO`:this.autofillAuto();break}}getAutofillTooltip(){return this.tooltip}autofill(e){if(!this.autofillZone||!this.steps||this.direction===void 0){this.tooltip=void 0;return}let t=this.getters.getSelectedZone(),n=this.autofillZone,r=[];switch(this.direction){case`down`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.top;n<=t.bottom;n++)i.push(E(e,n));let a=this.createGenerator(i);for(let t=n.top;t<=n.bottom;t++)r.push(this.computeNewCell(a,e,t))}break;case`up`:for(let e=t.left;e<=t.right;e++){let i=[];for(let n=t.bottom;n>=t.top;n--)i.push(E(e,n));let a=this.createGenerator(i);for(let t=n.bottom;t>=n.top;t--)r.push(this.computeNewCell(a,e,t))}break;case`left`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.right;n>=t.left;n--)i.push(E(n,e));let a=this.createGenerator(i);for(let t=n.right;t>=n.left;t--)r.push(this.computeNewCell(a,t,e))}break;case`right`:for(let e=t.top;e<=t.bottom;e++){let i=[];for(let n=t.left;n<=t.right;n++)i.push(E(n,e));let a=this.createGenerator(i);for(let t=n.left;t<=n.right;t++)r.push(this.computeNewCell(a,t,e))}break}if(e){let e={},t={},n={},i=this.getters.getActiveSheetId();for(let a of r)this.collectBordersData(a,e),this.autofillMerge(i,a),this.autofillCell(i,a),this.collectConditionalFormatsData(i,a,t),this.collectDataValidationsData(i,a,n);this.autofillBorders(i,e),this.autofillConditionalFormats(i,t),this.autofillDataValidations(i,n),this.autofillZone=void 0,this.selection.resizeAnchorZone(this.direction,this.steps),this.lastCellSelected={},this.direction=void 0,this.steps=0,this.tooltip=void 0}}collectBordersData(e,t){let n=JSON.stringify(e.border);n in t||(t[n]=[]),t[n].push(D({col:e.col,row:e.row}))}collectConditionalFormatsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s=this.getters.getRulesByCell(e,r,i),c=E(a,o);for(let e of s)e.id in n||(n[e.id]=[]),n[e.id].push(c)}collectDataValidationsData(e,t,n){let{originCol:r,originRow:i,col:a,row:o}=t,s={sheetId:e,col:r,row:i},c=this.getters.getValidationRuleForCell(s);c&&(c.id in n||(n[c.id]=[]),n[c.id].push(D({col:a,row:o})))}autofillCell(e,t){this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t.col,row:t.row,content:t.content||``,style:t.style||null,format:t.format||``}),this.dispatch(`AUTOFILL_CELL`,t)}autofillBorders(e,t){for(let n in t){let r=n===`undefined`?void 0:JSON.parse(n);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,border:r,target:cn(t[n])})}}autofillConditionalFormats(e,t){for(let n in t){let r=t[n],i=this.getters.getConditionalFormats(e).find(e=>e.id===n);if(!i)continue;let a=this.getters.getAdaptedCfRanges(e,i,r.map(yn),[]);a&&this.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{id:i.id,rule:i.rule,stopIfTrue:i.stopIfTrue},ranges:a,sheetId:e})}}autofillDataValidations(e,t){for(let n in t){let r=t[n],i=this.getters.getDataValidationRule(e,n);if(!i)continue;let a=cn(i.ranges.map(e=>e.zone).concat(r),[]);this.dispatch(`ADD_DATA_VALIDATION_RULE`,{rule:i,ranges:a.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e})}}select(e,t){let n=this.getters.getSelectedZone();if(Fn(e,t,n)){this.autofillZone=void 0;return}switch(this.direction=this.getDirection(e,t),this.direction){case`up`:this.saveZone(t,n.top-1,n.left,n.right),this.steps=n.top-t;break;case`down`:this.saveZone(n.bottom+1,t,n.left,n.right),this.steps=t-n.bottom;break;case`left`:this.saveZone(n.top,n.bottom,e,n.left-1),this.steps=n.left-e;break;case`right`:this.saveZone(n.top,n.bottom,n.right+1,e),this.steps=e-n.right;break}this.autofill(!1)}autofillAuto(){let e=this.getters.getActivePosition(),t=this.getters.getTable(e),n=t?t.range.zone.bottom:this.getAutofillAutoLastRow(),r=this.getters.getSelectedZone();for(let t=r.bottom+1;t<=n;t++)if(this.getters.getEvaluatedCell({...e,row:t}).type!==`empty`){n=t-1;break}n>r.bottom&&(this.select(e.col,n),this.autofill(!0))}getAutofillAutoLastRow(){let e=this.getters.getSelectedZone(),t=this.getters.getActiveSheetId(),n=e.left,r=e.bottom;if(n>0){let e={sheetId:t,col:n-1,row:r};for(;this.getters.getEvaluatedCell(e).type!==`empty`;)r+=1,e={sheetId:t,col:n-1,row:r}}if(r===e.bottom&&(n=e.right,n<=this.getters.getNumberCols(t))){let e={sheetId:t,col:n+1,row:r};for(;this.getters.getEvaluatedCell(e).type!==`empty`;)r+=1,e={sheetId:t,col:n+1,row:r}}return r-1}computeNewCell(e,t,n){let{cellData:r,tooltip:i,origin:a}=e.next(),{content:o,style:s,border:c,format:l}=r;return this.tooltip=i,{originCol:a.col,originRow:a.row,col:t,row:n,content:o,style:s,border:c,format:l}}getRule(e,t){let n=YL.getAll().sort((e,t)=>e.sequence-t.sequence).find(n=>n.condition(e,t));return n&&this.direction&&n.generateRule(e,t,this.direction)}createGenerator(e){let t=[],n=[],r=this.getters.getActiveSheetId();for(let t of e){let{col:e,row:i}=sn(t),a=this.getters.getCell({sheetId:r,col:e,row:i});n.push({col:e,row:i,cell:a,sheetId:r})}let i=n.map(e=>e.cell);for(let e of n){let n={type:`COPY_MODIFIER`};e&&e.cell&&(n=this.getRule(e.cell,i)||n);let r=this.getters.getCellBorder(e)??void 0;t.push({data:{...e,border:r},rule:n})}return new oR(t,this.getters,this.direction)}saveZone(e,t,n,r){this.autofillZone={top:e,bottom:t,left:n,right:r}}getDirection(e,t){let n=this.getters.getSelectedZone(),r={up:{number:n.top-t,value:`up`},down:{number:t-n.bottom,value:`down`},left:{number:n.left-e,value:`left`},right:{number:e-n.right,value:`right`}};if(Object.values(r).map(e=>+(e.number>0)).reduce((e,t)=>e+t)===1)return Object.values(r).find(e=>+(e.number>0)).value;let i=r.up.number>0?`up`:`down`,a=r.left.number>0?`left`:`right`;return Math.abs(r[i].number)>=Math.abs(r[a].number)?r[i].value:r[a].value}autofillMerge(e,t){let{originCol:n,originRow:r,col:i,row:a}=t,o={sheetId:e,col:i,row:a},s={sheetId:e,col:n,row:r};if(this.getters.isInMerge(o)&&!this.getters.isInMerge(s)){let t=this.getters.getMerge(o);t&&this.dispatch(`REMOVE_MERGE`,{sheetId:e,target:[t]})}let c=this.getters.getMerge(s);c?.left===n&&c?.top===r&&this.dispatch(`ADD_MERGE`,{sheetId:e,target:[{top:a,bottom:a+c.bottom-c.top,left:i,right:i+c.right-c.left}]})}drawLayer(e){if(!this.autofillZone)return;let{ctx:t,thinLineWidth:n,viewports:r,sheetId:i}=e,{x:a,y:o,width:s,height:c}=r.getVisibleRect(i,this.autofillZone);s>0&&c>0&&(t.strokeStyle=`black`,t.lineWidth=n,t.setLineDash([3]),t.strokeRect(a,o,s,c),t.setLineDash([]))}},cR=class extends KL{static getters=[`getAutomaticSums`];handle(e){switch(e.type){case`SUM_SELECTION`:let e=this.getters.getActiveSheetId(),{zones:t,anchor:n}=this.getters.getSelection();for(let r of t){let t=this.getAutomaticSums(e,r,n.cell);this.dispatchCellUpdates(e,t)}break}}getAutomaticSums(e,t,n){return this.shouldFindData(e,t)?this.sumAdjacentData(e,t,n):this.sumData(e,t)}sumData(e,t){let n=this.dimensionsToSum(e,t),r=this.sumDimensions(e,t,n).filter(({zone:t})=>!this.getters.isEmpty(e,t));return n.has(`ROW`)&&n.has(`COL`)&&r.push(this.sumTotal(t)),r}sumAdjacentData(e,t,n){let{col:r,row:i}=Fn(n.col,n.row,t)?n:{col:t.left,row:t.top},a=this.findAdjacentData(e,r,i);return a?this.getters.isSingleCellOrMerge(e,t)||Rn(kn(a,t))?[{position:{col:r,row:i},zone:a}]:this.sumDimensions(e,kn(a,t),this.transpose(this.dimensionsToSum(e,t))):[]}findAdjacentData(e,t,n){let r=this.getters.getSheet(e),i=this.getters.getMainCellPosition({sheetId:e,col:t,row:n}),a=this.findSuitableZoneToSum(r,i.col,i.row);if(a)return this.getters.expandZone(e,a)}findSuitableZoneToSum(e,t,n){let r=this.getters.getEvaluatedCell({sheetId:e.id,col:t,row:n-1}),i=this.getters.getEvaluatedCell({sheetId:e.id,col:t-1,row:n});if(this.isNumber(i)&&!this.isNumber(r))return this.findHorizontalZone(e,t,n);let a=this.findVerticalZone(e,t,n);if(this.isZoneValid(a))return a;let o=this.findHorizontalZone(e,t,n);if(this.isZoneValid(o))return o}findVerticalZone(e,t,n){let r={top:0,bottom:n-1,left:t,right:t},i=this.reduceZoneStart(e,r,r.bottom);return{...r,top:i}}findHorizontalZone(e,t,n){let r={top:n,bottom:n,left:0,right:t-1},i=this.reduceZoneStart(e,r,r.right);return{...r,left:i}}reduceZoneStart(e,t,n){let r=this.getters.getEvaluatedCellsInZone(e.id,t),i=C(n,-1,-1),a=Vt(i.filter(e=>r[e]&&!r[e].isAutoSummable)),o=rt(i.filter(e=>this.isNumber(r[e])))[0]||[];return Vt(o)<a?1/0:Ht(o)}shouldFindData(e,t){return this.getters.isEmpty(e,t)||this.getters.isSingleCellOrMerge(e,t)}isNumber(e){return e.type===`number`&&!(e.format&&Il(e.format))}isZoneValid(e){return e.bottom>=e.top&&e.right>=e.left}lastColIsEmpty(e,t){return this.getters.isEmpty(e,{...t,left:t.right})}lastRowIsEmpty(e,t){return this.getters.isEmpty(e,{...t,top:t.bottom})}dimensionsToSum(e,t){let n=new Set;return Rn(t)?(n.add(Ln(t).numberOfCols===1?`COL`:`ROW`),n):(this.lastColIsEmpty(e,t)&&n.add(`ROW`),this.lastRowIsEmpty(e,t)&&n.add(`COL`),n.size===0&&n.add(`COL`),n)}sumDimensions(e,t,n){return[...n.has(`COL`)?this.sumColumns(t,e):[],...n.has(`ROW`)?this.sumRows(t,e):[]]}sumTotal(e){let{bottom:t,right:n}=e;return{position:{col:n,row:t},zone:{...e,top:t,right:n-1}}}sumColumns(e,t){let n=this.nextEmptyRow(t,{...e,bottom:e.bottom-1});return e={...e,bottom:Math.min(e.bottom,n.bottom-1)},Bn(n).map(t=>({position:t,zone:{...e,right:t.col,left:t.col}}))}sumRows(e,t){let n=this.nextEmptyCol(t,{...e,right:e.right-1});return e={...e,right:Math.min(e.right,n.right-1)},Bn(n).map(t=>({position:t,zone:{...e,top:t.row,bottom:t.row}}))}dispatchCellUpdates(e,t){for(let n of t){let{col:t,row:r}=n.position;this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:r,content:`=SUM(${this.getters.zoneToXC(e,n.zone)})`})}}nextEmptyRow(e,t){let n=t.bottom+1,{left:r,right:i}=t;for(;!this.getters.isEmpty(e,{bottom:n,top:n,left:r,right:i});)n++;return{...t,top:n,bottom:n}}nextEmptyCol(e,t){let n=t.right+1,{top:r,bottom:i}=t;for(;!this.getters.isEmpty(e,{left:n,right:n,top:r,bottom:i});)n++;return{...t,left:n,right:n}}transpose(e){return new Set([...e.values()].map(e=>e===`COL`?`ROW`:`COL`))}},lR=class extends KL{static getters=[`getCellTableStyle`,`getCellTableBorder`];tableStyles={};handle(e){if(hu.has(e.type)||e.type===`UPDATE_CELL`&&(`content`in e||`format`in e)||e.type===`EVALUATE_CELLS`){this.tableStyles={};return}if(dR(e)){`sheetId`in e?delete this.tableStyles[e.sheetId]:this.tableStyles={};return}}finalize(){for(let e of this.getters.getSheetIds()){this.tableStyles[e]||(this.tableStyles[e]={});for(let t of this.getters.getTables(e))this.tableStyles[e][t.id]||(this.tableStyles[e][t.id]=this.computeTableStyle(e,t))}}getCellTableStyle(e){let t=this.getters.getTable(e);if(t)try{return this.tableStyles[e.sheetId][t.id]().styles[e.col]?.[e.row]}catch(e){if(F(e)||e instanceof N)return;throw e}}getCellTableBorder(e){let t=this.getters.getTable(e);if(t)try{return this.tableStyles[e.sheetId][t.id]().borders[e.col]?.[e.row]}catch(e){if(F(e)||e instanceof N)return;throw e}}computeTableStyle(e,t){return xt(()=>{let n=this.getters.getTableStyle(t.config.styleId),r=this.getTableMetaData(e,t);if(!r)return{borders:{},styles:{}};let{tableMetaData:i,config:a}=r,o=DM(a,n,i),s=this.getTableMapping(e,t),c={borders:{},styles:{}};for(let e=0;e<i.numberOfCols;e++){let t=s.colMapping[e];c.borders[t]={},c.styles[t]={};for(let n=0;n<i.numberOfRows;n++){let r=s.rowMapping[n];c.borders[t][r]=o.borders[e][n],c.styles[t][r]=o.styles[e][n]}}return c})}getTableMetaData(e,t){let{config:n,numberOfCols:r,numberOfRows:i}=this.getTableRuntimeConfig(e,t);if(!t.isPivotTable)return{tableMetaData:{numberOfCols:r,numberOfRows:i,mode:`table`},config:n};let a={sheetId:e,col:t.range.zone.left,row:t.range.zone.top},o=this.getters.getPivotStyleAtPosition(a);if(!o)throw Error(`No dynamic pivot info found at pivot table position`);let s=this.getters.getPivot(o.pivotId);if(!s.isValid())return;let c=o.pivotStyle,l=s.getExpandedTableStructure().getNumberOfRowGroupBys(),u=s.getCollapsedTableStructure(),d=u.getPivotCells(c),f=new Set,p=new Set,m=new Set,h=u.getNumberOfRowGroupBys();if(c.tabularForm){let n=0;for(let r=0;r<h;r++){if(this.getters.isColHidden(e,r+t.range.zone.left)){n++;continue}r===0&&l>1?f.add(0):r%2==1?p.add(r-n):r%2==0&&m.add(r-n)}}else{let n=0;for(let r=0;r<d[0].length;r++){if(this.getters.isRowHidden(e,r+t.range.zone.top)){n++;continue}let i=d[0][r];i.type!==`HEADER`||i.domain.length===0||(i.domain.length===1&&l>1?f.add(r-n):i.domain.length%2==0&&l>i.domain.length?p.add(r-n):i.domain.length%2==1&&l>i.domain.length&&m.add(r-n))}}return{tableMetaData:{mode:`pivot`,numberOfCols:r,numberOfRows:i,mainSubHeaderRows:f,firstAlternatingSubHeaderIndexes:p,secondAlternatingSubHeaderIndexes:m,measureRow:n.numberOfHeaders&&c.displayMeasuresRow&&!this.getters.isRowHidden(e,n.numberOfHeaders-1+t.range.zone.top)?n.numberOfHeaders-1:void 0,isTabular:c.tabularForm},config:n}}getTableRuntimeConfig(e,t){let n=t.range.zone,r={...t.config},i=n.right-n.left+1,a=n.bottom-n.top+1;for(let i=n.top;i<=n.bottom;i++)this.getters.isRowHidden(e,i)&&(a--,i-n.top<t.config.numberOfHeaders&&(r.numberOfHeaders--,r.numberOfHeaders<0&&(r.numberOfHeaders=0)),i===n.bottom&&(r.totalRow=!1));for(let t=n.left;t<=n.right;t++)this.getters.isColHidden(e,t)&&(i--,t===n.left&&(r.firstColumn=!1),t===n.right&&(r.lastColumn=!1));return{config:r,numberOfCols:i,numberOfRows:a}}getTableMapping(e,t){let n={},r={},i=0,a=0,o=t.range.zone;for(let t=o.left;t<=o.right;t++)if(!this.getters.isColHidden(e,t)){n[i]=t,i++;for(let t=o.top;t<=o.bottom;t++)this.getters.isRowHidden(e,t)||(r[a]=t,a++)}return{colMapping:n,rowMapping:r}}};let uR=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`,`DELETE_CONTENT`]);function dR(e){return uR.has(e.type)}var fR=class extends KL{static getters=[`getCellComputedBorder`,`getCellComputedStyle`];styles=new tN;borders=new tN;handle(e){if(hu.has(e.type)||e.type===`UPDATE_CELL`||e.type===`SET_FORMATTING`||e.type===`CLEAR_FORMATTING`||e.type===`ADD_DATA_VALIDATION_RULE`||e.type===`REMOVE_DATA_VALIDATION_RULE`||e.type===`EVALUATE_CELLS`){this.styles=new tN,this.borders=new tN;return}if(dR(e)){`sheetId`in e?(this.styles.clearSheet(e.sheetId),this.borders.clearSheet(e.sheetId)):(this.styles=new tN,this.borders=new tN);return}if(vu.has(e.type)){this.styles=new tN;return}if(yu.has(e.type)){this.borders=new tN;return}}getCellComputedBorder(e){let t=this.borders.get(e);return t===void 0&&(t=this.computeCellBorder(e),this.borders.set(e,t)),t}getCellComputedStyle(e){let t=this.styles.get(e);return t===void 0&&(t=this.computeCellStyle(e),this.styles.set(e,t)),t}computeCellStyle(e){let t=this.getters.getEvaluatedCell(e),n=this.getComputedStyle(e);return t.link&&!n.textColor&&(n.textColor=ce),n}getComputedStyle(e){let t=this.getters.getCell(e),n=this.getters.getCellConditionalFormatStyle(e),r=this.getters.getCellTableStyle(e),i=this.getters.getDataValidationCellStyle(e);return{...Dt(r),...Dt(i),...Dt(t?.style),...Dt(n)}}exportForExcel(e){for(let t of e.sheets){let n={},r=[];for(let e in t.cells){let i={sheetId:t.id,...sn(e)},a=this.getters.getEvaluatedCell(i),o=this.getComputedStyle(i);if(!a.link||o.textColor)continue;let s=Object.keys(t.styles).find(t=>In(yn(e),yn(t)));s?(n[s]||(n[s]=[]),n[s].push(e)):r.push(e)}for(let[r,i]of Object.entries(n)){let n=t.styles[r];if(e.styles[n].textColor)continue;let a=e.styles[n],o=i.map(yn),s=cn([yn(r)],o);delete t.styles[r];for(let e of s)t.styles[wn(e)]=n;let c=od({...a,textColor:ce},e.styles);for(let e of i)t.styles[e]=c}for(let n of r){let r=this.getters.getCell({sheetId:t.id,...sn(n)});t.styles[n]=od({...r?.style,textColor:ce},e.styles)}}}computeCellBorder(e){let t=this.getters.getCellBorder(e)||{},n={...Dt(this.getters.getCellTableBorder(e)||{}),...Dt(t)};return gt(n)?null:n}},pR=class extends KL{static getters=[`hasBooleanValidationInZones`];handle(e){switch(e.type){case`TOGGLE_CHECKBOX`:this.toggleCheckbox(e.sheetId,e.target);break}}hasBooleanValidationInZones(e){let t=this.getters.getActiveSheetId();for(let n of e)for(let e=n.left;e<=n.right;e++)for(let r=n.top;r<=n.bottom;r++)if(this.getters.isCellValidCheckbox({col:e,row:r,sheetId:t}))return!0;return!1}toggleCheckbox(e,t){for(let n of t)for(let t=n.left;t<=n.right;t++)for(let r=n.top;r<=n.bottom;r++){let n={col:t,row:r,sheetId:e};if(this.getters.isCellValidCheckbox(n)){let e=this.getters.getEvaluatedCell(n).value?`FALSE`:`TRUE`;this.dispatch(`UPDATE_CELL`,{...n,content:e})}}}};function mR(e){let t=sc.get(e.type)?.(e),n=_R(e);if(!t&&!n)return;let r=t||gR(),i=n||(e=>e),a=hR(r.applyChange);return{applyChange:a,adaptRangeString:(e,t)=>wc(e,t,r),adaptFormulaString:(e,t)=>Sc(e,t,r,i),adaptCompiledFormula:e=>e.adaptCompiledFormula(a,i)}}function hR(e){return t=>{let n=e(t);return n.changeType!==`NONE`&&!Sn(n.range.zone)?{range:n.range,changeType:`REMOVE`}:n}}function gR(){return{applyChange:e=>({changeType:`NONE`,range:e}),sheetId:`ignoredSheetId`,sheetName:{old:`ignoredSheetName`,current:`ignoredSheetName`}}}function _R(e){if(e.type!==`UPDATE_NAMED_RANGE`)return;let t=e.oldRangeName.toLowerCase();return n=>n.toLowerCase()===t?e.newRangeName:n}let vR=new class extends A{addTransformation(e,t,n){this.content[e]||(this.content[e]=new Map);for(let r of t)this.content[e].set(r,n);return this}getTransformation(e,t){return this.content[t]&&this.content[t].get(e)}},yR=new class extends A{add(e,t){return super.add(e,t),this}replace(e,t){return super.replace(e,t),this}get(e){return this.content[e]}};vR.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],MR),vR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_COLUMNS_ROWS`],MR),vR.addTransformation(`DELETE_SHEET`,[`MOVE_RANGES`],CR),vR.addTransformation(`DELETE_FIGURE`,[`UPDATE_FIGURE`,`UPDATE_CHART`,`UPDATE_CAROUSEL`],wR),vR.addTransformation(`DELETE_CHART`,[`UPDATE_CHART`],TR),vR.addTransformation(`DELETE_CHART`,[`UPDATE_CAROUSEL`],ER),vR.addTransformation(`CREATE_SHEET`,[`CREATE_SHEET`],DR),vR.addTransformation(`ADD_MERGE`,[`ADD_MERGE`,`REMOVE_MERGE`],OR),vR.addTransformation(`ADD_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],kR),vR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`FREEZE_COLUMNS`,`FREEZE_ROWS`],kR),vR.addTransformation(`ADD_COLUMNS_ROWS`,[`UPDATE_TABLE`],AR),vR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`UPDATE_TABLE`],AR),vR.addTransformation(`REMOVE_TABLE_STYLE`,[`CREATE_TABLE`,`UPDATE_TABLE`],jR),vR.addTransformation(`ADD_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],NR),vR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`GROUP_HEADERS`,`UNGROUP_HEADERS`,`FOLD_HEADER_GROUP`,`UNFOLD_HEADER_GROUP`],NR),vR.addTransformation(`REMOVE_PIVOT`,[`RENAME_PIVOT`,`DUPLICATE_PIVOT`,`INSERT_PIVOT`,`UPDATE_PIVOT`],SR),vR.addTransformation(`DELETE_SHEET`,[`ADD_PIVOT`,`UPDATE_PIVOT`],xR),vR.addTransformation(`ADD_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],bR),vR.addTransformation(`REMOVE_COLUMNS_ROWS`,[`ADD_PIVOT`,`UPDATE_PIVOT`],bR),vR.addTransformation(`UPDATE_NAMED_RANGE`,[`UPDATE_NAMED_RANGE`,`DELETE_NAMED_RANGE`],PR);function bR(e,t){if(e.pivot.type!==`SPREADSHEET`||e.pivot.dataSet?.sheetId!==t.sheetId)return e;let n=sr(e.pivot.dataSet.zone,t),r=n?{...e.pivot.dataSet,zone:n}:void 0;return{...e,pivot:{...e.pivot,dataSet:r}}}function xR(e,t){return e.pivot.type===`SPREADSHEET`&&e.pivot.dataSet?.sheetId===t.sheetId?{...e,pivot:{...e.pivot,dataSet:void 0}}:e}function SR(e,t){if(e.pivotId!==t.pivotId)return e}function CR(e,t){let n=t.sheetId;if(!(e.targetSheetId===n||e.sheetId===n))return e}function wR(e,t){if(e.figureId!==t.figureId)return e}function TR(e,t){if(e.chartId!==t.chartId)return e}function ER(e,t){return{...e,definition:{...e.definition,items:e.definition.items.filter(e=>!(e.type===`chart`&&e.chartId===t.chartId))}}}function DR(e,t){return e.sheetId===t.sheetId&&(e={...e,sheetId:`${e.sheetId}~`}),e.name===t.name?{...e,name:e.name?.match(/\d+/)?e.name.replace(/\d+/,e=>(parseInt(e)+1).toString()):`${e.name}~`,position:e.position+1}:e}function OR(e,t){if(e.sheetId!==t.sheetId)return e;let n=[];for(let r of e.target)t.target.every(e=>!Nn(r,e))&&n.push(r);if(n.length)return{...e,target:n}}function kR(e,t){if(e.sheetId!==t.sheetId||(e.type===`FREEZE_COLUMNS`?`COL`:`ROW`)!==t.dimension)return e;let n=e.quantity;if(t.type===`REMOVE_COLUMNS_ROWS`){let e=[...t.elements].sort((e,t)=>t-e);for(let t of e)n>t&&n--}if(t.type===`ADD_COLUMNS_ROWS`){let e=t.position===`before`?t.base-1:t.base;n=n>e?n+t.quantity:n}return n>0?{...e,quantity:n}:void 0}function AR(e,t){if(e.sheetId!==t.sheetId)return e;let n=sr(e.zone,t);if(!n)return;let r=e.newTableRange?cr(e.newTableRange,t):void 0;return{...e,newTableRange:r,zone:n}}function jR(e,t){return e.config?.styleId===t.tableStyleId?{...e,config:{...e.config,styleId:BS.styleId}}:e}function MR(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n;if(t.type===`REMOVE_COLUMNS_ROWS`?n=_c(t.elements,[e.base])[0]:t.type===`ADD_COLUMNS_ROWS`&&(n=gc(Ct(t.position,t.base),t.quantity,[e.base])[0]),n!==void 0)return{...e,base:n}}function NR(e,t){if(e.sheetId!==t.sheetId||e.dimension!==t.dimension)return e;let n=C(e.start,e.end+1),r=[];if(t.type===`REMOVE_COLUMNS_ROWS`?r=_c(t.elements,n):t.type===`ADD_COLUMNS_ROWS`&&(r=gc(Ct(t.position,t.base),t.quantity,n)),r.length!==0)return{...e,start:Math.min(...r),end:Math.max(...r)}}function PR(e,t){return t.newRangeName===t.oldRangeName?e:e.type===`DELETE_NAMED_RANGE`&&e.name===t.oldRangeName?{...e,name:t.newRangeName}:e.type===`UPDATE_NAMED_RANGE`&&e.oldRangeName===t.oldRangeName?{...e,oldRangeName:t.newRangeName}:e}function FR(e,{adaptFormulaString:t}){let n=e.content&&t(e.sheetId,e.content);return{...e,content:n}}yR.add(`UPDATE_CELL`,FR);function IR(e,{adaptRangeString:t,adaptFormulaString:n}){let r=e.cf.rule;if(e={...e,cf:{...e.cf}},r.type===`CellIsRule`)e.cf.rule={...r,values:r.values.map(t=>n(e.sheetId,t))};else if(r.type===`ColorScaleRule`){let{minimum:t,maximum:i,midpoint:a}=r;e.cf.rule={...r,minimum:{...t,value:t.value&&n(e.sheetId,t.value)},maximum:{...i,value:i.value&&n(e.sheetId,i.value)},midpoint:a?{...a,value:n(e.sheetId,a.value)}:void 0}}else if(r.type===`IconSetRule`){let{upperInflectionPoint:t,lowerInflectionPoint:i}=r;e.cf.rule={...r,upperInflectionPoint:{...t,value:n(e.sheetId,t.value)},lowerInflectionPoint:{...i,value:n(e.sheetId,i.value)}}}else r.type===`DataBarRule`&&(e.cf.rule={...r,rangeValues:r.rangeValues?t(e.sheetId,r.rangeValues).range:void 0});return e}yR.add(`ADD_CONDITIONAL_FORMAT`,IR);function LR(e,{adaptFormulaString:t}){return e={...e,rule:{...e.rule,criterion:{...e.rule.criterion}}},e.rule.criterion.values=e.rule.criterion.values.map(n=>t(e.sheetId,n)),e}yR.add(`ADD_DATA_VALIDATION_RULE`,LR);function RR(e,{adaptFormulaString:t}){return e=x(e),e.pivot.measures.map(e=>{e.computedBy&&(e.computedBy.formula=t(e.computedBy.sheetId,e.computedBy.formula))}),e}yR.add(`ADD_PIVOT`,RR),yR.add(`UPDATE_PIVOT`,RR),yR.add(`CREATE_CHART`,zR),yR.add(`UPDATE_CHART`,zR);function zR(e,t){return{...e,definition:yO.transformDefinition(e.sheetId,e.definition,t)}}let BR=[{match:lu,fn:GR},{match:du,fn:KR},{match:mu,fn:qR},{match:pu,fn:XR},{match:uu,fn:YR},{match:fu,fn:JR}];function VR(e,t){let n=vR.getTransformation(e.type,t.type),r=n?n(e,t):WR(e,t);return r&&HR(r,t)}function HR(e,t){let n=yR.get(e.type);if(!n)return e;let r=mR(t);return r?n(e,r):e}function UR(e,t){let n=[...e],r=new Set(vR.getKeys());for(let e of t)(r.has(e.type)||sc.contains(e.type))&&(n=n.reduce((t,n)=>{let r=VR(n,e);return r&&t.push(r),t},[]));return n}function WR(e,t){for(let{match:n,fn:r}of BR)if(n(e)){let n=r(e,t);if(n===`SKIP_TRANSFORMATION`)continue;if(n===`IGNORE_COMMAND`)return;e=n}return e}function GR(e,t){if(!(`sheetId`in t))return e;let n=t.type===`DELETE_SHEET`&&t.sheetId,r=t.type===`LOCK_SHEET`&&t.sheetId;return e.sheetId===n||e.sheetId===r?`IGNORE_COMMAND`:e.type===`CREATE_SHEET`||t.type===`CREATE_SHEET`||e.sheetId!==t.sheetId?e:`SKIP_TRANSFORMATION`}function KR(e,t){let n=GR(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=[];for(let n of e.target){let e=sr(n,t);e&&r.push(e)}return r.length?{...e,target:r}:`IGNORE_COMMAND`}function qR(e,t){let n=GR(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;let r=sr(e.zone,t);return r?{...e,zone:r}:`IGNORE_COMMAND`}function JR(e,t){if(!(`sheetId`in t))return e;let n=e.ranges.map(e=>cr(e,t)).filter(w);return n.length?{...e,ranges:n}:`IGNORE_COMMAND`}function YR(e,t){let n=GR(e,t);if(n!==`SKIP_TRANSFORMATION`)return n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e;if(t.type!==`ADD_COLUMNS_ROWS`&&t.type!==`REMOVE_COLUMNS_ROWS`)return`SKIP_TRANSFORMATION`;if(t.dimension!==e.dimension)return e;let r=[];return t.type===`REMOVE_COLUMNS_ROWS`?r=_c(t.elements,e.elements):t.type===`ADD_COLUMNS_ROWS`&&(r=gc(Ct(t.position,t.base),t.quantity,e.elements)),r.length===0?`IGNORE_COMMAND`:{...e,elements:r}}function XR(e,t){let n=GR(e,t);return n===`SKIP_TRANSFORMATION`?t.type===`ADD_COLUMNS_ROWS`||t.type===`REMOVE_COLUMNS_ROWS`?ZR(e,t):t.type===`ADD_MERGE`?QR(e,t):`SKIP_TRANSFORMATION`:n===`IGNORE_COMMAND`?`IGNORE_COMMAND`:e}function ZR(e,t){let n=t.dimension===`COL`?`col`:`row`,r=e[n];if(t.type===`REMOVE_COLUMNS_ROWS`){let e=[...t.elements].sort((e,t)=>t-e);if(e.includes(r))return`IGNORE_COMMAND`;for(let t of e)r>=t&&r--}return t.type===`ADD_COLUMNS_ROWS`&&(r>t.base||r===t.base&&t.position===`before`)&&(r+=t.quantity),{...e,[n]:r}}function QR(e,t){for(let n of t.target)if(!(e.col===n.left&&e.row===n.top)&&Fn(e.col,e.row,n))return`IGNORE_COMMAND`;return e}var $R=class{rootCommand;timestamp;id;clientId;_commands=[];_changes=[];constructor(e,t,n,r,i,a){this.rootCommand=r,this.timestamp=a,this.id=e,this.clientId=t,this._commands=[...n],this._changes=i?[...i]:[]}setChanges(e){this._changes=e}get commands(){return this._commands}get changes(){return this._changes}},ez=class extends Error{},tz=class extends lr{revisions;transportService;serverRevisionId;commandSquisher;clients={};clientId=`local`;pendingMessages=[];awaitingClientPosition;waitingAck=!1;waitingUndoRedoAck=!1;isReplayingInitialRevisions=!1;processedRevisions=new Set;lastRevisionMessage=void 0;uuidGenerator=new Rd;lastLocalOperation;constructor(e,t,n=ke,r){super(),this.revisions=e,this.transportService=t,this.serverRevisionId=n,this.commandSquisher=r}canApplyOptimisticUpdate(){return!this.waitingUndoRedoAck}save(e,t,n){if(!t.length||!n.length||!this.canApplyOptimisticUpdate())return;let r=new $R(this.uuidGenerator.uuidv4(),this.clientId,t,e,n,Date.now());this.revisions.append(r.id,r),e.type!==`REQUEST_REDO`&&(this.lastLocalOperation=r),this.trigger(`new-local-state-update`,{id:r.id}),this.sendUpdateMessage({type:`REMOTE_REVISION`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:r.id,clientId:r.clientId,commands:r.commands})}undo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_UNDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),undoneRevisionId:e})}redo(e){this.waitingUndoRedoAck=!0,this.sendUpdateMessage({type:`REVISION_REDONE`,version:1,serverRevisionId:this.serverRevisionId,nextRevisionId:this.uuidGenerator.uuidv4(),redoneRevisionId:e})}join(e){e?(this.clients[e.id]=e,this.clientId=e.id):(this.clients.local={id:`local`,name:`local`},this.clientId=`local`),this.transportService.onNewMessage(this.clientId,this.onMessageReceived.bind(this)),this.awaitingClientPosition&&=(this.move(this.awaitingClientPosition),void 0)}loadInitialMessages(e){let t=performance.now(),n=e.reduce((e,t)=>e+(t.type===`REMOTE_REVISION`?t.commands.length:1),0);this.isReplayingInitialRevisions=!0;for(let t of e)this.onMessageReceived(t);this.isReplayingInitialRevisions=!1,console.debug(`Replayed`,n,`commands in`,performance.now()-t,`ms`)}async leave(e){e&&Object.keys(this.clients).length===1&&this.lastRevisionMessage&&this.lastRevisionMessage?.type!==`SNAPSHOT_CREATED`&&await this.snapshot(e()),delete this.clients[this.clientId],this.transportService.leave(this.clientId),await this.sendToTransport({type:`CLIENT_LEFT`,clientId:this.clientId,version:1})}async snapshot(e){if(this.pendingMessages.length!==0)return;let t=this.uuidGenerator.uuidv4();await this.sendToTransport({type:`SNAPSHOT`,nextRevisionId:t,serverRevisionId:this.serverRevisionId,data:{...e,revisionId:t},version:1})}getCurrentClient(){return this.getClient(this.clientId)}getClient(e){let t=this.clients[e];if(!t)throw new ez(`The client left the session`);return t}getConnectedClients(){return new Set(Object.values(this.clients).filter(w))}getRevisionId(){return this.serverRevisionId}isFullySynchronized(){return this.pendingMessages.length===0}getLastLocalNonEmptyRevision(){return this.lastLocalOperation}move(e){if(!this.clients[this.clientId]){this.awaitingClientPosition=e;return}let t=this.clients[this.clientId]?.position;if(t?.col===e.col&&t.row===e.row&&t.sheetId===e.sheetId)return;let n=t?`CLIENT_MOVED`:`CLIENT_JOINED`,r=this.getCurrentClient();this.clients[this.clientId]={...r,position:e},this.sendToTransport({type:n,version:1,client:{...r,position:e}}).then(()=>{this.pendingMessages.length>0&&!this.waitingAck&&this.sendPendingMessage()})}onMessageReceived(e){if(!this.isAlreadyProcessed(e)){if(this.isWrongServerRevisionId(e)){this.trigger(`unexpected-revision-id`);return}switch(e.type){case`CLIENT_MOVED`:this.onClientMoved(e);break;case`CLIENT_JOINED`:this.onClientJoined(e);break;case`CLIENT_LEFT`:this.onClientLeft(e);break;case`REVISION_REDONE`:this.revisions.redo(e.redoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger(`revision-redone`,{revisionId:e.redoneRevisionId,commands:this.revisions.get(e.redoneRevisionId).commands});break;case`REVISION_UNDONE`:this.revisions.undo(e.undoneRevisionId,e.nextRevisionId,e.serverRevisionId),this.trigger(`revision-undone`,{revisionId:e.undoneRevisionId,commands:this.revisions.get(e.undoneRevisionId).commands});break;case`REMOTE_REVISION`:let{clientId:t,timestamp:n}=e,r=this.commandSquisher.unsquish(e.commands),i=new $R(e.nextRevisionId,t,r,void 0,void 0,n);if(i.clientId!==this.clientId){this.revisions.insert(i.id,i,e.serverRevisionId);let t=this.pendingMessages.filter(e=>e.type===`REMOTE_REVISION`).map(e=>e.commands).flat();this.trigger(`remote-revision-received`,{commands:UR(r,t)})}break;case`SNAPSHOT_CREATED`:{let t=new $R(e.nextRevisionId,`server`,[],void 0,void 0,Date.now());this.revisions.insert(t.id,t,e.serverRevisionId),this.dropPendingHistoryMessages(),this.trigger(`snapshot`),this.lastLocalOperation=void 0;break}}this.acknowledge(e),this.trigger(`collaborative-event-received`)}}onClientMoved(e){e.client.id!==this.clientId&&(this.clients[e.client.id]=e.client)}onClientJoined(e){if(e.client.id!==this.clientId){this.clients[e.client.id]=e.client;let t=this.clients[this.clientId];if(t){let{position:e}=t;e&&this.sendToTransport({type:`CLIENT_MOVED`,version:1,client:{...t,position:e}})}}}onClientLeft(e){e.clientId!==this.clientId&&delete this.clients[e.clientId]}sendUpdateMessage(e){this.pendingMessages.push(e),!this.waitingAck&&this.sendPendingMessage()}async sendToTransport(e){return this.transportService.sendMessage(e)}sendPendingMessage(){let e=this.pendingMessages[0];if(e){if(e.type===`REMOTE_REVISION`){let t=this.revisions.get(e.nextRevisionId);t.commands.length===0&&(this.revisions.rebase(t.id),t=this.revisions.get(e.nextRevisionId)),e={...e,commands:this.commandSquisher.squish(t.commands)}}if(this.isReplayingInitialRevisions)throw Error(`Trying to send a new revision while replaying initial revision. This can lead to endless dispatches every time the spreadsheet is open.
117
+ ${JSON.stringify(e)}`);this.waitingAck=!0,this.sendToTransport({...e,serverRevisionId:this.serverRevisionId}).catch(e=>{if(!(e instanceof ez))throw e.cause||e;this.waitingAck=!1})}}acknowledge(e){switch((e.type===`REVISION_UNDONE`||e.type===`REVISION_REDONE`)&&(this.waitingUndoRedoAck=!1),e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`SNAPSHOT_CREATED`:this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter(t=>t.nextRevisionId!==e.nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.lastRevisionMessage=e,this.sendPendingMessage();break;case`REVISION_UNDONE`:{this.waitingAck=!1,this.pendingMessages=this.pendingMessages.filter(t=>t.nextRevisionId!==e.nextRevisionId);let t=this.pendingMessages.findIndex(e=>e.type===`REMOTE_REVISION`);t!==-1&&this.revisions.rebase(this.pendingMessages[t].nextRevisionId),this.serverRevisionId=e.nextRevisionId,this.processedRevisions.add(e.nextRevisionId),this.sendPendingMessage();break}}}isAlreadyProcessed(e){if(e.type===`CLIENT_MOVED`&&e.client.id===this.clientId)return!0;switch(e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`REVISION_UNDONE`:case`SNAPSHOT_CREATED`:return this.processedRevisions.has(e.nextRevisionId);default:return!1}}isWrongServerRevisionId(e){switch(e.type){case`REMOTE_REVISION`:case`REVISION_REDONE`:case`REVISION_UNDONE`:case`SNAPSHOT_CREATED`:return e.serverRevisionId!==this.serverRevisionId;default:return!1}}dropPendingHistoryMessages(){this.waitingUndoRedoAck=!1,this.pendingMessages=this.pendingMessages.filter(({type:e})=>e!==`REVISION_REDONE`&&e!==`REVISION_UNDONE`)}},nz=class extends KL{static getters=[`getClientsToDisplay`,`getClient`,`getCurrentClient`,`getConnectedClients`,`isFullySynchronized`];static layers=[`Selection`];colors=new fi(12);session;constructor(e){super(e),this.session=e.session}isPositionValid(e){return e.row<this.getters.getNumberRows(e.sheetId)&&e.col<this.getters.getNumberCols(e.sheetId)}getClient(e){return this.session.getClient(e)}getCurrentClient(){return this.session.getCurrentClient()}getConnectedClients(){return[...this.session.getConnectedClients()].map(e=>({...e,color:this.colors.get(e.id)}))}isFullySynchronized(){return this.session.isFullySynchronized()}getClientsToDisplay(e){try{this.getters.getCurrentClient()}catch(e){if(e instanceof ez)return[];throw e}let t=[];for(let n of this.getters.getConnectedClients())n.id!==this.getters.getCurrentClient().id&&n.position&&n.position.sheetId===e&&this.isPositionValid(n.position)&&t.push({...n,position:n.position});return t}drawLayer(e){if(this.getters.isDashboard())return;let{ctx:t,thinLineWidth:n,viewports:r,sheetId:i}=e;for(let e of this.getClientsToDisplay(i)){let{row:a,col:o}=e.position,s=this.getters.expandZone(i,{top:a,bottom:a,left:o,right:o}),{x:c,y:l,width:u,height:d}=r.getVisibleRect(i,s);if(u<=0||d<=0)continue;let f=e.color;t.fillStyle=`${f}10`,t.lineWidth=4*n,t.strokeStyle=f,t.globalCompositeOperation=`multiply`,t.fillRect(c,l,u,d),t.globalCompositeOperation=`source-over`,t.strokeRect(c,l,u,d),t.font=`bold ${Ee+1}px ${De}`}}},rz=class extends KL{handle(e){switch(e.type){case`ADD_DATA_VALIDATION_RULE`:if(e.rule.criterion.type===`isBoolean`){let t=e.ranges.map(e=>this.getters.getRangeFromRangeData(e));for(let e of rc(t)){let t=this.getters.getCell(e),n=this.getters.getEvaluatedCell(e);if(!t?.isFormula&&!t?.content)this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`});else if((t?.isFormula||t?.content)&&n.type===`empty`){let n;if(t.isFormula){let r=this.getters.evaluateCompiledFormula(e.sheetId,t.compiledFormula);n=(Je(r)?r[0][0]:r)?.toString()}else n=t.content;(!n||!at(n))&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}else n.type!==`boolean`&&this.dispatch(`UPDATE_CELL`,{...e,content:`FALSE`})}}}}},iz=class extends KL{static getters=[`dynamicTranslate`];dynamicTranslate(e){return e}},az=class extends KL{handle(e){switch(e.type){case`SET_DECIMAL`:this.setDecimal(e.sheetId,e.target,e.step);break;case`SET_FORMATTING_WITH_PIVOT`:this.setContextualFormat(e.sheetId,e.target,e.format);break}}setContextualFormat(e,t,n){let r=[],i={};for(let n of cn(t))for(let t=n.left;t<=n.right;t++)for(let a=n.top;a<=n.bottom;a++){let n={sheetId:e,col:t,row:a},o=this.getters.getPivotCellFromPosition(n);if(this.isSpilledPivotValueFormula(n,o)){r.push(n);let e=this.getters.getPivotIdFromPosition(n)||``;i[e]??=new Set,i[e].add(o.measure)}}let a=cn(r.map(D));for(let e in i){let t=i[e],r=this.getters.getPivotCoreDefinition(e);this.dispatch(`UPDATE_PIVOT`,{pivotId:e,pivot:{...r,measures:r.measures.map(e=>t.has(e.id)?{...e,format:n}:e)}})}this.dispatch(`SET_FORMATTING`,{sheetId:e,target:a,format:``}),this.dispatch(`SET_FORMATTING`,{sheetId:e,target:cn(t,a),format:n})}isSpilledPivotValueFormula(e,t){let n=this.getters.getCell(e);return t.type===`VALUE`&&!n?.isFormula}setDecimal(e,t,n){let r={};for(let i of cn(t))for(let t of Bn(i)){let i=this.getCellNumberFormat({sheetId:e,...t});if(i!==void 0){let e=$l(i,n);r[e]=r[e]||[],r[e].push(t)}}for(let t in r){let n=cn(r[t].map(e=>D(e)));this.setContextualFormat(e,n,t)}}getCellNumberFormat(e){for(let t of[e]){let e=this.getters.getEvaluatedCell(t);if(e.type===`number`&&!(e.format&&Il(e.format)))return e.format||Bl(e.value)}}},oz=class extends KL{static getters=[`getGeoJsonFeatures`,`geoFeatureNameToId`,`getGeoChartAvailableRegions`,`getAvailableChartRegions`];geoJsonService;geoJsonCache={};initialRegions={};constructor(e){super(e),this.geoJsonService=e.external.geoJsonService}handle(e){switch(e.type){case`START`:for(let e of this.getters.getSheetIds())for(let t of this.getters.getChartIds(e))this.trackInitialRegion(t);break;case`CREATE_CHART`:this.trackInitialRegion(e.chartId);break;case`UPDATE_CHART_REGION`:{let t=this.getters.getChart(e.chartId),n=this.getters.getChartDefinition(e.chartId);if(!t||n.type!==`geo`)break;this.dispatch(`UPDATE_CHART`,{chartId:e.chartId,sheetId:t.sheetId,figureId:this.getters.getFigureIdFromChartId(e.chartId),definition:{...n,region:e.region}});break}}}trackInitialRegion(e){let t=this.getters.getChartDefinition(e);if(t?.type===`geo`){let n=this.getGeoChartAvailableRegions();this.initialRegions[e]=t.region||n[0]?.id||``}}getGeoChartAvailableRegions(){return this.geoJsonService?this.geoJsonService.getAvailableRegions()||[]:(console.error(`No geoJsonService provided to the model`),[])}getAvailableChartRegions(e){if(!this.geoJsonService)return[];let t=this.getters.getChartDefinition(e);if(!t||t.type!==`geo`)return[];let n=this.initialRegions[e];return n&&this.geoJsonService.getAlternativeRegions?.(n)||[]}getGeoJsonFeatures(e){if(!this.geoJsonService){console.error(`No geoJsonService provided to the model`);return}let t=this.geoJsonCache[e];if(!(t instanceof Promise)){if(t!==void 0)return t??void 0;this.geoJsonCache[e]=new Promise(async t=>{let n=await this.geoJsonService?.getTopoJson(e);this.geoJsonCache[e]=this.convertToGeoJson(n),this.dispatch(`EVALUATE_CHARTS`),t()})}}geoFeatureNameToId(e,t){if(!this.geoJsonService){console.error(`No geoJsonService provided to the model`);return}return this.geoJsonService.geoFeatureNameToId(e,t)}convertToGeoJson(e){if(!e)return null;if(e.type===`Topology`){let t=globalThis.ChartGeo.topojson.feature(e,Object.values(e.objects)[0]);return t.type===`FeatureCollection`?t.features:[t]}else if(e.type===`FeatureCollection`)return e.features;throw Error(`Invalid TopoJSON`)}},sz=class extends KL{static getters=[`getNextVisibleCellPosition`,`findVisibleHeader`,`findLastVisibleColRowIndex`,`findFirstVisibleColRowIndex`,`isRowHidden`,`isColHidden`,`isHeaderHidden`];isRowHidden(e,t){return this.getters.isRowHiddenByUser(e,t)||this.getters.isRowFiltered(e,t)}isColHidden(e,t){return this.getters.isColHiddenByUser(e,t)}isHeaderHidden(e,t,n){return t===`COL`?this.isColHidden(e,n):this.isRowHidden(e,n)}getNextVisibleCellPosition({sheetId:e,col:t,row:n}){return{sheetId:e,col:this.findVisibleHeader(e,`COL`,t,this.getters.getNumberCols(e)-1)||this.findVisibleHeader(e,`COL`,t,0)||0,row:this.findVisibleHeader(e,`ROW`,n,this.getters.getNumberRows(e)-1)||this.findVisibleHeader(e,`ROW`,n,0)||0}}findVisibleHeader(e,t,n,r){if(n<=r){for(let i=n;i<=r;i++)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}if(n>r){for(let i=n;i>=r;i--)if(this.getters.doesHeaderExist(e,t,i)&&!this.isHeaderHidden(e,t,i))return i}}findLastVisibleColRowIndex(e,t,{last:n,first:r}){return C(n,r,-1).find(n=>!this.isHeaderHidden(e,t,n))||r}findFirstVisibleColRowIndex(e,t){let n=this.getters.getNumberHeaders(e,t);for(let r=0;r<n;r++)if(t===`COL`&&!this.isColHidden(e,r)||t===`ROW`&&!this.isRowHidden(e,r))return r}exportForExcel(e){for(let t of e.sheets)for(let[e,n]of Object.entries(t.rows))n.isHidden=this.isRowHidden(t.id,Number(e))}},cz=class extends KL{static getters=[];allowDispatch(e){switch(e.type){case`DUPLICATE_PIVOT_IN_NEW_SHEET`:if(!this.getters.isExistingPivot(e.pivotId))return`PivotIdNotFound`;if(!this.getters.getPivot(e.pivotId).isValid())return`PivotInError`;break}return`Success`}handle(e){switch(e.type){case`INSERT_NEW_PIVOT`:this.insertNewPivot(e.pivotId,e.newSheetId);break;case`DUPLICATE_PIVOT_IN_NEW_SHEET`:this.duplicatePivotInNewSheet(e.pivotId,e.newPivotId,e.newSheetId);break;case`INSERT_PIVOT_WITH_TABLE`:this.insertPivotWithTable(e.sheetId,e.col,e.row,e.pivotId,e.table,e.pivotMode);break;case`SPLIT_PIVOT_FORMULA`:this.splitPivotFormula(e.sheetId,e.col,e.row,e.pivotId)}}insertNewPivot(e,t){Xn(this.getters.getSelectedZone())===1&&this.selection.selectTableAroundSelection();let n=this.getters.getActiveSheetId();this.dispatch(`ADD_PIVOT`,{pivotId:e,pivot:{dataSet:{zone:this.getters.getSelectedZone(),sheetId:n},columns:[],rows:[],measures:[],name:j(`New pivot`),type:`SPREADSHEET`,style:{tableStyleId:Ve}}});let r=this.getters.getSheetIds().findIndex(e=>e===n)+1,i=this.getters.getPivotFormulaId(e);this.dispatch(`CREATE_SHEET`,{sheetId:t,name:j(`Pivot #%(formulaId)s`,{formulaId:i}),position:r}),this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:n,sheetIdTo:t});let a=this.getters.getPivot(e);this.insertPivotWithTable(t,0,0,e,a.getCollapsedTableStructure().export(),`dynamic`)}duplicatePivotInNewSheet(e,t,n){this.dispatch(`DUPLICATE_PIVOT`,{pivotId:e,newPivotId:t,duplicatedPivotName:j(`%s (copy)`,this.getters.getPivotCoreDefinition(e).name)});let r=this.getters.getActiveSheetId(),i=this.getters.getSheetIds().indexOf(r)+1,a=this.getters.getPivotFormulaId(t),o=this.getters.getPivotName(t);if(this.dispatch(`CREATE_SHEET`,{sheetId:n,name:this.getPivotDuplicateSheetName(j(`%(newPivotName)s (Pivot #%(formulaId)s)`,{newPivotName:o,formulaId:a})),position:i}).isSuccessful){this.dispatch(`ACTIVATE_SHEET`,{sheetIdFrom:r,sheetIdTo:n});let i=this.getters.getPivot(e);this.insertPivotWithTable(n,0,0,t,i.getCollapsedTableStructure().export(),`dynamic`)}}getPivotDuplicateSheetName(e){let t=this.getters.getSheetIds().map(e=>this.getters.getSheetName(e));return Kt(nt(e),t)}insertPivotWithTable(e,t,n,r,i,a){let{cols:o,rows:s,measures:c,fieldsType:l}=i,u=new jj(o,s,c,l||{}),d=u.columns.length-1;if(this.resizeSheet(e,t,n,u),a===`dynamic`)this.dispatch(`UPDATE_CELL`,{sheetId:e,col:t,row:n,content:`=PIVOT(${this.getters.getPivotFormulaId(r)})`});else{this.dispatch(`INSERT_PIVOT`,{sheetId:e,col:t,row:n,pivotId:r,table:u.export()});let i={left:t,right:t+u.getNumberOfDataColumns(),top:n,bottom:n+d+u.rows.length};this.dispatch(`CREATE_TABLE`,{tableType:`static`,sheetId:e,ranges:[this.getters.getRangeDataFromZone(e,i)],config:{...Be,numberOfHeaders:d}})}}resizeSheet(e,t,n,r){let i=r.getNumberOfDataColumns()+1,a=this.getters.getNumberCols(e),o=a-t;o<i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:a-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:i-o,position:`after`});let s=r.columns.length+r.rows.length,c=this.getters.getNumberRows(e),l=c-n;l<s&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:c-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:s-l,position:`after`})}splitPivotFormula(e,t,n,r){let i={sheetId:e,col:t,row:n},a=this.getters.getSpreadZone(i),o=this.getters.getTable(i);if(!a)return;let s=this.getters.getPivotFormulaId(r),c=this.getters.getPivotStyleAtPosition(i);if(!c)return;let l={...c.pivotStyle,tabularForm:!1},u=this.getters.getPivot(r).getCollapsedTableStructure(),d=u.getPivotCells(l),{numberOfCols:f,numberOfRows:p}=u.getPivotTableDimensions(l);if(!(p===0||f===0)){for(let t of C(0,f))for(let n of C(0,p)){let r=d[t][n];if(r){let i={sheetId:e,col:a.left+t,row:a.top+n};this.dispatch(`UPDATE_CELL`,{...i,content:Eg(s,r)})}}if(this.getters.getCoreTable(i)&&this.dispatch(`REMOVE_TABLE`,{sheetId:e,target:[D(i)]}),o?.isPivotTable){let t=this.getters.getRangeDataFromZone(e,{left:a.left,right:a.left+f-1,top:a.top,bottom:a.top+p-1});this.dispatch(`CREATE_TABLE`,{tableType:`static`,sheetId:e,ranges:[t],config:{...o.config,styleId:xM(o.config.styleId)}})}}}};let lz=new A,uz=new A;function dz(e,t){if(t&&lz.contains(t.type))return lz.get(t.type)(e,t)}function fz(e,t,n){if(uz.contains(t.type))return uz.get(t.type)(e,t,n)}function pz(e){return!e||!e.rootCommand||typeof e.rootCommand!=`object`?!1:wu(e.rootCommand)?lz.contains(e.rootCommand.type):uz.contains(e.rootCommand.type)}function mz(e,t){if(!(!e.rootCommand||typeof e.rootCommand!=`object`))return wu(e.rootCommand)?dz(t,e.rootCommand):fz(t,e.rootCommand,e.commands)}var hz=class extends KL{static getters=[`canUndo`,`canRedo`];undoStack=[];redoStack=[];session;constructor(e){super(e),this.session=e.session,this.session.on(`new-local-state-update`,this,this.onNewLocalStateUpdate),this.session.on(`snapshot`,this,()=>{this.undoStack=[],this.redoStack=[]})}allowDispatch(e){switch(e.type){case`REQUEST_UNDO`:if(!this.canUndo())return`EmptyUndoStack`;break;case`REQUEST_REDO`:if(!this.canRedo())return`EmptyRedoStack`;break}return`Success`}handle(e){switch(e.type){case`REQUEST_UNDO`:case`REQUEST_REDO`:this.requestHistoryChange(e.type===`REQUEST_UNDO`?`UNDO`:`REDO`)}}finalize(){}requestHistoryChange(e){let t=e===`UNDO`?this.undoStack.pop():this.redoStack.pop();if(!t){let e=this.getPossibleRevisionToRepeat();if(!e)return;let t=mz(e,this.getters);if(!t)return;if(!Array.isArray(t)){this.dispatch(t.type,t);return}for(let e of t)this.dispatch(e.type,e);return}e===`UNDO`?(this.session.undo(t),this.redoStack.push(t)):(this.session.redo(t),this.undoStack.push(t))}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0?!0:pz(this.getPossibleRevisionToRepeat())}onNewLocalStateUpdate({id:e}){this.undoStack.push(e),this.redoStack=[],this.undoStack.length>99&&this.undoStack.shift()}getPossibleRevisionToRepeat(){return this.session.getLastLocalNonEmptyRevision()}},gz=class extends KL{static getters=[`isCurrentSheetLocked`];allowDispatch(e){return Su.has(e.type)||this.getters.isDashboard()?`Success`:`sheetId`in e&&this.getters.isSheetLocked(e.sheetId)||!wu(e)&&this.isCurrentSheetLocked()?`SheetLocked`:`Success`}isCurrentSheetLocked(){return this.getters.isSheetLocked(this.getters.getActiveSheetId())}},_z=class{trackedValues=new Set;domainToArray(e){return e.flatMap(e=>[e.field,L(e.value)])}isValuePresent(e,t){let n=JSON.stringify({measure:e,domain:this.domainToArray(t)});return this.trackedValues.has(n)}isHeaderPresent(e){let t=JSON.stringify({domain:this.domainToArray(e)});return this.trackedValues.has(t)}trackValue(e,t){let n=JSON.stringify({measure:e,domain:this.domainToArray(t)});this.trackedValues.add(n)}trackHeader(e){let t=JSON.stringify({domain:this.domainToArray(e)});this.trackedValues.add(t)}},vz=class extends KL{static getters=[`getPivotPresenceTracker`];trackPresencePivotId;tracker;handle(e){switch(e.type){case`PIVOT_START_PRESENCE_TRACKING`:this.tracker=new _z,this.trackPresencePivotId=e.pivotId;break;case`PIVOT_STOP_PRESENCE_TRACKING`:this.trackPresencePivotId=void 0;break}}getPivotPresenceTracker(e){if(this.trackPresencePivotId===e){if(!this.tracker)throw Error(`Tracker not initialized`);return this.tracker}}};let yz=[`number`,`error`,`text`,`boolean`];function bz(e){let t=e===`asc`?1:-1;return(e,n)=>{if(e.type===`empty`)return n.type===`empty`?0:1;if(n.type===`empty`)return-1;let r=yz.indexOf(e.type)-yz.indexOf(n.type);return r===0&&(r=e.type===`text`||e.type===`error`?e.value.localeCompare(n.value):e.value-n.value),t*r}}function xz(e,t,n){let r=e.map((e,t)=>({index:t,type:e.type,value:e.value}));return(n?r.map(e=>e.type===`empty`?{...e,type:`number`,value:0}:e):r).sort(bz(t))}var Sz=class extends KL{allowDispatch(e){switch(e.type){case`SORT_CELLS`:return Fn(e.col,e.row,e.zone)?this.checkValidations(e,this.checkMerge,this.checkMergeSizes,this.checkArrayFormulaInSortZone):`InvalidSortAnchor`}return`Success`}handle(e){switch(e.type){case`SORT_CELLS`:this.sortZone(e.sheetId,e,e.zone,e.sortDirection,e.sortOptions||{});break}}checkMerge({sheetId:e,zone:t}){return this.getters.doesIntersectMerge(e,t)&&Bn(t).some(({col:t,row:n})=>!this.getters.isInMerge({sheetId:e,col:t,row:n}))?`InvalidSortZone`:`Success`}checkMergeSizes({sheetId:e,zone:t}){if(!this.getters.doesIntersectMerge(e,t))return`Success`;let n=this.getters.getMerges(e).filter(e=>Nn(e,t)),r=Ln(n[0]),[i,a]=[r.numberOfCols,r.numberOfRows];return n.every(e=>{let[t,n]=[e.right-e.left+1,e.bottom-e.top+1];return t===i&&n===a})?`Success`:`InvalidSortZone`}checkArrayFormulaInSortZone({sheetId:e,zone:t}){return Bn(t).some(({col:t,row:n})=>{let r=this.getters.getArrayFormulaSpreadingOn({sheetId:e,col:t,row:n});return r&&!T(r,{sheetId:e,col:t,row:n})})?`SortZoneWithArrayFormulas`:`Success`}hasHeader(e,t){if(t[0].length===1)return!1;let n=t.map(t=>t.map(({col:t,row:n})=>this.getters.getEvaluatedCell({sheetId:e,col:t,row:n}).type));return n[0][0]===`empty`&&(n=n.slice(1)),n.some(e=>e[0]===`empty`)?!1:!!n.some(e=>e[1]!==`empty`&&e[0]!==e[1])}sortZone(e,t,n,r,i){let[a,o]=this.mainCellsSteps(e,n),s=this.getters.getMainCellPosition({sheetId:e,col:t.col,row:t.row}).col,c=Object.assign({},n),l=this.mainCells(e,n);!i.sortHeaders&&this.hasHeader(e,l)&&(c.top+=o),l=this.mainCells(e,c);let u=l[s-c.left],d=xz(u.map(e=>this.getters.getEvaluatedCell(e)),r,!!i.emptyCellAsZero).map(e=>e.index),[f,p]=[l.length,l[0].length],m=[];for(let e=0;e<f;e++)for(let t=0;t<p;t++){let{col:n,row:r,sheetId:i}=l[e][d[t]],s=this.getters.getCell({sheetId:i,col:n,row:r}),u=c.left+e*a,f=c.top+t*o,p={sheetId:i,col:u,row:f,content:``};if(s){let e;if(s.isFormula){let t=this.getters.getCellPosition(s.id);e=this.getters.getTranslatedCellFormula(i,0,f-t.row,s.compiledFormula)}else e=s.content;p.style=s.style,p.content=e,p.format=s.format}m.push(p)}m.forEach(e=>this.dispatch(`UPDATE_CELL`,e))}mainCellsSteps(e,t){let n=this.getters.getMerge({sheetId:e,col:t.left,row:t.top});return[n?n.right-n.left+1:1,n?n.bottom-n.top+1:1]}mainCells(e,t){let[n,r]=this.mainCellsSteps(e,t),i=[],a=C(t.left,t.right+1,n),o=C(t.top,t.bottom+1,r);for(let t of a){let n=[];i.push(n);for(let r of o)n.push({sheetId:e,col:t,row:r})}return i}},Cz=class extends KL{static getters=[`getAutomaticSeparator`];allowDispatch(e){switch(e.type){case`SPLIT_TEXT_INTO_COLUMNS`:return this.chainValidations(this.batchValidations(this.checkSingleColSelected,this.checkNonEmptySelector),this.batchValidations(this.checkNotOverwritingContent,this.checkSeparatorInSelection))(e)}return`Success`}handle(e){switch(e.type){case`SPLIT_TEXT_INTO_COLUMNS`:this.splitIntoColumns(e);break}}getAutomaticSeparator(){let e=this.getters.getSelectedCells();for(let t of e)if(t.value&&t.type===`text`){let e=this.getAutoSeparatorForString(t.value);if(e)return e}return` `}getAutoSeparatorForString(e){for(let t of[`
118
118
  `,`;`,`,`,` `,`.`])if(e.includes(t))return t}splitIntoColumns({separator:e,addNewColumns:t}){let n=this.getters.getSelectedZone(),r=this.getters.getActiveSheetId(),i=this.getSplittedCols(n,e);t&&this.addColsToAvoidCollisions(n,i),this.removeMergesInSplitZone(n,i),this.addColumnsToNotOverflowSheet(n,i);for(let e=0;e<i.length;e++){let t=n.top+e,a=i[e],o=n.left,s=this.getters.getCell({sheetId:r,col:o,row:t});if(!(a.length===1&&!s?.isFormula&&a[0]===s?.content))for(let[e,n]of a.entries())this.dispatch(`UPDATE_CELL`,{sheetId:r,col:o+e,row:t,content:Gy(n,this.getters.getLocale()),format:``,style:s?.style||null})}}getSplittedCols(e,t){if(!t)throw Error(`Separator cannot be empty`);let n=this.getters.getActiveSheetId(),r=[];for(let i of C(e.top,e.bottom+1)){let a=this.getters.getEvaluatedCell({sheetId:n,col:e.left,row:i}).formattedValue;r.push(this.splitAndRemoveTrailingEmpty(a,t))}return r}splitAndRemoveTrailingEmpty(e,t){let n=e.split(t);for(;n.length>1&&n[n.length-1]===``;)n.pop();return n}willSplittedColsOverwriteContent(e,t){let n=this.getters.getActiveSheetId();for(let r of C(e.top,e.bottom+1)){let i=t[r-e.top];for(let t=1;t<i.length;t++){let i=this.getters.getCell({sheetId:n,col:e.left+t,row:r});if(i?.isFormula||i?.content)return!0}}return!1}removeMergesInSplitZone(e,t){let n=this.getters.getActiveSheetId(),r=Math.max(...t.map(e=>e.length)),i={...e,right:e.left+r-1},a=this.getters.getMergesInZone(n,i);this.dispatch(`REMOVE_MERGE`,{sheetId:n,target:a})}addColsToAvoidCollisions(e,t){let n=this.getters.getActiveSheetId(),r=0;for(let i of C(e.top,e.bottom+1)){let a={sheetId:n,col:e.left,row:i},o=t[i-e.top],s=this.getColsToAddToAvoidCollision(a,o);r=Math.max(r,s)}r&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:e.left,sheetId:n,sheetName:this.getters.getSheetName(n),quantity:r,position:`after`})}getColsToAddToAvoidCollision(e,t){let n=t.length;for(let t=1;t<n;t++){let r=e.col+t,i=this.getters.getCell({...e,col:r});if(i?.isFormula||i?.content)return n-t}return 0}addColumnsToNotOverflowSheet(e,t){let n=this.getters.getActiveSheetId(),r=Math.max(...t.map(e=>e.length-1)),i=this.getters.getNumberCols(n)-1;e.left+r>i&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:i,sheetId:n,sheetName:this.getters.getSheetName(n),quantity:e.left+r-i,position:`after`})}checkSingleColSelected(){return this.getters.isSingleColSelected()?`Success`:`MoreThanOneColumnSelected`}checkNonEmptySelector(e){return e.separator===``?`EmptySplitSeparator`:`Success`}checkNotOverwritingContent(e){if(e.addNewColumns||e.force)return`Success`;let t=this.getters.getSelectedZones()[0],n=this.getSplittedCols(t,e.separator);return this.willSplittedColsOverwriteContent(t,n)?`SplitWillOverwriteContent`:`Success`}checkSeparatorInSelection({separator:e}){let t=this.getters.getSelectedCells();for(let n of t)if(n.formattedValue.includes(e))return`Success`;return`NoSplitSeparatorInSelection`}},wz=class extends KL{handle(e){bu.has(e.type)&&this.dispatch(`EVALUATE_CELLS`,{cellIds:this.getters.getCellsWithTrackedFormula(`SUBTOTAL`)})}},Tz=class extends KL{handle(e){switch(e.type){case`AUTOFILL_TABLE_COLUMN`:let t=this.getters.getCoreTable(e),n=this.getters.getCell(e);if(!t?.config.automaticAutofill||t.type===`dynamic`||!n?.isFormula)return;let{col:r,row:i}=e,a=CM(t.range.zone,t.config);if(a&&Fn(r,i,a)){let t=e.autofillRowStart??a.top,n=e.autofillRowEnd??a.bottom,r={...a,top:t,bottom:n};this.autofillTableZone(e,r)}break}}autofillTableZone(e,t){if(t.top===t.bottom)return;let{col:n,row:r,sheetId:i}=e;for(let e=t.top;e<=t.bottom;e++)if(e!==r&&this.getters.getEvaluatedCell({col:n,row:e,sheetId:i}).type!==`empty`)return;let a={zone:this.getters.getSelectedZone(),cell:this.getters.getActivePosition()};this.selection.selectCell(n,r),this.dispatch(`AUTOFILL_SELECT`,{col:n,row:t.bottom}),this.dispatch(`AUTOFILL`),this.selection.selectCell(n,r),this.dispatch(`AUTOFILL_SELECT`,{col:n,row:t.top}),this.dispatch(`AUTOFILL`),this.selection.selectZone(a)}},Ez=class extends KL{allowDispatch(e){switch(e.type){case`RESIZE_TABLE`:let t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(!t)return`TableNotFound`;let n=t.range.zone,r=this.getters.getRangeFromRangeData(e.newTableRange).zone;return r.top!==n.top||r.left!==n.left?`InvalidTableResize`:this.canDispatch(`UPDATE_TABLE`,{...e}).reasons}return`Success`}handle(e){switch(e.type){case`RESIZE_TABLE`:{let t=this.getters.getCoreTableMatchingTopLeft(e.sheetId,e.zone);if(this.dispatch(`UPDATE_TABLE`,{...e}),!t)return;let n=this.getters.getRangeFromRangeData(e.newTableRange).zone;if(this.selection.selectCell(n.right,n.bottom),!t.config.automaticAutofill)return;let r=t.range.zone;if(n.bottom>=r.bottom){for(let t=n.left;t<=n.right;t++){let i={col:t,row:r.bottom,sheetId:e.sheetId};this.getters.getCell(i)?.isFormula&&this.dispatch(`AUTOFILL_TABLE_COLUMN`,{...i,autofillRowStart:r.bottom,autofillRowEnd:n.bottom})}break}}}}},Dz=class extends KL{static getters=[`shouldShowFormulas`];showFormulas=!1;handle(e){switch(e.type){case`SET_FORMULA_VISIBILITY`:this.showFormulas=e.show;break}}shouldShowFormulas(){return this.showFormulas}},Oz=class extends KL{static getters=[`getCellWidth`,`getTextWidth`,`getCellText`,`getCellMultiLineText`,`getMultilineTextSize`,`getContiguousZone`,`computeTextYCoordinate`];ctx=hd();allowDispatch(e){return this.chainValidations(this.checkSheetExists,this.checkZonesAreInSheet)(e)}handle(e){switch(e.type){case`AUTORESIZE_COLUMNS`:for(let t of e.cols){let n=this.getColMaxWidth(e.sheetId,t);n!==0&&this.dispatch(`RESIZE_COLUMNS_ROWS`,{elements:[t],dimension:`COL`,size:n,sheetId:e.sheetId})}break;case`AUTORESIZE_ROWS`:this.autoResizeRows(e.sheetId,e.rows);break;case`DELETE_UNFILTERED_CONTENT`:let t=[];for(let n of e.target){let r=rt(C(n.top,n.bottom+1).filter(t=>!this.getters.isRowFiltered(e.sheetId,t)));for(let e of r)t.push({...n,top:e[0],bottom:e[e.length-1]})}this.dispatch(`DELETE_CONTENT`,{sheetId:e.sheetId,target:t});break}}getCellWidth(e){let t=this.getters.getCellComputedStyle(e),n=0,r=this.getters.getEvaluatedCell(e).formattedValue;if(r){let e=kd(this.ctx,r,t,void 0);n+=yd(this.ctx,e,t).width}for(let t of this.getters.getCellIcons(e))n+=t.margin+t.size;if(this.getters.getDataValidationChipStyle(e)&&(n+=10),n===0)return 0;if(n+=8,t.wrapping===`wrap`){let t=this.getters.getColSize(this.getters.getActiveSheetId(),e.col);return Math.min(t,n)}return n}getTextWidth(e,t){return bd(this.ctx,e,t)}getMultilineTextSize(e,t){return yd(this.ctx,e,t)}getCellText(e,t){let n=this.getters.getCell(e),r=this.getters.getLocale();if(t?.showFormula){if(n?.isFormula)return Xy(n.compiledFormula.toFormulaString(this.getters),r);if(!n?.content)return``}let i=this.getters.getEvaluatedCell(e),a=t?.availableWidth?{availableWidth:t.availableWidth,measureText:e=>bd(this.ctx,e,n?.style||{})}:void 0;return H(i.value,{format:i.format,locale:r,formatWidth:a})}getCellMultiLineText(e,t){let n=this.getters.getCellStyle(e),r=this.getters.getCellText(e,{showFormula:this.getters.shouldShowFormulas(),availableWidth:t.maxWidth});return kd(this.ctx,r,n,t.wrapWidth)}computeTextYCoordinate(e,t,n=we,r=1){let i=e.y+1,a=md(t,r);if(e.height>a+8){if(n===`middle`)return Math.ceil(i+(e.height-a)/2);if(n===`bottom`)return i+e.height-a-4}return i+4}getContiguousZone(e,t){let n=t=>{for(let n of C(t.left,t.right+1)){if(!this.isCellEmpty({sheetId:e,col:n,row:t.top-1}))return{...t,top:t.top-1};if(!this.isCellEmpty({sheetId:e,col:n,row:t.bottom+1}))return{...t,bottom:t.bottom+1}}for(let n of C(t.top,t.bottom+1)){if(!this.isCellEmpty({sheetId:e,col:t.left-1,row:n}))return{...t,left:t.left-1};if(!this.isCellEmpty({sheetId:e,col:t.right+1,row:n}))return{...t,right:t.right+1}}return t},r=!1,i=t;do{r=!1;let e=n(i);Mn(i,e)||(r=!0,i=e)}while(r);return i}isCellEmpty(e){let t=this.getters.getMainCellPosition(e);return this.getters.getEvaluatedCell(t).type===`empty`}getColMaxWidth(e,t){let n=Bn(this.getters.getColsZone(e,t,t)).map(t=>this.getCellWidth({sheetId:e,...t}));return Math.max(0,Vt(n))}checkSheetExists(e){return`sheetId`in e&&this.getters.tryGetSheet(e.sheetId)===void 0&&e.type!==`CREATE_SHEET`?`InvalidSheetId`:`Success`}checkZonesAreInSheet(e){let t=`sheetId`in e?e.sheetId:this.getters.tryGetActiveSheetId();if(`ranges`in e&&e.ranges.some(e=>!this.getters.tryGetSheet(e._sheetId)))return`InvalidSheetId`;let n=this.getters.getCommandZones(e);return!t&&n.length>0?`NoActiveSheet`:t&&n.length>0?this.getters.checkZonesExistInSheet(t,n):`Success`}autoResizeRows(e,t){let n=[];for(let r of t){let t=0;for(let n of this.getters.getRowCellIds(e,r)){let r=this.getters.getCellById(n);if(!r)continue;let i=this.getters.getCellPosition(r.id),a=this.getters.getColSize(e,i.col);if(r.isFormula||this.getters.getArrayFormulaSpreadingOn(i)){let e=this.getters.getEvaluatedCell(i).formattedValue,n=_d(this.ctx,e,r?.style,a);n>t&&n>23&&(t=n)}else{let e=r.content,n=_d(this.ctx,e,r?.style,a);n>=t&&n>23&&(t=0)}}n.push(t||null)}let r=new Map(n.map(e=>[e,[]]));for(let e=0;e<n.length;e++)r.get(n[e])?.push(t[e]);for(let[t,n]of r)this.dispatch(`RESIZE_COLUMNS_ROWS`,{elements:n,dimension:`ROW`,size:t,sheetId:e})}},kz=class extends KL{static getters=[`getSelectedCarouselItem`,`getChartFromFigureId`,`getChartIdFromFigureId`];uuidGenerator=new Rd;carouselStates={};allowDispatch(e){switch(e.type){case`ADD_FIGURE_CHART_TO_CAROUSEL`:return!this.getters.doesCarouselExist(e.carouselFigureId)||this.getters.getFigure(e.sheetId,e.chartFigureId)?.tag!==`chart`?`InvalidFigureId`:`Success`;case`DUPLICATE_CAROUSEL_CHART`:return!this.getters.doesCarouselExist(e.carouselId)||!this.getters.getCarousel(e.carouselId).items.some(t=>t.type===`chart`&&t.chartId===e.chartId)||this.getters.getChart(e.duplicatedChartId)?`InvalidFigureId`:`Success`;case`ADD_NEW_CHART_TO_CAROUSEL`:return this.getters.doesCarouselExist(e.figureId)?`Success`:`InvalidFigureId`;case`UPDATE_CAROUSEL_ACTIVE_ITEM`:return this.getters.doesCarouselExist(e.figureId)?this.getters.getCarousel(e.figureId).items.some(t=>T(t,e.item))?`Success`:`InvalidCarouselItem`:`InvalidFigureId`}return`Success`}handle(e){switch(e.type){case`ADD_NEW_CHART_TO_CAROUSEL`:this.addNewChartToCarousel(e.figureId,e.sheetId);break;case`ADD_FIGURE_CHART_TO_CAROUSEL`:this.addFigureChartToCarousel(e.carouselFigureId,e.chartFigureId,e.sheetId);break;case`DUPLICATE_CAROUSEL_CHART`:this.duplicateCarouselChart(e);break;case`UPDATE_CAROUSEL_ACTIVE_ITEM`:this.carouselStates[e.figureId]=this.getCarouselItemId(e.item);break;case`POPOUT_CHART_FROM_CAROUSEL`:this.popOutChartFromCarousel(e.carouselId,e.chartId,e.sheetId);break;case`DELETE_FIGURE`:delete this.carouselStates[e.figureId];break;case`UPDATE_CAROUSEL`:this.fixWrongCarouselState(e.figureId);break;case`DELETE_CHART`:case`UNDO`:case`REDO`:case`DELETE_SHEET`:for(let e in this.carouselStates)this.fixWrongCarouselState(e);break}}popOutChartFromCarousel(e,t,n){let r=this.getters.getCarousel(e);if(!r)return;let i=this.getters.getFigure(n,e),a=this.getters.getChartDefinition(t);if(!a||!i)return;let o=this.getters.getFigureUI(n,i),s=this.getters.getPositionAnchorOffset({x:o.x+50,y:o.y+50}),c=this.uuidGenerator.smallUuid();this.dispatch(`CREATE_CHART`,{...s,chartId:this.uuidGenerator.smallUuid(),figureId:c,sheetId:n,size:{width:i.width,height:i.height},definition:{...a}});let l=r.items.filter(e=>e.type!==`chart`||e.chartId!==t);this.dispatch(`UPDATE_CAROUSEL`,{sheetId:n,figureId:e,definition:{...r,items:l}}),this.dispatch(`SELECT_FIGURE`,{figureId:c})}getSelectedCarouselItem(e){let t=this.getters.getCarousel(e);if(t.items.length)return this.carouselStates[e]?t.items.find(t=>this.getCarouselItemId(t)===this.carouselStates[e]):t.items[0]}getChartFromFigureId(e){if(!this.getters.getFigureSheetId(e))return;let t=this.getChartIdFromFigureId(e);return t?this.getters.getChart(t):void 0}getChartIdFromFigureId(e){let t=this.getters.getFigureSheetId(e);if(!t)return;let n=this.getters.getFigure(t,e);if(!(!n||n.tag!==`chart`&&n.tag!==`carousel`)){if(n.tag===`carousel`){let t=this.getSelectedCarouselItem(e);return t?.type===`chart`?t.chartId:void 0}return this.getters.getChartIds(t).find(t=>this.getters.getFigureIdFromChartId(t)===e)}}fixWrongCarouselState(e){if(!this.getters.doesCarouselExist(e)){delete this.carouselStates[e];return}let t=this.getters.getCarousel(e);t.items.length===0?delete this.carouselStates[e]:this.carouselStates[e]&&t.items.some(t=>this.getCarouselItemId(t)===this.carouselStates[e])||(this.carouselStates[e]=this.getCarouselItemId(t.items[0]))}addNewChartToCarousel(e,t){let n=this.getters.getCarousel(e),r=this.uuidGenerator.smallUuid();this.dispatch(`CREATE_CHART`,{chartId:r,figureId:e,sheetId:t,definition:Uv});let i={...n,items:[...n.items,{type:`chart`,chartId:r}]};this.dispatch(`UPDATE_CAROUSEL`,{sheetId:t,figureId:e,definition:i})}addFigureChartToCarousel(e,t,n){let r=this.getChartIdFromFigureId(t);if(!r)return;let i=this.getters.getCarousel(e),a={...i,items:[...i.items,{type:`chart`,chartId:r}]};this.dispatch(`UPDATE_CAROUSEL`,{sheetId:n,figureId:e,definition:a}),this.dispatch(`UPDATE_CHART`,{sheetId:n,chartId:r,figureId:e,definition:this.getters.getChartDefinition(r)}),this.dispatch(`DELETE_FIGURE`,{sheetId:n,figureId:t})}duplicateCarouselChart({carouselId:e,chartId:t,sheetId:n,duplicatedChartId:r}){let i=this.getters.getChart(t);if(!i)return;let a=this.getters.getCarousel(e),o=a.items.findIndex(e=>e.type===`chart`&&e.chartId===t);if(o===-1)return;this.dispatch(`CREATE_CHART`,{chartId:r,figureId:e,sheetId:n,definition:i.getDefinition()});let s=It(a.items,[{type:`chart`,chartId:r}],o+1);this.dispatch(`UPDATE_CAROUSEL`,{sheetId:n,figureId:e,definition:{...a,items:s}})}getCarouselItemId(e){return e.type===`chart`?e.chartId:`carouselDataView`}};async function Az(e){return new Promise((t,n)=>{let r=new Image;r.addEventListener(`load`,()=>{let e=document.createElement(`canvas`);e.width=r.width,e.height=r.height,e.getContext(`2d`)?.drawImage(r,0,0),e.toBlob(t,`image/png`)}),r.addEventListener(`error`,n),r.src=e})}var jz=class extends KL{static layers=[`Clipboard`];static getters=[`getClipboardTextAndImageContent`,`getClipboardId`,`getClipboardTextContent`,`isCutOperation`];status=`invisible`;originSheetId;copiedData;_isCutOperation=!1;clipboardId=new Rd().uuidv4();fileStore;uuidGenerator;constructor(e){super(e),this.fileStore=e.external.fileStore,this.uuidGenerator=new Rd}allowDispatch(e){switch(e.type){case`CUT`:let t=this.getters.getSelectedZones();return this.isCutAllowedOn(t);case`PASTE_FROM_OS_CLIPBOARD`:{let t=this.convertTextToClipboardData(e.clipboardContent.text??``),n=e.pasteOption;return this.isPasteAllowed(e.target,t,{pasteOption:n,isCutOperation:!1})}case`PASTE`:{if(!this.copiedData)return`EmptyClipboard`;let t=e.pasteOption;return this.isPasteAllowed(e.target,this.copiedData,{pasteOption:t,isCutOperation:this._isCutOperation})}case`COPY_PASTE_CELLS_ABOVE`:{let e=this.getters.getSelectedZones();if(e.length>1||e[0].top===0&&e[0].bottom===0)return`InvalidCopyPasteSelection`;let t=this.getters.getSelectedZone(),n=this.getCopiedDataAbove(t);return this.isPasteAllowed(e,n,{isCutOperation:!1})}case`COPY_PASTE_CELLS_ON_LEFT`:{let e=this.getters.getSelectedZones();if(e.length>1||e[0].left===0&&e[0].right===0)return`InvalidCopyPasteSelection`;let t=this.getters.getSelectedZone(),n=this.getCopiedDataOnLeft(t);return this.isPasteAllowed(e,n,{isCutOperation:!1})}case`COPY_PASTE_CELLS_ON_ZONE`:{let e=this.getters.getSelectedZones();if(e.length>1)return`InvalidCopyPasteSelection`;let t=this.getters.getSelectedZone(),n=this.getCopiedDataOnLeft(t);return this.isPasteAllowed(e,n,{isCutOperation:!1})}case`INSERT_CELL`:{let{cut:t,paste:n}=this.getInsertCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);return this.isPasteAllowed(n,r,{isCutOperation:!0})}case`DELETE_CELL`:{let{cut:t,paste:n}=this.getDeleteCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);return this.isPasteAllowed(n,r,{isCutOperation:!0})}}return`Success`}handle(e){switch(e.type){case`COPY`:case`CUT`:let t=this.getters.getSelectedZones();this.status=`visible`,this.originSheetId=this.getters.getActiveSheetId(),this._isCutOperation=e.type===`CUT`,this.copiedData=this.copy(t);break;case`PASTE_FROM_OS_CLIPBOARD`:{this._isCutOperation=!1;let t=e.clipboardContent;if(t.data?.version!==GC()&&(t={...t},delete t.data),t.imageData){let n=this.getters.getActiveSheetId(),r=this.uuidGenerator.uuidv4(),i=t.imageData,a=Nv(this.getters,i.size);this.dispatch(`CREATE_IMAGE`,{definition:i,size:a,col:e.target[0].left,row:e.target[0].top,offset:{x:0,y:0},sheetId:n,figureId:r})}t.data?this.copiedData=t.data:this.copiedData=this.convertTextToClipboardData(t.text??``);let n=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:n,selectTarget:!0,isCutOperation:!1}),this.status=`invisible`,this.copiedData=void 0;break}case`PASTE`:{let t=e.pasteOption;this.paste(e.target,this.copiedData,{pasteOption:t,selectTarget:!0,isCutOperation:this._isCutOperation}),this.status=`invisible`,this._isCutOperation&&=(this.copiedData=void 0,!1);break}case`COPY_PASTE_CELLS_ABOVE`:{let e=this.getters.getSelectedZone();this.originSheetId=this.getters.getActiveSheetId();let t=this.getCopiedDataAbove(e);this.paste([e],t,{isCutOperation:!1,selectTarget:!0})}break;case`COPY_PASTE_CELLS_ON_LEFT`:{let e=this.getters.getSelectedZone();this.originSheetId=this.getters.getActiveSheetId();let t=this.getCopiedDataOnLeft(e);this.paste([e],t,{isCutOperation:!1,selectTarget:!0})}break;case`COPY_PASTE_CELLS_ON_ZONE`:{let e=this.getters.getSelectedZone();this.originSheetId=this.getters.getActiveSheetId();let t=this.getCopiedDataAboveOnLeft(e);this.paste([e],t,{isCutOperation:!1,selectTarget:!0})}break;case`CLEAN_CLIPBOARD_HIGHLIGHT`:this.status=`invisible`;break;case`DELETE_CELL`:{let{cut:t,paste:n}=this.getDeleteCellsTargets(e.zone,e.shiftDimension);if(!Sn(t[0])){this.dispatch(`CLEAR_CELLS`,{target:[e.zone],sheetId:this.getters.getActiveSheetId()});break}let r=this.copy(t,`shiftCells`);this.paste(n,r,{isCutOperation:!0});break}case`INSERT_CELL`:{let{cut:t,paste:n}=this.getInsertCellsTargets(e.zone,e.shiftDimension),r=this.copy(t,`shiftCells`);this.paste(n,r,{isCutOperation:!0});break}case`ADD_COLUMNS_ROWS`:if(this.status=`invisible`,!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;this.isColRowDirtyingClipboard(e.position===`before`?e.base:e.base+1,e.dimension)&&(this.copiedData=void 0);break;case`REMOVE_COLUMNS_ROWS`:if(this.status=`invisible`,!this._isCutOperation||e.sheetId!==this.copiedData?.sheetId)return;for(let t of e.elements)if(this.isColRowDirtyingClipboard(t,e.dimension)){this.copiedData=void 0;break}this.status=`invisible`;break;case`REPEAT_PASTE`:this.paste(e.target,this.copiedData,{isCutOperation:!1,pasteOption:e.pasteOption,selectTarget:!0});break;case`DELETE_SHEET`:if(!this._isCutOperation)return;this.originSheetId===e.sheetId&&(this.copiedData=void 0,this.status=`invisible`);break;default:wu(e)&&(this.status=`invisible`)}}getCopiedDataAbove(e){let t=e.top!==e.bottom,n={...e,bottom:t?e.top:e.top-1,top:t?e.top:e.top-1};return this.copy([n])}getCopiedDataOnLeft(e){let t=e.left!==e.right,n={...e,right:t?e.left:e.left-1,left:t?e.left:e.left-1};return this.copy([n])}getCopiedDataAboveOnLeft(e){let t={...e,right:e.left,bottom:e.top};return this.copy([t])}convertTextToClipboardData(e){let t=this.selectClipboardHandlers({figureId:!0}).concat(this.selectClipboardHandlers({})),n={};for(let{handlerName:r,handler:i}of t){let t=i.convertTextToClipboardData(e);n[r]=t;for(let e of[`sheetId`,`cells`,`zones`,`figureId`])t&&e in t&&(n[e]=t[e])}return n}selectClipboardHandlers(e){let t=`figureId`in e?zF.figureHandlers:zF.cellHandlers;return t.getKeys().map(e=>({handlerName:e,handler:new(t.get(e))(this.getters,this.dispatch)}))}isCutAllowedOn(e){let t=this.getClipboardData(e);for(let{handler:e}of this.selectClipboardHandlers(t)){let n=e.isCutAllowed(t);if(n!==`Success`)return n}return`Success`}isPasteAllowed(e,t,n){for(let{handler:r}of this.selectClipboardHandlers(t)){let i=r.isPasteAllowed(this.getters.getActiveSheetId(),e,t,{...n});if(i!==`Success`)return i}return`Success`}isColRowDirtyingClipboard(e,t){if(!this.copiedData||!this.copiedData.zones)return!1;let{zones:n}=this.copiedData;for(let r of n)if(t===`COL`&&e<=r.right||t===`ROW`&&e<=r.bottom)return!0;return!1}copy(e,t=`copyPaste`){let n={},r=this.getClipboardData(e);for(let{handlerName:e,handler:i}of this.selectClipboardHandlers(r)){let a=i.copy(r,this._isCutOperation,t);n[e]=a;for(let e of[`sheetId`,`cells`,`zones`,`figureId`])a&&e in a&&(n[e]=a[e])}return n}paste(e,t,n){if(!t)return;let r=this.getters.getActiveSheetId(),i=this.selectClipboardHandlers(t),{target:a,zone:o,selectedZones:s}=QT(r,e,t,i,n);o!==void 0&&this.addMissingDimensions(r,o.right-o.left+1,o.bottom-o.top+1,o.left,o.top),ZT(i,t,a,n),n?.selectTarget&&$T(this.selection,e,s)}addMissingDimensions(e,t,n,r,i){let a=n+i-this.getters.getNumberRows(e);a>0&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`ROW`,base:this.getters.getNumberRows(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:a,position:`after`});let o=t+r-this.getters.getNumberCols(e);o>0&&this.dispatch(`ADD_COLUMNS_ROWS`,{dimension:`COL`,base:this.getters.getNumberCols(e)-1,sheetId:e,sheetName:this.getters.getSheetName(e),quantity:o,position:`after`})}getClipboardTextContent(){return this.getPlainTextContent()}getClipboardId(){return this.clipboardId}async getClipboardTextAndImageContent(){let e=await this.getImageContent(),t=e?.type,n={"text/plain":``,"text/html":``};try{n[`text/plain`]=this.getPlainTextContent(),n[`text/html`]=await this.getHTMLContent()}catch{this.ui.notifyUI({type:`danger`,text:`Your selection was too large for the browser to copy it.
119
119
  Please select a smaller zone.`,sticky:!0})}return t&&e&&(n[t]=e),n}getSheetData(){let e={version:GC()};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?.compiledFormula?e?.content||``:e.evaluatedCell?.formattedValue||``).join(` `)).join(`
120
120
  `)||` `}async getHTMLContent(){let e=``,t=this.copiedData?.cells;if(!t)if(this.copiedData?.figureId){let t=this.copiedData.figureId,n=this.getters.getFigureSheetId(t);e=this.getters.getFigure(n,t).tag===`image`?await this.craftImageHTML(t):` `}else e=` `;else if(t.length===1&&t[0].length===1)e=`${this.getters.getCellText(t[0][0].position)}`;else if(t[0][0]){let n=`<table border="1" style="border-collapse:collapse">`;for(let e of t){n+=`<tr>`;for(let t of e){if(!t)continue;let e=W(qv(this.getters.getCellComputedStyle(t.position))),r=this.getters.getCellText(t.position);n+=`<td style="${e}">`+pC(r)+`</td>`}n+=`</tr>`}n+=`</table>`,e=n}else return``;let n=JSON.stringify(this.getSheetData());return`<div data-osheet-clipboard-id='${this.clipboardId}' data-osheet-clipboard='${pC(n)}'>${e}</div>`}readFileAsDataURL(e){return new Promise(t=>{let n=new FileReader;n.onload=()=>t(n.result),n.readAsDataURL(e)})}async craftImageHTML(e){if(!this.fileStore)return` `;let t=this.getters.getImage(e).path,n=await this.fileStore?.getFile(t)||null;return n?`<img src="${pC(await this.readFileAsDataURL(n))}" />`:` `}async getImageContent(){let e=this.copiedData?.figureId;if(!e)return;let t=this.getters.getFigureSheetId(e),n=this.getters.getFigure(t,e),r;if(n.tag===`image`){if(!this.fileStore)return;let t=this.getters.getImage(e).path;if(r=await this.fileStore?.getFile(t),r.type!==`image/png`){if(r.size>5242880){this.ui.notifyUI({text:j(`The file you are trying to copy is too large (>%sMB).
@@ -953,4 +953,4 @@ If you meant to create a named range, named range cannot have the same name as a
953
953
  <Relationships xmlns="${ef.Relationships}">
954
954
  <Relationship ${q(e)} />
955
955
  </Relationships>
956
- `),`_rels/.rels`)}function KU(e){let t={},n=[];for(let r of e.sheets){let e=r.name.slice(0,31);e=Kt(e,n,{compute:(e,t)=>e.slice(0,31-String(t).length)+t}),n.push(e),e!==r.name&&(t[r.name]=e,r.name=e)}if(!Object.keys(t).length)return e;let r=Object.keys(t).sort((e,t)=>t.length-e.length),i=JSON.stringify(e);for(let e of r){let n=RegExp(`'?${Ze(e)}'?!`,`g`);i=i.replaceAll(n,n=>{let r=t[e];return n.replace(e,r)})}return JSON.parse(i)}function qU(e){for(let t of e.sheets)t.tables=t.tables.filter(e=>Ln(yn(e.range)).numberOfRows>1);return e}var JU=class e extends lr{corePlugins=[];statefulUIPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;coreViewPluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},t={},n=[],r=new Rd,i=!1){let a=performance.now();console.debug(`##### Model creation #####`),super(),Mi(),n=nw(e,n);let o=JC(e,i);this.state=new sH,this.uuidGenerator=r,this.config=this.setupConfig(t),this.getters={isReadonly:()=>this.config.mode===`readonly`||this.config.mode===`dashboard`,isDashboard:()=>this.config.mode===`dashboard`},this.session=this.setupSession(o.revisionId),this.coreGetters={},this.range=new iH(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.coreGetters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.coreGetters.getRangeData=this.range.getRangeData.bind(this.range),this.coreGetters.getRangeDataFromXc=this.range.getRangeDataFromXc.bind(this.range),this.coreGetters.getRangeDataFromZone=this.range.getRangeDataFromZone.bind(this.range),this.coreGetters.getRangeFromRangeData=this.range.getRangeFromRangeData.bind(this.range),this.coreGetters.getRangeFromZone=this.range.getRangeFromZone.bind(this.range),this.coreGetters.recomputeRanges=this.range.recomputeRanges.bind(this.range),this.coreGetters.isRangeValid=this.range.isRangeValid.bind(this.range),this.coreGetters.extendRange=this.range.extendRange.bind(this.range),this.coreGetters.getRangesUnion=this.range.getRangesUnion.bind(this.range),this.coreGetters.removeRangesSheetPrefix=this.range.removeRangesSheetPrefix.bind(this.range),this.coreGetters.copyFormulaStringForSheet=this.range.copyFormulaStringForSheet.bind(this.range),this.selection=new oH(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 zz.getAll())this.setupCorePlugin(e,o);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(n);for(let e of Hz.getAll()){let t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(let e of Vz.getAll()){let t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(let e of Bz.getAll()){let t=this.setupUiPlugin(e);this.handlers.push(t),this.uiHandlers.push(t)}if(this.config.mode!==`export_verification`&&(this.dispatch(`START`),this.selection.observe(this,{handleEvent:()=>this.trigger(`update`)}),this.setupSessionEvents(),this.joinSession(),t.snapshotRequested||e[`[Content_Types].xml`]&&!this.getters.isReadonly())){let e=performance.now();console.debug(`Snapshot requested`),this.session.snapshot(this.exportData()),console.debug(`Snapshot taken in`,performance.now()-e,`ms`)}console.debug(`Model created in`,performance.now()-a,`ms`),console.debug(`######`)}joinSession(){this.session.join(this.config.client)}async leaveSession(){let e=this.getters.isReadonly()?void 0:xt(()=>this.exportData());await this.session.leave(e)}setupUiPlugin(e){let t=new e(this.uiPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}for(let n of e.layers)this.renderers[n]||(this.renderers[n]=[]),this.renderers[n].push(t);return t}setupCoreViewPlugin(e){let t=new e(this.coreViewPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}return t}setupCorePlugin(e,t){let n=new e(this.corePluginConfig);for(let t of e.getters){if(!(t in n))throw Error(`Invalid getter name: ${t} for plugin ${n.constructor}`);if(t in this.coreGetters)throw Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=n[t].bind(n)}n.import(t),this.corePlugins.push(n),this.coreHandlers.push(n),this.handlers.push(n)}onRemoteRevisionReceived({commands:e}){for(let t of e){let e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new tz(tH({initialRevisionId:e,recordChanges:this.state.recordChanges.bind(this.state),dispatch:e=>{if(!this.checkDispatchAllowedRemoteCommand(e).isSuccessful){this.dispatchToHandlers(this.coreHandlers,{type:`UNDO`,commands:[e]});return}this.isReplayingCommand=!0,this.dispatchToHandlers(this.coreHandlers,e),this.isReplayingCommand=!1}}),this.config.transportService,e,new KV(this.getters))}setupSessionEvents(){this.session.on(`remote-revision-received`,this,this.onRemoteRevisionReceived),this.session.on(`revision-undone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`UNDO`,{commands:e}),this.finalize()}),this.session.on(`revision-redone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`REDO`,{commands:e}),this.finalize()}),this.session.on(`unexpected-revision-id`,this,()=>this.trigger(`unexpected-revision-id`)),this.session.on(`collaborative-event-received`,this,()=>{this.trigger(`update`)})}setupConfig(e){let t=e.client||{id:this.uuidGenerator.smallUuid(),name:j(`Anonymous`).toString()},n=e.transportService||new ZB,r=e.mode===`readonly`||e.mode===`dashboard`||e.mode===`export_verification`;return{...e,mode:e.mode||`normal`,custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:r?new qV(n):n,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger(`notify-ui`,e),raiseBlockingErrorUI:e=>this.trigger(`raise-error-ui`,{text:e}),customColors:e.customColors||[]}}setupExternalConfig(e){let t=e.loadLocales||(()=>Promise.resolve(Io));return{...e,loadLocales:t}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,canDispatch:this.canDispatch,custom:this.config.custom,external:this.config.external}}setupCoreViewPluginConfig(){return{getters:this.getters,stateObserver:this.state,custom:this.config.custom,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,canDispatch:this.canDispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}checkDispatchAllowed(e){let t=wu(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return this.processCommandResults(t)}processCommandResults(e){return e.some(e=>e!==`Success`)?new Eu(e.flat()):Eu.Success}checkDispatchAllowedRemoteCommand(e){let t=this.coreHandlers.map(t=>t.allowDispatch(e));return this.processCommandResults(t)}checkDispatchAllowedCoreCommand(e){return this.handlers.map(t=>t.allowDispatch(e))}checkDispatchAllowedLocalCommand(e){return this.uiHandlers.map(t=>t.allowDispatch(e))}finalize(){this.status=3;for(let e of this.handlers)e.finalize();this.status=0,this.trigger(`command-finalized`)}canDispatch=(e,t)=>this.checkDispatchAllowed(YU(e,t));dispatch=(e,t)=>{let n=YU(e,t),r=this.status;if(this.getters.isReadonly()&&!Tu(n))return new Eu(`Readonly`);if(!this.session.canApplyOptimisticUpdate())return new Eu(`WaitingSessionConfirmation`);switch(r){case 0:let t=this.checkDispatchAllowed(n);if(!t.isSuccessful)return this.trigger(`update`),this.trigger(`command-rejected`,{command:n,result:t}),t;this.status=1;let{changes:r,commands:i}=this.state.recordChanges(()=>{let t=performance.now();wu(n)&&this.state.addCommand(n),this.dispatchToHandlers(this.handlers,n),this.finalize();let r=performance.now()-t;r>5&&console.debug(e,r,`ms`)});this.session.save(n,i,r),this.status=0,this.trigger(`update`);break;case 1:if(wu(n)){let e=this.checkDispatchAllowed(n);if(!e.isSuccessful)return e;this.state.addCommand(n)}this.dispatchToHandlers(this.handlers,n);break;case 3:throw Error(`Cannot dispatch commands in the finalize state`);case 2:if(wu(n))throw Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,n)}return Eu.Success};dispatchFromCorePlugin=(e,t)=>{let n=YU(e,t),r=this.status;this.status=2;let i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,n),this.status=r,Eu.Success};dispatchToHandlers(e,t){let n=wu(t);for(let r of e)!n&&r instanceof SI||r.beforeHandle(t);for(let r of e)!n&&r instanceof SI||r.handle(t);this.trigger(`command-dispatched`,t)}drawLayer(e,t){let n=this.renderers[t];if(n)for(let r of n)e.ctx.save(),r.drawLayer(e,t),e.ctx.restore()}exportData(){let t=this._exportData(!0),n=this._exportData(!1),r={...this.config,mode:`export_verification`,client:{id:`exporter`,name:`exporter`},snapshotRequested:!1,transportService:new ZB};return T(n,new e(x(t),r)._exportData(!1))?t:(n.isNotSquishable=!0,n)}_exportData(e){let t=lw();for(let n of this.handlers)n instanceof SI&&n.export(t,e);return t.revisionId=this.session.getRevisionId()||`START_REVISION`,t=x(t),t}updateMode(e){this.config.mode=e,this.trigger(`update`)}async exportXLSX(){this.dispatch(`EVALUATE_CELLS`);let e=dw();for(let t of this.handlers)t instanceof xI&&await t.exportForExcel(e);return e=x(e),LU(e)}};function YU(e,t={}){let n=x(t);return n.type=e,n}function XU(e){return!OO.includes(e.horizontalGroupBy)||!OO.includes(e.verticalGroupBy)?`InvalidChartDefinition`:`Success`}let ZU={sequence:110,dataSeriesLimit:1,allowedDefinitionKeys:[...Kp.commonKeys,`dataSource`,`dataSetStyles`,`showValues`,`colorScale`,`missingValueColor`,`axesDesign`,`horizontalGroupBy`,`verticalGroupBy`,`legendPosition`],validateDefinition(e,t){return e.checkValidations(t,XU)},fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){let n=`left`;return e.legendPosition===`right`&&(n=`right`),{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},title:e.title||{text:``},type:`calendar`,showValues:e.showValues,axesDesign:e.axesDesign,legendPosition:n,horizontalGroupBy:`day_of_week`,verticalGroupBy:`month_number`}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractData:n}){let r=t_(t,n(),e),{labels:i,datasets:a}=mp(t,r);return{chartJsConfig:{type:`calendar`,data:{labels:i,datasets:a},options:{...rh,indexAxis:`x`,layout:N_(t,r),scales:Yf(t,a),plugins:{title:Q_(t,e),legend:{display:!1},tooltip:rv(t,r),chartShowValuesPlugin:q_(t,r),chartColorScalePlugin:Xf(t,r),background:{color:t.background}}}}}}},QU={sequence:15,allowedDefinitionKeys:[...Kp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`aggregated`,`axesDesign`,`showValues`,`hideDataMarkers`,`zoomable`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){return{...t,backgroundColor:zm(t.background||`#FFFFFF`),fontColor:zm(xf(t.background)),dataSets:n,labelRange:r,verticalAxis:Df(t)}},getDefinitionFromContextCreation(e,t){let n=e.dataSetStyles??{};if(e.dataSource?.type===`range`){let t=e.dataSource?.dataSets?.[0]?.dataSetId;for(let r of e.dataSource?.dataSets||[])n[r.dataSetId]={...e.dataSetStyles?.[r.dataSetId]||{},type:r.dataSetId===t?`bar`:`line`}}return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:n,aggregated:e.aggregated,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`combo`,axesDesign:e.axesDesign,showValues:e.showValues,hideDataMarkers:e.hideDataMarkers,zoomable:e.zoomable,humanize:e.humanize}},getRuntime(e,t,{extractData:n},r,i){let a=Qg(t,n(),e);return{chartJsConfig:{type:`bar`,data:{labels:a.labels,datasets:yp(t,a)},options:{...rh,layout:M_(t,a),scales:Jf(t,a),plugins:{title:Q_(t,e),legend:z_(t,a),tooltip:nv(t,a),chartShowValuesPlugin:K_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},$U={sequence:100,dataSeriesLimit:1,allowedDefinitionKeys:[...Kp.commonKeys,`dataSource`,`dataSetStyles`,`axesDesign`,`legendPosition`,`horizontal`,`aggregated`,`showValues`,`funnelColors`,`cumulative`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},aggregated:e.aggregated??!1,legendPosition:`none`,title:e.title||{text:``},type:`funnel`,showValues:e.showValues,axesDesign:e.axesDesign,funnelColors:e.funnelColors,horizontal:!0,cumulative:e.cumulative??!0,humanize:e.humanize}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractData:n},r,i){let a=s_(t,n(),e);return{chartJsConfig:{type:`funnel`,data:{labels:a.labels,datasets:Sp(t,a)},options:{...rh,indexAxis:`y`,layout:M_(t,a),scales:ap(t,a),plugins:{title:Q_(t,e),legend:{display:!1},tooltip:uv(t,a),chartShowValuesPlugin:K_(t,a),background:{color:t.background}},...i}}}}},eW={sequence:90,dataSeriesLimit:1,allowedDefinitionKeys:[...Kp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`colorScale`,`missingValueColor`,`region`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`geo`,humanize:e.humanize}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractData:n},r,i){let a=o_(t,n(),e);return{chartJsConfig:{type:`choropleth`,data:{datasets:xp(t,a)},options:{...rh,layout:M_(t,a),scales:ip(t,a),plugins:{title:Q_(t,e),tooltip:lv(t,a),legend:{display:!1},background:{color:t.background}},...i}}}}},tW={sequence:80,dataSeriesLimit:2,allowedDefinitionKeys:[...Kp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showValues`,`aggregated`,`axesDesign`,`stacked`,`horizontal`],fromStrDefinition:e=>({...e,horizontal:!0,stacked:!0}),toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`pyramid`,axesDesign:e.axesDesign,horizontal:!0,stacked:!0,showValues:e.showValues,humanize:e.humanize}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){if(t.dataSource.type!==`range`)return;let{dataSetsValues:i}=n_(t,CO(e,t.dataSource),e),a=Math.max(...i.map(e=>Math.max(...e.data.map(e=>U(e)?Math.abs(e.value):-1/0))));return{...t,horizontal:!0,backgroundColor:zm(t.background||`#FFFFFF`),fontColor:zm(xf(t.background)),dataSets:n,labelRange:r,verticalAxis:Df(t),maxValue:a}},getRuntime(e,t,{extractData:n},r,i){let a=n_(t,n(),e);return{chartJsConfig:{type:`bar`,data:{labels:a.labels,datasets:pp(t,a)},options:{...rh,indexAxis:`y`,layout:M_(t,a),scales:np(t,a),plugins:{title:Q_(t,e),legend:F_(t,a),tooltip:sv(t,a),chartShowValuesPlugin:Y_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},nW={sequence:80,allowedDefinitionKeys:[...Kp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showValues`,`aggregated`,`stacked`,`fillArea`,`hideDataMarkers`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},stacked:e.stacked??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`radar`,fillArea:e.fillArea??!1,showValues:e.showValues??!1,hideDataMarkers:e.hideDataMarkers,humanize:e.humanize}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){return{...t,backgroundColor:zm(t.background||`#FFFFFF`),fontColor:zm(xf(t.background)),dataSets:n,labelRange:r}},getRuntime(e,t,{extractData:n},r,i){let a=a_(t,n(),e);return{chartJsConfig:{type:`radar`,data:{labels:a.labels,datasets:bp(t,a)},options:{...rh,layout:M_(t,a),scales:rp(t,a),plugins:{title:Q_(t,e),legend:V_(t,a),tooltip:cv(t,a),chartShowValuesPlugin:K_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},rW={sequence:60,allowedDefinitionKeys:[...Kp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showValues`,`labelsAsText`,`aggregated`,`axesDesign`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},labelsAsText:e.labelsAsText??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`scatter`,aggregated:e.aggregated??!1,axesDesign:e.axesDesign,showValues:e.showValues,humanize:e.humanize}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){return{...t,backgroundColor:zm(t.background||`#FFFFFF`),fontColor:zm(xf(t.background)),dataSets:n,labelRange:r,verticalAxis:Df(t)}},getRuntime(e,t,{extractData:n},r,i){let a=r_(t,n(),e);return{chartJsConfig:{type:`line`,data:{labels:a.labels,datasets:_p(t,a)},options:{...rh,layout:M_(t,a),scales:ep(t,a),plugins:{title:Q_(t,e),legend:R_(t,a),tooltip:iv(t,a),chartShowValuesPlugin:K_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},iW={sequence:30,allowedDefinitionKeys:[...Kp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showValues`,`showLabels`,`valuesDesign`,`groupColors`,`pieHolePercentage`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSetStyles:e.dataSetStyles??{},dataSource:t.fromHierarchicalContextCreation(e),legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`sunburst`,showValues:e.showValues,showLabels:e.showLabels,valuesDesign:e.valuesDesign,groupColors:e.groupColors,humanize:e.humanize,pieHolePercentage:e.pieHolePercentage}},getContextCreation(e,t,n){return{...e,...t.getHierarchicalContextCreation(n)}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractHierarchicalData:n},r,i){let a=c_(t,n(),e);return{chartJsConfig:{type:`doughnut`,data:{datasets:wp(t,a)},options:{cutout:t.pieHolePercentage===void 0?`25%`:`${t.pieHolePercentage}%`,...rh,layout:M_(t,a),plugins:{title:Q_(t,e),legend:H_(t,a),tooltip:dv(t,a),sunburstLabelsPlugin:J_(t,a),sunburstHoverPlugin:{enabled:!0},background:{color:t.background}},...i}}}}},aW={sequence:100,allowedDefinitionKeys:[...Kp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showHeaders`,`headerDesign`,`showLabels`,`valuesDesign`,`coloringOptions`,`showValues`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSetStyles:e.dataSetStyles??{},dataSource:t.fromHierarchicalContextCreation(e),legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`treemap`,showValues:e.showValues,showHeaders:e.showHeaders,headerDesign:e.headerDesign,showLabels:e.showLabels,valuesDesign:e.valuesDesign,coloringOptions:e.treemapColoringOptions,humanize:e.humanize}},getContextCreation(e,t,n){return{...e,treemapColoringOptions:e.coloringOptions,...t.getHierarchicalContextCreation(n)}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractHierarchicalData:n},r,i){let a=c_(t,n(),e);return{chartJsConfig:{type:`treemap`,data:{labels:a.labels,datasets:kp(t,a)},options:{...rh,layout:M_(t,a),plugins:{title:Q_(t,e),legend:{display:!1},tooltip:fv(t,a),background:{color:t.background}},...i}}}}};sS.add(`bar`,_v),sS.add(`combo`,QU),sS.add(`line`,Ov),sS.add(`pie`,kv),sS.add(`scorecard`,nm),sS.add(`gauge`,Cv),sS.add(`scatter`,rW),sS.add(`waterfall`,Av),sS.add(`pyramid`,tW),sS.add(`radar`,nW),sS.add(`geo`,eW),sS.add(`funnel`,$U),sS.add(`sunburst`,iW),sS.add(`treemap`,aW),sS.add(`calendar`,ZU),Hv.add(`line`,{matcher:e=>e.type===`line`&&!e.stacked&&!e.fillArea,displayName:j(`Line`),chartType:`line`,chartSubtype:`line`,subtypeDefinition:{stacked:!1,fillArea:!1},category:`line`,preview:`o-spreadsheet-ChartPreview.LINE_CHART`}).add(`stacked_line`,{matcher:e=>e.type===`line`&&!e.fillArea&&!!e.stacked,displayName:j(`Stacked Line`),chartType:`line`,chartSubtype:`stacked_line`,subtypeDefinition:{stacked:!0,fillArea:!1},category:`line`,preview:`o-spreadsheet-ChartPreview.STACKED_LINE_CHART`}).add(`area`,{matcher:e=>e.type===`line`&&!e.stacked&&!!e.fillArea,displayName:j(`Area`),chartType:`line`,chartSubtype:`area`,subtypeDefinition:{stacked:!1,fillArea:!0},category:`area`,preview:`o-spreadsheet-ChartPreview.AREA_CHART`}).add(`stacked_area`,{matcher:e=>e.type===`line`&&e.stacked&&!!e.fillArea,displayName:j(`Stacked Area`),chartType:`line`,chartSubtype:`stacked_area`,subtypeDefinition:{stacked:!0,fillArea:!0},category:`area`,preview:`o-spreadsheet-ChartPreview.STACKED_AREA_CHART`}).add(`scatter`,{displayName:j(`Scatter`),chartType:`scatter`,chartSubtype:`scatter`,category:`misc`,preview:`o-spreadsheet-ChartPreview.SCATTER_CHART`}).add(`column`,{matcher:e=>e.type===`bar`&&!e.stacked&&!e.horizontal,displayName:j(`Column`),chartType:`bar`,chartSubtype:`column`,subtypeDefinition:{stacked:!1,horizontal:!1},category:`column`,preview:`o-spreadsheet-ChartPreview.COLUMN_CHART`}).add(`stacked_column`,{matcher:e=>e.type===`bar`&&e.stacked&&!e.horizontal,displayName:j(`Stacked Column`),chartType:`bar`,chartSubtype:`stacked_column`,subtypeDefinition:{stacked:!0,horizontal:!1},category:`column`,preview:`o-spreadsheet-ChartPreview.STACKED_COLUMN_CHART`}).add(`bar`,{matcher:e=>e.type===`bar`&&!e.stacked&&!!e.horizontal,displayName:j(`Bar`),chartType:`bar`,chartSubtype:`bar`,subtypeDefinition:{horizontal:!0,stacked:!1},category:`bar`,preview:`o-spreadsheet-ChartPreview.BAR_CHART`}).add(`stacked_bar`,{matcher:e=>e.type===`bar`&&e.stacked&&!!e.horizontal,displayName:j(`Stacked Bar`),chartType:`bar`,chartSubtype:`stacked_bar`,subtypeDefinition:{horizontal:!0,stacked:!0},category:`bar`,preview:`o-spreadsheet-ChartPreview.STACKED_BAR_CHART`}).add(`combo`,{displayName:j(`Combo`),chartSubtype:`combo`,chartType:`combo`,category:`line`,preview:`o-spreadsheet-ChartPreview.COMBO_CHART`}).add(`pie`,{matcher:e=>e.type===`pie`&&!e.isDoughnut,displayName:j(`Pie`),chartSubtype:`pie`,chartType:`pie`,subtypeDefinition:{isDoughnut:!1},category:`pie`,preview:`o-spreadsheet-ChartPreview.PIE_CHART`}).add(`doughnut`,{matcher:e=>e.type===`pie`&&!!e.isDoughnut,displayName:j(`Doughnut`),chartSubtype:`doughnut`,chartType:`pie`,subtypeDefinition:{isDoughnut:!0},category:`pie`,preview:`o-spreadsheet-ChartPreview.DOUGHNUT_CHART`}).add(`gauge`,{displayName:j(`Gauge`),chartSubtype:`gauge`,chartType:`gauge`,category:`misc`,preview:`o-spreadsheet-ChartPreview.GAUGE_CHART`}).add(`scorecard`,{displayName:j(`Scorecard`),chartSubtype:`scorecard`,chartType:`scorecard`,category:`misc`,preview:`o-spreadsheet-ChartPreview.SCORECARD_CHART`}).add(`waterfall`,{displayName:j(`Waterfall`),chartSubtype:`waterfall`,chartType:`waterfall`,category:`misc`,preview:`o-spreadsheet-ChartPreview.WATERFALL_CHART`}).add(`pyramid`,{displayName:j(`Population Pyramid`),chartSubtype:`pyramid`,chartType:`pyramid`,category:`misc`,preview:`o-spreadsheet-ChartPreview.POPULATION_PYRAMID_CHART`}).add(`radar`,{matcher:e=>e.type===`radar`&&!e.fillArea,displayName:j(`Radar`),chartSubtype:`radar`,chartType:`radar`,subtypeDefinition:{fillArea:!1},category:`misc`,preview:`o-spreadsheet-ChartPreview.RADAR_CHART`}).add(`filled_radar`,{matcher:e=>e.type===`radar`&&!!e.fillArea,displayName:j(`Filled Radar`),chartType:`radar`,chartSubtype:`filled_radar`,subtypeDefinition:{fillArea:!0},category:`misc`,preview:`o-spreadsheet-ChartPreview.FILLED_RADAR_CHART`}).add(`geo`,{displayName:j(`Geo Chart`),chartSubtype:`geo`,chartType:`geo`,category:`misc`,preview:`o-spreadsheet-ChartPreview.GEO_CHART`}).add(`funnel`,{displayName:j(`Funnel`),chartSubtype:`funnel`,chartType:`funnel`,category:`misc`,preview:`o-spreadsheet-ChartPreview.FUNNEL_CHART`}).add(`sunburst`,{matcher:e=>e.type===`sunburst`,displayName:j(`Sunburst`),chartSubtype:`sunburst`,chartType:`sunburst`,category:`hierarchical`,preview:`o-spreadsheet-ChartPreview.SUNBURST_CHART`}).add(`treemap`,{matcher:e=>e.type===`treemap`,displayName:j(`Tree Map`),chartType:`treemap`,chartSubtype:`treemap`,category:`hierarchical`,preview:`o-spreadsheet-ChartPreview.TREE_MAP_CHART`}).add(`calendar`,{displayName:j(`Calendar`),chartSubtype:`calendar`,chartType:`calendar`,category:`misc`,preview:`o-spreadsheet-ChartPreview.CALENDAR_CHART`});var oW=class extends WL{queuedBordersToAdd={};copy(e){let t=e.sheetId;if(e.zones.length===0)return;let{rowsIndexes:n,columnsIndexes:r}=e,i=[];for(let e of n){let n=[];for(let i of r){let r={col:i,row:e,sheetId:t};n.push(this.getters.getCellBorder(r))}i.push(n)}return{borders:i}}paste(e,t,n){let r=e.sheetId;if(n.pasteOption===`asValue`)return;let i=e.zones;if(!n.isCutOperation)this.pasteFromCopy(r,i,t.borders);else{let{left:e,top:n}=i[0];this.pasteZone(r,e,n,t.borders)}this.executeQueuedChanges(r)}pasteZone(e,t,n,r){for(let[i,a]of r.entries())for(let[r,o]of a.entries()){let a={col:t+r,row:n+i,sheetId:e};this.pasteBorder(o,a)}}pasteBorder(e,t){let n={...this.getters.getCellBorder(t),...e},r=JSON.stringify(n);this.queuedBordersToAdd[r]||(this.queuedBordersToAdd[r]=[]),this.queuedBordersToAdd[r].push(D(t))}executeQueuedChanges(e){for(let t in this.queuedBordersToAdd){let n=this.queuedBordersToAdd[t],r=JSON.parse(t),i=cn(n,[]);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,target:i,border:r})}this.queuedBordersToAdd={}}},sW=class extends UL{copy(e){}},cW=class extends sW{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);if(n.tag!==`carousel`)return;let r={...n},i=this.getters.getCarousel(e.figureId),a={};for(let e of i.items)if(e.type===`chart`){let t=this.getters.getChart(e.chartId);if(!t)throw Error(`No chart for the given id: ${e.chartId}`);a[e.chartId]=t}return{figureId:e.figureId,copiedFigure:r,copiedCarousel:i,copiedCharts:a,copiedSheetId:t}}getPasteTarget(e){return{zones:[],figureId:new Rd().smallUuid(),sheetId:e}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=e.sheetId,{width:o,height:s}=t.copiedFigure,c=this.getters.getMaxAnchorOffset(a,s,o),{left:l,top:u}=r[0],d={x:0,y:0};l>c.col&&(l=c.col,d.x=c.offset.x),u>c.row&&(u=c.row,d.y=c.offset.y),this.dispatch(`CREATE_CAROUSEL`,{figureId:i,sheetId:a,definition:{items:[]},col:l,row:u,offset:d,size:{height:s,width:o}});let f=new Rd,p=x(t.copiedCarousel.items);for(let e of p){if(e.type!==`chart`)continue;let n=t.copiedCharts[e.chartId],r=f.smallUuid(),o=yO.fromDefinition(this.getters,a,n.copyInSheetId(a)).getDefinition();this.dispatch(`CREATE_CHART`,{figureId:i,chartId:r,sheetId:a,definition:o}),e.chartId=r}this.dispatch(`UPDATE_CAROUSEL`,{sheetId:a,figureId:i,definition:{...t.copiedCarousel,items:p}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.copiedSheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},lW=class extends sW{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);if(n.tag!==`chart`)return;let r={...n},i=this.getters.getChartFromFigureId(e.figureId);if(!i)throw Error(`No chart for the given id: ${e.figureId}`);let a=i;return{figureId:e.figureId,copiedFigure:r,copiedChart:a}}getPasteTarget(e,t,n,r){return{zones:[],figureId:new Rd().smallUuid(),sheetId:e}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=e.sheetId,{width:o,height:s}=t.copiedFigure,c=t.copiedChart,l=yO.fromDefinition(this.getters,a,c.copyInSheetId(a)).getDefinition();l=yO.fromStrDefinition(this.getters,a,l).getDefinition();let u=this.getters.getMaxAnchorOffset(a,s,o),{left:d,top:f}=r[0],p={x:0,y:0};d>u.col&&(d=u.col,p.x=u.offset.x),f>u.row&&(f=u.row,p.y=u.offset.y),this.dispatch(`CREATE_CHART`,{figureId:i,chartId:new Rd().smallUuid(),sheetId:a,definition:l,col:d,row:f,offset:p,size:{height:s,width:o}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.copiedChart.sheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},uW=class extends WL{uuidGenerator=new Rd;queuedChanges={};copy(e){if(!e.zones.length)return;let{rowsIndexes:t,columnsIndexes:n}=e,r=e.sheetId,i=[];for(let e of t){let t=[];for(let i of n){let n=Array.from(this.getters.getRulesByCell(r,i,e));t.push({position:{col:i,row:e,sheetId:r},rules:n})}i.push(t)}return{cfRules:i}}paste(e,t,n){if(this.queuedChanges={},n.pasteOption===`asValue`)return;let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t):this.pasteFromCopy(i,r,t.cfRules,n),this.executeQueuedChanges()}pasteFromCut(e,t,n){let r=t[0];this.pasteZone(e,r.left,r.top,n.cfRules,{isCutOperation:!0})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){let o={col:t+r,row:n+a,sheetId:e};this.pasteCf(s,o,i?.isCutOperation)}}pasteCf(e,t,n){if(e?.rules&&e.rules.length>0){let r=D(e.position),i=D(t);for(let a of e.rules){let o=[];if(n&&o.push(r),e.position.sheetId===t.sheetId)this.adaptCFRules(e.position.sheetId,a,[i],o);else{this.adaptCFRules(e.position.sheetId,a,[],o);let n=this.getCFToCopyTo(t.sheetId,a);this.adaptCFRules(t.sheetId,n,[i],[])}}}}adaptCFRules(e,t,n,r){this.queuedChanges[e]||(this.queuedChanges[e]=[]);let i=this.queuedChanges[e].find(e=>e.cf.id===t.id);i?(i.toAdd.push(...n),i.toRemove.push(...r)):this.queuedChanges[e].push({toAdd:n,toRemove:r,cf:t})}executeQueuedChanges(){for(let e in this.queuedChanges)for(let{toAdd:t,toRemove:n,cf:r}of this.queuedChanges[e]){let i=this.getters.getAdaptedCfRanges(e,r,t,n);if(i){if(i.length===0){this.dispatch(`REMOVE_CONDITIONAL_FORMAT`,{id:r.id,sheetId:e});continue}this.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{id:r.id,rule:r.rule,stopIfTrue:r.stopIfTrue},ranges:i,sheetId:e})}}}getCFToCopyTo(e,t){let n=this.getters.getConditionalFormats(e).find(e=>e.stopIfTrue===t.stopIfTrue&&T(e.rule,t.rule)),r=this.queuedChanges[e];return!n&&r&&(n=r.find(e=>e.cf.stopIfTrue===t.stopIfTrue&&T(e.cf.rule,t.rule))?.cf),n||{...t,id:this.uuidGenerator.smallUuid(),ranges:[]}}},dW=class extends WL{uuidGenerator=new Rd;queuedChanges={};copy(e){let{rowsIndexes:t,columnsIndexes:n}=e,r=e.sheetId,i=[];for(let e of t){let t=[];for(let i of n){let n={sheetId:r,col:i,row:e},a=this.getters.getValidationRuleForCell(n);t.push({position:n,rule:a})}i.push(t)}return{dvRules:i}}paste(e,t,n){if(this.queuedChanges={},n.pasteOption)return;let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t):this.pasteFromCopy(i,r,t.dvRules),this.executeQueuedChanges()}pasteFromCut(e,t,n){let r=t[0];this.pasteZone(e,r.left,r.top,n.dvRules,{isCutOperation:!0})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){let o={col:t+r,row:n+a,sheetId:e};this.pasteDataValidation(s,o,i?.isCutOperation)}}pasteDataValidation(e,t,n){if(e){let r=D(t),i=D(e.position),a=e.rule;if(!a){let e=this.getters.getValidationRuleForCell(t);e&&this.adaptDataValidationRule(t.sheetId,e,[],[r]);return}let o=[];if(n&&o.push(i),e.position.sheetId===t.sheetId){let n=this.getDataValidationRuleToCopyTo(t.sheetId,a,!1);this.adaptDataValidationRule(e.position.sheetId,n,[r],o)}else{let n=this.getters.getValidationRuleForCell(e.position);n&&this.adaptDataValidationRule(e.position.sheetId,n,[],o);let i=this.getDataValidationRuleToCopyTo(t.sheetId,a);this.adaptDataValidationRule(t.sheetId,i,[r],[])}}}getDataValidationRuleToCopyTo(e,t,n=!0){let r=this.getters.getDataValidationRules(e).find(e=>T(t.criterion,e.criterion)&&t.isBlocking===e.isBlocking),i=this.queuedChanges[e];return!r&&i&&(r=i.find(e=>T(t.criterion,e.rule.criterion)&&t.isBlocking===e.rule.isBlocking)?.rule),r||{...t,id:n?this.uuidGenerator.smallUuid():t.id,ranges:[]}}adaptDataValidationRule(e,t,n,r){this.queuedChanges[e]||(this.queuedChanges[e]=[]);let i=this.queuedChanges[e].find(e=>e.rule.id===t.id);i?(i.toAdd.push(...n),i.toRemove.push(...r)):this.queuedChanges[e].push({toAdd:n,toRemove:r,rule:t})}executeQueuedChanges(){for(let e in this.queuedChanges)for(let{toAdd:t,toRemove:n,rule:r}of this.queuedChanges[e]){let i=cn([...cn(r.ranges.map(e=>e.zone),n),...t],[]);if(i.length===0){this.dispatch(`REMOVE_DATA_VALIDATION_RULE`,{sheetId:e,id:r.id});continue}this.dispatch(`ADD_DATA_VALIDATION_RULE`,{rule:{id:r.id,criterion:r.criterion,isBlocking:r.isBlocking},ranges:i.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e})}}},fW=class extends sW{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);let r={...n};if(n.tag!==`image`)return;let i=x(this.getters.getImage(e.figureId));return{figureId:e.figureId,copiedFigure:r,copiedImage:i,sheetId:t}}getPasteTarget(e,t,n,r){return{sheetId:e,zones:[],figureId:new Rd().smallUuid()}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=this.getters.getActiveSheetId(),{width:o,height:s}=t.copiedFigure,c=x(t.copiedImage),l=this.getters.getMaxAnchorOffset(a,s,o),{left:u,top:d}=r[0],f={x:0,y:0};u>l.col&&(u=l.col,f.x=l.offset.x),d>l.row&&(d=l.row,f.y=l.offset.y),this.dispatch(`CREATE_IMAGE`,{figureId:i,sheetId:a,col:u,row:d,offset:f,size:{height:s,width:o},definition:c}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.sheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},pW=class extends WL{copy(e){let t=this.getters.getActiveSheetId(),{rowsIndexes:n,columnsIndexes:r}=e,i=[];for(let e of n){let n=[];for(let i of r){let r={col:i,row:e,sheetId:t};n.push(this.getters.getMerge(r))}i.push(n)}return{merges:i,sheetId:t}}paste(e,t,n){if(n.isCutOperation){let e=t.merges.flat().filter(w);this.dispatch(`REMOVE_MERGE`,{sheetId:t.sheetId,target:e})}this.pasteFromCopy(e.sheetId,e.zones,t.merges,n)}pasteZone(e,t,n,r){for(let[i,a]of r.entries())for(let[r,o]of a.entries()){let a={col:t+r,row:n+i,sheetId:e};this.pasteMerge(o,a)}}pasteMerge(e,t){if(!e||this.getters.isInMerge(t))return;let{sheetId:n,col:r,row:i}=t;this.dispatch(`ADD_MERGE`,{sheetId:n,force:!0,target:[{left:r,top:i,right:r+e.right-e.left,bottom:i+e.bottom-e.top}]})}},mW=class extends WL{copy(e){return{zones:e.clippedZones,sheetId:e.sheetId}}paste(e,t,n){if(n.isCutOperation){let n=e.zones[0];this.dispatch(`MOVE_RANGES`,{target:t.zones,sheetId:t.sheetId,sheetName:this.getters.getSheetName(t.sheetId),targetSheetId:e.sheetId,col:n.left,row:n.top})}}},hW=class extends WL{isPasteAllowed(e,t,n,r){if(!(`cells`in n))return`Success`;let{xSplit:i,ySplit:a}=this.getters.getPaneDivisions(e);return Qn(qT(t,n.cells),i,a)?`FrozenPaneOverlap`:`Success`}},gW=class extends WL{copy(e,t,n=`copyPaste`){let r=e.sheetId,{rowsIndexes:i,columnsIndexes:a,zones:o}=e,s=new Set,c=[];for(let e of i){let l=[];c.push(l);for(let c of a){let a={col:c,row:e,sheetId:r},u=this.getters.getTable(a);if(!u){l.push({});continue}let d=this.getters.getCoreTable(a),f=d?.range.zone,p;if(!s.has(u.id)&&d&&f&&o.some(e=>In(f,e))){s.add(u.id);let{numberOfRows:e}=Ln(f);for(let n=f.top;n<=f.bottom;n++)!t&&!i.includes(n)&&e--;let n=d.range,r=this.getters.extendRange(d.range,`ROW`,n.zone.top+e-1-n.zone.bottom);p={range:this.getters.getRangeData(r),config:d.config,type:d.type}}if(u.isPivotTable){let t=u.range.zone.top===e&&u.range.zone.left===c,n=o.some(e=>In(u.range.zone,e));(t||n)&&s.add(u.id)}n!==`shiftCells`&&l.push({table:p,style:this.getTableStyleToCopy(a),isWholeTableCopied:s.has(u.id)})}}return{tableCells:c,sheetId:e.sheetId}}getTableStyleToCopy(e){let t=Dt({...this.getters.getCellTableStyle(e),hideGridLines:!1}),n=this.getters.getCellStyle(e),r=this.getters.getCellTableBorder(e),i=this.getters.getCellBorder(e);return{style:{...t,...Dt(n)},border:{...r,...Dt(i)}}}paste(e,t,n){let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t,n):this.pasteFromCopy(i,r,t.tableCells,n)}pasteFromCut(e,t,n,r){for(let e of n.tableCells)for(let t of e)t.table&&this.dispatch(`REMOVE_TABLE`,{sheetId:n.sheetId,target:[this.getters.getRangeFromRangeData(t.table.range).zone]});let i=t[0];this.pasteZone(e,i.left,i.top,n.tableCells,r)}pasteZone(e,t,n,r,i){for(let a=0;a<r.length;a++){let o=r[a];for(let r=0;r<o.length;r++){let s=o[r];if(!s)continue;let c={col:t+r,row:n+a,sheetId:e};this.pasteTableCell(e,s,c,i)}}if(r.length===1)for(let i=0;i<r[0].length;i++)this.dispatch(`AUTOFILL_TABLE_COLUMN`,{col:t+i,row:n,sheetId:e})}pasteTableCell(e,t,n,r){if(t.table&&!r?.pasteOption){let{range:r}=t.table,i=Ln(this.getters.getRangeFromRangeData(r).zone),a={left:n.col,top:n.row,right:n.col+i.numberOfCols-1,bottom:n.row+i.numberOfRows-1};this.dispatch(`CREATE_TABLE`,{sheetId:n.sheetId,ranges:[this.getters.getRangeDataFromZone(e,a)],config:t.table.config,tableType:t.table.type})}this.getters.getCoreTable(n)||r?.pasteOption===`asValue`||(!r?.pasteOption&&!t.isWholeTableCopied||r?.pasteOption===`onlyFormat`)&&(t.style?.style&&this.dispatch(`UPDATE_CELL`,{...n,style:t.style.style}),t.style?.border&&this.dispatch(`SET_BORDER`,{...n,border:t.style.border}))}};zF.figureHandlers.add(`chart`,lW).add(`image`,fW).add(`carousel`,cW),zF.cellHandlers.add(`dataValidation`,dW).add(`cell`,GL).add(`sheet`,hW).add(`merge`,pW).add(`border`,oW).add(`table`,gW).add(`conditionalFormat`,uW).add(`references`,mW);var _W=l({ARRAYTOTEXT:()=>KW,ARRAY_CONSTRAIN:()=>bW,ARRAY_LITERAL:()=>xW,ARRAY_ROW:()=>SW,CHOOSECOLS:()=>CW,CHOOSEROWS:()=>wW,EXPAND:()=>TW,FLATTEN:()=>EW,FREQUENCY:()=>DW,HSTACK:()=>OW,MDETERM:()=>kW,MINVERSE:()=>AW,MMULT:()=>jW,SUMPRODUCT:()=>MW,SUMX2MY2:()=>PW,SUMX2PY2:()=>FW,SUMXMY2:()=>IW,TOCOL:()=>zW,TOROW:()=>BW,TRANSPOSE:()=>VW,VSTACK:()=>HW,WRAPCOLS:()=>UW,WRAPROWS:()=>WW});function vW(e,t){let n=e.map(B),r=n.map(e=>e?.[0]?.length??0),i=Math.max(...r);if(t?.requireSameRowCount){let e=r[0];if(r.some(t=>t!==e))return new N(j(`All ranges in [[FUNCTION_NAME]] must have the same number of columns (got %s).`,r.join(`, `)))}let a=[];for(let e of n)for(let t=0;t<e.length;t++){let n=Array(i).fill({value:null});for(let r=0;r<e[t].length;r++)n[r]=e[t][r];a.push(n)}return a}function yW(e,t){let n=e.map(B),r=n.map(e=>e?.length??0),i=Math.max(...r);if(t?.requireSameColCount){let e=r[0];if(r.some(t=>t!==e))return new N(j(`All ranges in [[FUNCTION_NAME]] must have the same number of columns (got %s).`,r.join(`, `)))}let a=so(i,n.reduce((e,t)=>e+(t?.[0]?.length??0),0),()=>({value:null})),o=0;for(let e of n){for(let t=0;t<e.length;t++)for(let n=0;n<e[t].length;n++)a[t][o+n]=e[t][n];o+=e[0]?.length??0}return a}let bW={description:j(`Returns a result array constrained to a specific width and height.`),args:[k(`input_range (any, range<any>)`,j(`The range to constrain.`)),k(`rows (number)`,j(`The number of rows in the constrained array.`)),k(`columns (number)`,j(`The number of columns in the constrained array.`))],compute:function(e,t,n){let r=B(e),i=Ja(t?.value,this.locale),a=Ja(n?.value,this.locale);if(i<=0)return new N(j(`The rows argument (%s) must be strictly positive.`,i.toString()));if(a<=0)return new N(j(`The columns argument (%s) must be strictly positive.`,a.toString()));let o=Math.min(i,r[0].length);return so(Math.min(a,r.length),o,(e,t)=>r[e][t])},isExported:!1},xW={description:j(`Appends ranges vertically and in sequence to return a larger array. All ranges must have the same number of columns.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return yW(e,{requireSameColCount:!0})},isExported:!1,hidden:!0},SW={description:j(`Appends ranges horizontally and in sequence to return a larger array. All ranges must have the same number of rows.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return vW(e,{requireSameRowCount:!0})},isExported:!1,hidden:!0},CW={description:j(`Creates a new array from the selected columns in the existing range.`),args:[k(`array (any, range<any>)`,j(`The array that contains the columns to be returned.`)),k(`col_num (number, range<number>, repeating)`,j(`The column index of the column to be returned.`))],compute:function(e,...t){let n=B(e),r=wo(t,e=>Ja(e?.value,this.locale)),i=r.filter(e=>e===0||n.length<Math.abs(e));if(i.length!==0)return new N(j(`The columns arguments must be between -%s and %s (got %s), excluding 0.`,n.length.toString(),n.length.toString(),i.join(`,`)));let a=Array(r.length);for(let e=0;e<r.length;e++)r[e]>0?a[e]=n[r[e]-1]:a[e]=n[n.length+r[e]];return a},isExported:!0},wW={description:j(`Creates a new array from the selected rows in the existing range.`),args:[k(`array (any, range<any>)`,j(`The array that contains the rows to be returned.`)),k(`row_num (number, range<number>, repeating)`,j(`The row index of the row to be returned.`))],compute:function(e,...t){let n=B(e),r=wo(t,e=>Ja(e?.value,this.locale)),i=n.length,a=r.filter(e=>e===0||n[0].length<Math.abs(e));return a.length===0?so(i,r.length,(e,t)=>r[t]>0?n[e][r[t]-1]:n[e][n[e].length+r[t]]):new N(j(`The rows arguments must be between -%s and %s (got %s), excluding 0.`,n[0].length.toString(),n[0].length.toString(),a.join(`,`)))},isExported:!0},TW={description:j(`Expands or pads an array to specified row and column dimensions.`),args:[k(`array (any, range<any>)`,j(`The array to expand.`)),k(`rows (number)`,j(`The number of rows in the expanded array. If missing, rows will not be expanded.`)),k(`columns (number, optional)`,j(`The number of columns in the expanded array. If missing, columns will not be expanded.`)),k(`pad_with (any, default=0)`,j(`The value with which to pad.`))],compute:function(e,t,n,r={value:0}){let i=B(e),a=Ja(t?.value,this.locale),o=n===void 0?i.length:Ja(n.value,this.locale);return a<i[0].length?new N(j(`The rows arguments (%s) must be greater or equal than the number of rows of the array.`,a.toString())):o<i.length?new N(j(`The columns arguments (%s) must be greater or equal than the number of columns of the array.`,o.toString())):so(o,a,(e,t)=>e>=i.length||t>=i[e].length?r:i[e][t])},isExported:!0},EW={description:j(`Flattens all the values from one or more ranges into a single column.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to flatten.`))],compute:function(...e){return[wo(e,e=>e===void 0?{value:``}:e)]},isExported:!1},DW={description:j(`Calculates the frequency distribution of a range.`),args:[k(`data (range<number>)`,j(`The array of ranges containing the values to be counted.`)),k(`classes (number, range<number>)`,j(`The range containing the set of classes.`))],compute:function(e,t){let n=wo([e],e=>e.value).filter(e=>typeof e==`number`),r=wo([t],e=>e.value).filter(e=>typeof e==`number`).map((e,t)=>({initialIndex:t,value:e,count:0})).sort((e,t)=>e.value-t.value);r.push({initialIndex:r.length,value:1/0,count:0});let i=n.sort((e,t)=>e-t),a=0;for(let e of i){for(;e>r[a].value&&a<r.length-1;)a++;r[a].count++}return[r.sort((e,t)=>e.initialIndex-t.initialIndex).map(e=>e.count)]},isExported:!0},OW={description:j(`Appends ranges horizontally and in sequence to return a larger array.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return vW(e)},isExported:!0},kW={description:j(`Returns the matrix determinant of a square matrix.`),args:[k(`square_matrix (number, range<number>)`,j(`An range with an equal number of rows and columns representing a matrix whose determinant will be calculated.`))],compute:function(e){let t=Ka(e,`square_matrix`);return mh(t)?_h(t).determinant:new N(j(`The argument square_matrix must have the same number of columns and rows.`))},isExported:!0},AW={description:j(`Returns the multiplicative inverse of a square matrix.`),args:[k(`square_matrix (number, range<number>)`,j(`An range with an equal number of rows and columns representing a matrix whose multiplicative inverse will be calculated.`))],compute:function(e){let t=Ka(e,`square_matrix`);if(!mh(t))return new N(j(`The argument square_matrix must have the same number of columns and rows.`));let{inverted:n}=_h(t);return n||new N(j(`The matrix is not invertible.`))},isExported:!0},jW={description:j(`Calculates the matrix product of two matrices.`),args:[k(`matrix1 (number, range<number>)`,j(`The first matrix in the matrix multiplication operation.`)),k(`matrix2 (number, range<number>)`,j(`The second matrix in the matrix multiplication operation.`))],compute:function(e,t){let n=Ka(e,`matrix1`),r=Ka(t,`matrix2`);return n.length===0||r.length===0?new N(j(`The first and second arguments of [[FUNCTION_NAME]] must be non-empty matrices.`)):n.length===r[0].length?yh(n,r):new N(j(`In [[FUNCTION_NAME]], the number of columns of the first matrix (%s) must be equal to the number of rows of the second matrix (%s).`,n.length.toString(),r[0].length.toString()))},isExported:!0},MW={description:j(`Calculates the sum of the products of corresponding entries in equal-sized ranges.`),args:[k(`range (number, range<number>, repeating)`,j(`The range whose entries will be multiplied with corresponding entries in the other range.`))],compute:function(...e){if(!ph(...e))return new N(j(`All the ranges must have the same dimensions.`));let t=e.map(B),n=0;for(let e=0;e<t[0].length;e++)for(let r=0;r<t[0][e].length;r++){if(!t.every(t=>typeof t[e][r].value==`number`))continue;let i=1;for(let n of t)i*=I(n[e][r],this.locale);n+=i}return n},isExported:!0};function NW(e,t,n){if(!ph(e,t))return new N(j(`The arguments array_x and array_y must have the same dimensions.`));let r=B(e),i=B(t),a=!1,o=0;for(let e in r)for(let t in r[e]){let s=r[e][t].value,c=i[e][t].value;typeof s!=`number`||typeof c!=`number`||(a=!0,o+=n(s,c))}return a?o:new N(j(`The arguments array_x and array_y must contain at least one pair of numbers.`))}let PW={description:j(`Calculates the sum of the difference of the squares of the values in two array.`),args:[k(`array_x (number, range<number>)`,j(`The array or range of values whose squares will be reduced by the squares of corresponding entries in array_y and added together.`)),k(`array_y (number, range<number>)`,j(`The array or range of values whose squares will be subtracted from the squares of corresponding entries in array_x and added together.`))],compute:function(e,t){return NW(e,t,(e,t)=>e**2-t**2)},isExported:!0},FW={description:j(`Calculates the sum of the sum of the squares of the values in two array.`),args:[k(`array_x (number, range<number>)`,j(`The array or range of values whose squares will be added to the squares of corresponding entries in array_y and added together.`)),k(`array_y (number, range<number>)`,j(`The array or range of values whose squares will be added to the squares of corresponding entries in array_x and added together.`))],compute:function(e,t){return NW(e,t,(e,t)=>e**2+t**2)},isExported:!0},IW={description:j(`Calculates the sum of squares of the differences of values in two array.`),args:[k(`array_x (number, range<number>)`,j(`The array or range of values that will be reduced by corresponding entries in array_y, squared, and added together.`)),k(`array_y (number, range<number>)`,j(`The array or range of values that will be subtracted from corresponding entries in array_x, the result squared, and all such results added together.`))],compute:function(e,t){return NW(e,t,(e,t)=>(e-t)**2)},isExported:!0},LW=[k(`array (any, range<any>)`,j(`The array which will be transformed.`)),k(`ignore (number, default=0)`,j(`Whether to ignore certain types of values. By default, no values are ignored.`),[{value:0,label:j(`Keep all values (default)`)},{value:1,label:j(`Ignore blanks`)},{value:2,label:j(`Ignore errors`)},{value:3,label:j(`Ignore blanks and errors`)}]),k(`scan_by_column (number, default=false)`,j(`Scan the array by column. By default, the array is scanned by row.`),[{value:!1,label:j(`Scan by row (default)`)},{value:!0,label:j(`Scan by column`)}])];function RW(e){let t=Math.trunc(e);if(t===0)return()=>!0;if(t===1)return e=>e.value!==null;if(t===2)return e=>!F(e.value);if(t===3)return e=>e.value!==null&&!F(e.value);throw new N(j(`Argument ignore must be between 0 and 3`))}let zW={description:j(`Transforms a range of cells into a single column.`),args:LW,compute:function(e,t={value:0},n={value:!1}){let r=B(e),i=I(t.value,this.locale),a=(R(n.value)?r:uo(r)).flat().filter(RW(i));return a.length===0?new Ri(j(`No results for the given arguments of TOCOL.`)):[a]},isExported:!0},BW={description:j(`Transforms a range of cells into a single row.`),args:LW,compute:function(e,t={value:0},n={value:!1}){let r=B(e),i=I(t.value,this.locale),a=(R(n.value)?r:uo(r)).flat().filter(RW(i)).map(e=>[e]);return a.length===0||a[0].length===0?new Ri(j(`No results for the given arguments of TOROW.`)):a},isExported:!0},VW={description:j(`Transposes the rows and columns of a range.`),args:[k(`range (any, range<any>)`,j(`The range to be transposed.`))],compute:function(e){let t=B(e),n=t[0].length,r=t.length;return so(n,r,(e,n)=>t[n][e])},isExported:!0},HW={description:j(`Appends ranges vertically and in sequence to return a larger array.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return yW(e)},isExported:!0},UW={description:j(`Wraps the provided row or column of cells by columns after a specified number of elements to form a new array.`),args:[k(`range (any, range<any>)`,j(`The range to wrap.`)),k(`wrap_count (number)`,j(`The maximum number of cells for each column, rounded down to the nearest whole number.`)),k(`pad_with (any, default=0)`,j(`The value with which to fill the extra cells in the range.`))],compute:function(e,t,n={value:0}){let r=B(e),i=Ja(t?.value,this.locale);if(!fh(r))return new N(j(`Argument range must be a single row or column.`));let a=r.flat();return so(Math.ceil(a.length/i),i,(e,t)=>{let r=e*i+t;return r<a.length?a[r]:n})},isExported:!0},WW={description:j(`Wraps the provided row or column of cells by rows after a specified number of elements to form a new array.`),args:[k(`range (any, range<any>)`,j(`The range to wrap.`)),k(`wrap_count (number)`,j(`The maximum number of cells for each row, rounded down to the nearest whole number.`)),k(`pad_with (any, default=0)`,j(`The value with which to fill the extra cells in the range.`))],compute:function(e,t,n={value:0}){let r=B(e),i=Ja(t?.value,this.locale);if(!fh(r))return new N(j(`Argument range must be a single row or column.`));let a=r.flat();return so(i,Math.ceil(a.length/i),(e,t)=>{let r=t*i+e;return r<a.length?a[r]:n})},isExported:!0},GW=[{value:0,label:j(`Concise format\xA0(default)`)},{value:1,label:j(`Strict format`)}],KW={description:j(`returns an array of text values from any specified range. It passes text values unchanged, and converts non-text values to text.`),args:[k(`array (range)`,j(`The array to convert into text`)),k(`format (number, default=0)`,j(`The format of the returned data.`),GW)],compute:function(e,t={value:0}){let n=I(t,this.locale),r=B(e);if(n===1)return rT(r,``,this.locale);if(n===0){let e=this.locale.decimalSeparator===`,`?`/`:`,`;return uo(r).flatMap(e=>e.map(e=>F(e.value)?e.value:L(e))).join(e)}else return new N(j(`Format must be 0 or 1`))},isExported:!0};var qW=l({ABS:()=>YW,ACOS:()=>XW,ACOSH:()=>ZW,ACOT:()=>QW,ACOTH:()=>$W,ASIN:()=>eG,ASINH:()=>tG,ATAN:()=>nG,ATAN2:()=>rG,ATANH:()=>iG,CEILING:()=>aG,CEILING_MATH:()=>sG,CEILING_PRECISE:()=>cG,COS:()=>lG,COSH:()=>uG,COT:()=>dG,COTH:()=>fG,COUNTBLANK:()=>pG,COUNTIF:()=>mG,COUNTIFS:()=>hG,COUNTUNIQUE:()=>gG,COUNTUNIQUEIFS:()=>_G,CSC:()=>vG,CSCH:()=>yG,DECIMAL:()=>bG,DEGREES:()=>xG,EXP:()=>SG,FLOOR:()=>CG,FLOOR_MATH:()=>TG,FLOOR_PRECISE:()=>EG,INT:()=>cK,ISEVEN:()=>DG,ISODD:()=>kG,ISO_CEILING:()=>OG,LN:()=>AG,LOG:()=>jG,MOD:()=>NG,MUNIT:()=>PG,ODD:()=>FG,PI:()=>IG,POWER:()=>LG,PRODUCT:()=>RG,RAND:()=>zG,RANDARRAY:()=>BG,RANDBETWEEN:()=>VG,ROUND:()=>HG,ROUNDDOWN:()=>UG,ROUNDUP:()=>WG,SEC:()=>GG,SECH:()=>KG,SEQUENCE:()=>qG,SIN:()=>JG,SINH:()=>YG,SQRT:()=>XG,SUBTOTAL:()=>eK,SUM:()=>tK,SUMIF:()=>nK,SUMIFS:()=>rK,TAN:()=>iK,TANH:()=>aK,TRUNC:()=>sK});let JW=/^-?[a-z0-9]+$/i,YW={description:j(`Absolute value of a number.`),args:[k(`value (number)`,j(`The number of which to return the absolute value.`))],compute:function(e){return Math.abs(I(e,this.locale))},isExported:!0},XW={description:j(`Inverse cosine of a value, in radians.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=I(e,this.locale);return Math.abs(t)>1?new N(j(`The value (%s) must be between -1 and 1 inclusive.`,t)):Math.acos(t)},isExported:!0},ZW={description:j(`Inverse hyperbolic cosine of a number.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1.`))],compute:function(e){let t=I(e,this.locale);return t<1?new N(j(`The value (%s) must be greater than or equal to 1.`,t)):Math.acosh(t)},isExported:!0},QW={description:j(`Inverse cotangent of a value.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse cotangent.`))],compute:function(e){let t=I(e,this.locale);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},$W={description:j(`Inverse hyperbolic cotangent of a value.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive.`))],compute:function(e){let t=I(e,this.locale);return Math.abs(t)<=1?new N(j(`The value (%s) cannot be between -1 and 1 inclusive.`,t)):Math.log((t+1)/(t-1))/2},isExported:!0},eG={description:j(`Inverse sine of a value, in radians.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=I(e,this.locale);return Math.abs(t)>1?new N(j(`The value (%s) must be between -1 and 1 inclusive.`,t)):Math.asin(t)},isExported:!0},tG={description:j(`Inverse hyperbolic sine of a number.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse hyperbolic sine.`))],compute:function(e){return Math.asinh(I(e,this.locale))},isExported:!0},nG={description:j(`Inverse tangent of a value, in radians.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse tangent.`))],compute:function(e){return Math.atan(I(e,this.locale))},isExported:!0},rG={description:j(`Angle from the X axis to a point (x,y), in radians.`),args:[k(`x (number)`,j(`The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.`)),k(`y (number)`,j(`The y coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.`))],compute:function(e,t){let n=I(e,this.locale),r=I(t,this.locale);return n===0&&r===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):Math.atan2(r,n)},isExported:!0},iG={description:j(`Inverse hyperbolic tangent of a number.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive.`))],compute:function(e){let t=I(e,this.locale);return Math.abs(t)>=1?new N(j(`The value (%s) must be between -1 and 1 exclusive.`,t)):Math.atanh(t)},isExported:!0},aG={description:j(`Rounds number up to nearest multiple of factor.`),args:[k(`value (number)`,j(`The value to round up to the nearest integer multiple of factor.`)),k(`factor (number, default=1)`,j(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=I(e,this.locale),r=I(t,this.locale);return r<0&&n>0?new N(j(`The factor (%s) must be positive when the value (%s) is positive.`,r,n)):{value:r?Math.ceil(n/r)*r:0,format:e?.format}},isExported:!0};function oG(e,t,n=0){return t===0?0:(t=Math.abs(t),e>=0?Math.ceil(e/t)*t:n===0?-Math.floor(Math.abs(e)/t)*t:-Math.ceil(Math.abs(e)/t)*t)}let sG={description:j(`Rounds number up to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round up to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),k(`mode (number, default=0)`,j(`If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero.`))],compute:function(e,t={value:1},n={value:0}){let r=I(t,this.locale);return{value:oG(I(e,this.locale),r,I(n,this.locale)),format:e?.format}},isExported:!0},cG={description:j(`Rounds number up to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round up to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=I(t,this.locale);return{value:oG(I(e,this.locale),n),format:e?.format}},isExported:!0},lG={description:j(`Cosine of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the cosine of, in radians.`))],compute:function(e){return Math.cos(I(e,this.locale))},isExported:!0},uG={description:j(`Hyperbolic cosine of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic cosine of.`))],compute:function(e){return Math.cosh(I(e,this.locale))},isExported:!0},dG={description:j(`Cotangent of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the cotangent of, in radians.`))],compute:function(e){let t=I(e,this.locale);return t===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tan(t)},isExported:!0},fG={description:j(`Hyperbolic cotangent of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic cotangent of.`))],compute:function(e){let t=I(e,this.locale);return t===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tanh(t)},isExported:!0},pG={description:j(`Number of empty values.`),args:[k(`value (any, range, repeating)`,j(`Value or range in which to count the number of blanks.`))],compute:function(...e){return io(e,(e,t)=>t===void 0||t.value===null||t.value===``?e+1:e,0)},isExported:!0},mG={description:j(`A conditional count across a range.`),args:[k(`range (range)`,j(`The range that is tested against criterion.`)),k(`criterion (string)`,j(`The pattern or test to apply to range.`))],compute:function(...e){let t=0;return vo(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},hG={description:j(`Count values depending on multiple criteria.`),args:[k(`criteria_range (any, range, repeating)`,j(`Range over which to evaluate criteria.`)),k(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(...e){let t=0;return vo(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},gG={description:j(`Counts number of unique values in a range.`),args:[k(`value (any, range, repeating)`,j(`Value or range to consider for uniqueness.`))],compute:function(...e){return Zh(e)}},_G={description:j(`Counts number of unique values in a range, filtered by a set of criteria.`),args:[k(`range (range)`,j(`The range of cells from which the number of unique values will be counted.`)),k(`criteria_range (any, range, repeating)`,j(`Range over which to evaluate criteria.`)),k(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(e,...t){let n=new Set;return vo(t,(t,r)=>{let i=e[t]?.[r];To(i)&&n.add(i.value)},this.locale),n.size}},vG={description:j(`Cosecant of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the cosecant of, in radians.`))],compute:function(e){let t=I(e,this.locale);return t===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sin(t)},isExported:!0},yG={description:j(`Hyperbolic cosecant of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic cosecant of.`))],compute:function(e){let t=I(e,this.locale);return t===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sinh(t)},isExported:!0},bG={description:j(`Converts from another base to decimal.`),args:[k(`value (string)`,j(`The number to convert.`)),k(`base (number)`,j(`The base to convert the value from.`))],compute:function(e,t){let n=I(t,this.locale);if(n=Math.floor(n),2>n||n>36)return new N(j(`The base (%s) must be between 2 and 36 inclusive.`,n));let r=L(e);if(r===``)return 0;if(!JW.test(r))return new N(j(`The value (%s) must be a valid base %s representation.`,r,n));let i=parseInt(r,n);return isNaN(i)?new N(j(`The value (%s) must be a valid base %s representation.`,r,n)):i},isExported:!0},xG={description:j(`Converts an angle value in radians to degrees.`),args:[k(`angle (number)`,j(`The angle to convert from radians to degrees.`))],compute:function(e){return I(e,this.locale)*180/Math.PI},isExported:!0},SG={description:j(`Euler's number, e (~2.718) raised to a power.`),args:[k(`value (number)`,j(`The exponent to raise e.`))],compute:function(e){return Math.exp(I(e,this.locale))},isExported:!0},CG={description:j(`Rounds number down to nearest multiple of factor.`),args:[k(`value (number)`,j(`The value to round down to the nearest integer multiple of factor.`)),k(`factor (number, default=1)`,j(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=I(e,this.locale),r=I(t,this.locale);return r<0&&n>0?new N(j(`The factor (%s) must be positive when the value (%s) is positive.`,r,n)):{value:r?Math.floor(n/r)*r:0,format:e?.format}},isExported:!0};function wG(e,t,n=0){return t===0?0:(t=Math.abs(t),e>=0?Math.floor(e/t)*t:n===0?-Math.ceil(Math.abs(e)/t)*t:-Math.floor(Math.abs(e)/t)*t)}let TG={description:j(`Rounds number down to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round down to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),k(`mode (number, default=0)`,j(`If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero.`))],compute:function(e,t={value:1},n={value:0}){let r=I(t,this.locale);return{value:wG(I(e,this.locale),r,I(n,this.locale)),format:e?.format}},isExported:!0},EG={description:j(`Rounds number down to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round down to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=I(t,this.locale);return{value:wG(I(e,this.locale),n),format:e?.format}},isExported:!0},DG={description:j(`Whether the provided value is even.`),args:[k(`value (number)`,j(`The value to be verified as even.`))],compute:function(e){let t=qa(e,this.locale);return!(Math.floor(Math.abs(t))&1)},isExported:!0},OG={description:j(`Rounds number up to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round up to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){return{value:oG(I(e,this.locale),I(t,this.locale)),format:e?.format}},isExported:!0},kG={description:j(`Whether the provided value is even.`),args:[k(`value (number)`,j(`The value to be verified as even.`))],compute:function(e){let t=qa(e,this.locale);return!!(Math.floor(Math.abs(t))&1)},isExported:!0},AG={description:j(`The logarithm of a number, base e (euler's number).`),args:[k(`value (number)`,j(`The value for which to calculate the logarithm, base e.`))],compute:function(e){let t=I(e,this.locale);return t<=0?new N(j(`The value (%s) must be strictly positive.`,t)):Math.log(t)},isExported:!0},jG={description:j(`The logarithm of a number, for a given base.`),args:[k(`value (number)`,j(`The value for which to calculate the logarithm.`)),k(`base (number, default=10)`,j(`The base of the logarithm.`))],compute:function(e,t={value:10}){let n=I(e,this.locale),r=I(t,this.locale);return n<=0?new N(j(`The value (%s) must be strictly positive.`,n)):r<=0?new N(j(`The base (%s) must be strictly positive.`,r)):r===1?new N(j(`The base must be different from 1.`)):Math.log10(n)/Math.log10(r)},isExported:!0};function MG(e,t){dh(t,j(`The divisor must be different from 0.`));let n=e%t;return n>0&&t<0||n<0&&t>0?n+t:n}let NG={description:j(`Modulo (remainder) operator.`),args:[k(`dividend (number)`,j(`The number to be divided to find the remainder.`)),k(`divisor (number)`,j(`The number to divide by.`))],compute:function(e,t){let n=I(t,this.locale);return{value:MG(I(e,this.locale),n),format:e?.format}},isExported:!0},PG={description:j(`Returns a n x n unit matrix, where n is the input dimension.`),args:[k(`dimension (number)`,j(`An integer specifying the dimension size of the unit matrix. It must be positive.`))],compute:function(e){let t=Ja(e,this.locale);return t<1?new N(j(`The argument dimension must be positive`)):gh(t)},isExported:!0},FG={description:j(`Rounds a number up to the nearest odd integer.`),args:[k(`value (number)`,j(`The value to round to the next greatest odd number.`))],compute:function(e){let t=I(e,this.locale),n=Math.ceil(Math.abs(t));return n=n&1?n:n+1,{value:t<0?-n:n,format:e?.format}},isExported:!0},IG={description:j(`The number pi.`),args:[],compute:function(){return Math.PI},isExported:!0},LG={description:j(`A number raised to a power.`),args:[k(`base (number)`,j(`The number to raise to the exponent power.`)),k(`exponent (number)`,j(`The exponent to raise base to.`))],compute:function(e,t){let n=I(e,this.locale),r=I(t,this.locale);return n<0&&!Number.isInteger(r)?new N(j(`The exponent (%s) must be an integer when the base is negative.`,r)):{value:n**+r,format:e?.format}},isExported:!0},RG={description:j(`Result of multiplying a series of numbers together.`),args:[k(`factor (number, range<number>, repeating)`,j(`Number or range to calculate for the product.`))],compute:function(...e){let t=0,n=1;for(let r of e)if(Je(r))for(let e of r)for(let r of e){let e=r.value;if(typeof e==`number`&&(n*=e,t+=1),F(e))return r}else r!==void 0&&r.value!==null&&(n*=qa(r,this.locale),t+=1);return{value:t===0?0:n,format:za(e[0])}},isExported:!0},zG={description:j(`A random number between 0 inclusive and 1 exclusive.`),args:[],compute:function(){return Math.random()},isExported:!0},BG={description:j(`Returns a grid of random numbers between 0 inclusive and 1 exclusive.`),args:[k(`rows (number, default=1)`,j(`The number of rows to be returned.`)),k(`columns (number, default=1)`,j(`The number of columns to be returned.`)),k(`min (number, default=0)`,j(`The minimum number you would like returned.`)),k(`max (number, default=1)`,j(`The maximum number you would like returned.`)),k(`whole_number (boolean, default=FALSE)`,j(`Return a whole number or a decimal value.`),[{value:!1,label:j(`Decimal (default)`)},{value:!0,label:j(`Integer`)}])],compute:function(e={value:1},t={value:1},n={value:0},r={value:1},i={value:!1}){let a=Ja(t,this.locale),o=Ja(e,this.locale),s=I(n,this.locale),c=I(r,this.locale),l=R(i);if(a<1)return new N(j(`The number of columns (%s) must be positive.`,a));if(o<1)return new N(j(`The number of rows (%s) must be positive.`,o));if(s>c)return new N(j(`The maximum (%s) must be greater than or equal to the minimum (%s).`,c,s));if(l&&(!Number.isInteger(s)||!Number.isInteger(c)))return new N(j(`The maximum (%s) and minimum (%s) must be integers when whole_number is TRUE.`,c.toString(),s.toString()));let u=Array(a);for(let e=0;e<a;e++){u[e]=Array(o);for(let t=0;t<o;t++)l?u[e][t]=Math.floor(Math.random()*(c-s+1)+s):u[e][t]=s+Math.random()*(c-s)}return u},isExported:!0},VG={description:j(`Random integer between two values, inclusive.`),args:[k(`low (number)`,j(`The low end of the random range.`)),k(`high (number)`,j(`The high end of the random range.`))],compute:function(e,t){let n=I(e,this.locale);Number.isInteger(n)||(n=Math.ceil(n));let r=I(t,this.locale);return Number.isInteger(r)||(r=Math.floor(r)),n>r?new N(j(`The high (%s) must be greater than or equal to the low (%s).`,r,n)):{value:n+Math.ceil((r-n+1)*Math.random())-1,format:e?.format}},isExported:!0},HG={description:j(`Rounds a number according to standard rules.`),args:[k(`value (number)`,j(`The value to round to places number of places.`)),k(`places (number, default=0)`,j(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=I(e,this.locale),r=I(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.round(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.round(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},UG={description:j(`Rounds down a number.`),args:[k(`value (number)`,j(`The value to round to places number of places, always rounding down.`)),k(`places (number, default=0)`,j(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=I(e,this.locale),r=I(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.floor(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.floor(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},WG={description:j(`Rounds up a number.`),args:[k(`value (number)`,j(`The value to round to places number of places, always rounding up.`)),k(`places (number, default=0)`,j(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=I(e,this.locale),r=I(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.ceil(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.ceil(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},GG={description:j(`Secant of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the secant of, in radians.`))],compute:function(e){return 1/Math.cos(I(e,this.locale))},isExported:!0},KG={description:j(`Hyperbolic secant of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic secant of.`))],compute:function(e){return 1/Math.cosh(I(e,this.locale))},isExported:!0},qG={description:j(`Returns a sequence of numbers.`),args:[k(`rows (number)`,j(`The number of rows to return`)),k(`columns (number, optional, default=1)`,j(`The number of columns to return`)),k(`start (number, optional, default=1)`,j(`The first number in the sequence`)),k(`step (number, optional, default=1)`,j(`The amount to increment each value in the sequence`))],compute:function(e,t={value:1},n={value:1},r={value:1}){let i=I(n,this.locale),a=I(r,this.locale),o=Ja(e,this.locale),s=Ja(t,this.locale);return s<1?new N(j(`The number of columns (%s) must be positive.`,s)):o<1?new N(j(`The number of rows (%s) must be positive.`,o)):so(s,o,(e,t)=>({value:i+t*s*a+e*a}))},isExported:!0},JG={description:j(`Sine of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the sine of, in radians.`))],compute:function(e){return Math.sin(I(e,this.locale))},isExported:!0},YG={description:j(`Hyperbolic sine of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic sine of.`))],compute:function(e){return Math.sinh(I(e,this.locale))},isExported:!0},XG={description:j(`Positive square root of a positive number.`),args:[k(`value (number)`,j(`The number for which to calculate the positive square root.`))],compute:function(e){let t=I(e,this.locale);return t<0?new N(j(`The value (%s) must be positive or null.`,t)):{value:Math.sqrt(t),format:e?.format}},isExported:!0},ZG={1:`AVERAGE`,2:`COUNT`,3:`COUNTA`,4:`MAX`,5:`MIN`,6:`PRODUCT`,7:`STDEV`,8:`STDEVP`,9:`SUM`,10:`VAR`,11:`VARP`},QG=Object.entries(ZG).map(([e,t])=>({value:parseInt(e),label:j(`%s (include manually-hidden rows)`,t)})),$G=Object.entries(ZG).map(([e,t])=>({value:parseInt(e)+100,label:j(`%s (exclude manually-hidden rows)`,t)})),eK={description:j(`Returns a subtotal for a vertical range of cells using a specified aggregation function.`),args:[k(`function_code (number)`,j(`The function to use in subtotal aggregation.`),[...QG,...$G]),k(`ref (any, range<any>, repeating)`,j(`Range or reference for which you want the subtotal.`))],compute:function(e,...t){let n=Ja(e,this.locale),r=!0;if(n>100&&(n-=100,r=!1),n<1||n>11)return new N(j(`The function code (%s) must be between 1 to 11 or 101 to 111.`,n));let i=[];for(let e of t){let t=B(e),n=t[0][0]?.position;if(n===void 0)return new Li(Ha);let a=n.col+t.length-1,o=n.row+t[0].length-1,s=n.sheetId;for(let e=n.row;e<=o;e++)if(!this.getters.isRowFiltered(s,e)&&!(!r&&this.getters.isRowHiddenByUser(s,e)))for(let t=n.col;t<=a;t++){let n=this.getters.getCorrespondingFormulaCell({sheetId:s,col:t,row:e});(!n||!Yt(n,`SUBTOTAL`))&&i.push(this.getFormulaResult({sheetId:s,col:t,row:e}))}}return this[ZG[n]].apply(this,[[i]])},isExported:!0},tK={description:j(`Sum of a series of numbers and/or cells.`),args:[k(`value (number, range<number>, repeating)`,j(`Number or range to add together.`))],compute:function(...e){let t=e[0];return{value:Xh(e,this.locale),format:za(t)}},isExported:!0},nK={description:j(`A conditional sum across a range.`),args:[k(`criteria_range (range)`,j(`The range which is tested against criterion.`)),k(`criterion (string)`,j(`The pattern or test to apply to range.`)),k(`sum_range (range, default=criteria_range)`,j(`The range to be summed, if different from range.`))],compute:function(e,t,n){n===void 0&&(n=e);let r=0;return vo([e,t],(e,t)=>{let i=n[e]?.[t]?.value;typeof i==`number`&&(r+=i)},this.locale),r},isExported:!0},rK={description:j(`Sums a range depending on multiple criteria.`),args:[k(`sum_range (range)`,j(`The range to sum.`)),k(`criteria_range (any, range, repeating)`,j(`Range to check.`)),k(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(e,...t){let n=0;return vo(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n+=i)},this.locale),n},isExported:!0},iK={description:j(`Tangent of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the tangent of, in radians.`))],compute:function(e){return Math.tan(I(e,this.locale))},isExported:!0},aK={description:j(`Hyperbolic tangent of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic tangent of.`))],compute:function(e){return Math.tanh(I(e,this.locale))},isExported:!0};function oK(e,t){return t===0?Math.trunc(e):(Number.isInteger(t)||(t=Math.trunc(t)),Math.trunc(e*10**t)/10**t)}let sK={description:j(`Truncates a number.`),args:[k(`value (number)`,j(`The value to be truncated.`)),k(`places (number, default=0)`,j(`The number of significant digits to the right of the decimal point to retain.`))],compute:function(e,t={value:0}){return{value:oK(I(e,this.locale),I(t,this.locale)),format:e?.format}},isExported:!0},cK={description:j(`Rounds a number down to the nearest integer that is less than or equal to it.`),args:[k(`value (number)`,j(`The number to round down to the nearest integer.`))],compute:function(e){return Math.floor(I(e,this.locale))},isExported:!0};var lK=l({AVEDEV:()=>yK,AVERAGE:()=>bK,AVERAGEA:()=>wK,AVERAGEIF:()=>TK,AVERAGEIFS:()=>EK,AVERAGE_WEIGHTED:()=>CK,CORREL:()=>JK,COUNT:()=>DK,COUNTA:()=>OK,COVAR:()=>kK,COVARIANCE_P:()=>AK,COVARIANCE_S:()=>jK,FORECAST:()=>MK,GROWTH:()=>NK,INTERCEPT:()=>PK,LARGE:()=>FK,LINEST:()=>IK,LOGEST:()=>LK,MATTHEWS:()=>RK,MAX:()=>zK,MAXA:()=>BK,MAXIFS:()=>VK,MEDIAN:()=>HK,MIN:()=>UK,MINA:()=>WK,MINIFS:()=>GK,PEARSON:()=>qK,PERCENTILE:()=>YK,PERCENTILE_EXC:()=>XK,PERCENTILE_INC:()=>ZK,POLYFIT_COEFFS:()=>QK,POLYFIT_FORECAST:()=>$K,QUARTILE:()=>eq,QUARTILE_EXC:()=>tq,QUARTILE_INC:()=>nq,RANK:()=>rq,RSQ:()=>iq,SLOPE:()=>aq,SMALL:()=>oq,SPEARMAN:()=>sq,STDEV:()=>cq,STDEVA:()=>dq,STDEVP:()=>fq,STDEVPA:()=>pq,STDEV_P:()=>lq,STDEV_S:()=>uq,STEYX:()=>mq,TREND:()=>hq,VAR:()=>gq,VARA:()=>yq,VARP:()=>bq,VARPA:()=>xq,VAR_P:()=>_q,VAR_S:()=>vq});let uK=[{value:!0,label:j(`b is calculated normally`)},{value:!1,label:j(`b is forced to 1`)}],dK=[{value:!1,label:j(`do not return additional regression statistics`)},{value:!0,label:j(`return additional regression statistics`)}],fK=[{value:1,label:j(`order 1 (Linear)`)},{value:2,label:j(`order 2 (Quadratic)`)},{value:3,label:j(`order 3 (Cubic)`)},{value:4,label:j(`order 4 (Quartic)`)},{value:5,label:j(`order 5 (Quintic)`)},{value:6,label:j(`order 6 (Sextic)`)}],pK=[{value:!0,label:j(`Compute intercept`)},{value:!1,label:j(`Force intercept to 0`)}],mK=[{value:0,label:j(`Minimum value`)},{value:1,label:j(`First quartile (25th percentile)`)},{value:2,label:j(`Median value (50th percentile)`)},{value:3,label:j(`Third quartile (75th percentile)`)},{value:4,label:j(`Maximum value`)}];function hK(e,t){let n=[],r=[],i=0,a=0;to([e],e=>{n.push(e),i+=1}),to([t],e=>{r.push(e),a+=1}),uh(i===a,j(`[[FUNCTION_NAME]] has mismatched argument count %s vs %s.`,i,a));let o=[],s=[];for(let e=0;e<i;e++){let t=n[e]?.value,i=r[e]?.value;typeof t==`number`&&typeof i==`number`&&(s.push(t),o.push(i))}return{flatDataX:o,flatDataY:s}}function gK(e,t,n){let{flatDataX:r,flatDataY:i}=hK(e,t),a=i.length;dh(a),n&&dh(a-1);let o=0,s=0;for(let e=0;e<a;e++)o+=i[e],s+=r[e];let c=o/a,l=s/a,u=0;for(let e=0;e<a;e++)u+=(i[e]-c)*(r[e]-l);return u/(a-+!!n)}function _K(e,t,n,r){let i=0,a=n?oo:ao,o=a(e,(e,t)=>(i+=1,e+t),0,r);dh(i),t&&dh(i-1);let s=o/i;return a(e,(e,t)=>e+(t-s)**2,0,r)/(i-+!!t)}function vK(e,t,n,r){let i=I(t,r);uh(n?0<=i&&i<=1:0<i&&i<1,j(`Function [[FUNCTION_NAME]] parameter 2 value is out of range.`));let a=[],o,s=0;return to(e,e=>{let t=e?.value;typeof t==`number`&&(o=yo(a,e,`nextSmaller`,`asc`,a.length,(e,t)=>e[t]),a.splice(o+1,0,t),s++)}),uh(s!==0,Eo),n||uh(1/(s+1)<=i&&i<=s/(s+1),j(`Function [[FUNCTION_NAME]] parameter 2 value is out of range.`)),La(a,i,n)}let yK={description:j(`Average magnitude of deviations from mean.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){let t=0,n=ao(e,(e,n)=>(t+=1,e+n),0,this.locale);if(t===0)return new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`));let r=n/t;return ao(e,(e,t)=>e+Math.abs(r-t),0,this.locale)/t},isExported:!0},bK={description:j(`Numerical average value in a dataset, ignoring text.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the average value.`))],compute:function(...e){return{value:wh(e,this.locale),format:za(e[0])}},isExported:!0},xK=j(`[[FUNCTION_NAME]] has mismatched range sizes.`),SK=j(`[[FUNCTION_NAME]] expects the weight to be positive or equal to 0.`),CK={description:j(`Weighted average.`),args:[k(`values (number, range<number>, repeating)`,j(`Value to average.`)),k(`weights (number, range<number>, repeating)`,j(`Weight for each corresponding value.`))],compute:function(...e){let t=0,n=0;for(let r=0;r<e.length-1;r+=2){let i=e[r],a=e[r+1];if(!ph(i,a))return new N(xK);if(Je(i))for(let e=0;e<i.length;e++)for(let r=0;r<i[0].length;r++){let o=i[e][r].value,s=Je(a)?a?.[e][r].value:I(a,this.locale),c=typeof o==`number`,l=typeof s==`number`;if(c&&l){if(s<0)return new N(SK);t+=o*s,n+=s;continue}if(c!==l)return new N(j(`[[FUNCTION_NAME]] expects number values.`))}else{let e=I(i,this.locale),r=Je(a)?a?.[0][0].value:I(a,this.locale);if(typeof r==`number`){if(r<0)return new N(SK);t+=e*r,n+=r}}}return n===0?new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:t/n,format:za(e[0])}}},wK={description:j(`Numerical average value in a dataset.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the average value.`))],compute:function(...e){let t=0,n=oo(e,(e,n)=>(t+=1,e+n),0,this.locale);return t===0?new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:n/t,format:za(e[0])}},isExported:!0},TK={description:j(`Average of values depending on criteria.`),args:[k(`criteria_range (number, range<number>)`,j(`The range to check against criterion.`)),k(`criterion (string)`,j(`The pattern or test to apply to criteria_range.`)),k(`average_range (number, range<number>, default=criteria_range)`,j(`The range to average. If not included, criteria_range is used for the average instead.`))],compute:function(e,t,n){let r=B(n===void 0?e:n),i=0,a=0;return vo([e,t],(e,t)=>{let n=r[e]?.[t]?.value;typeof n==`number`&&(i+=1,a+=n)},this.locale),i===0?new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):a/i},isExported:!0},EK={description:j(`Average of values depending on multiple criteria.`),args:[k(`average_range (range)`,j(`The range to average.`)),k(`criteria_range (any, range, repeating)`,j(`Range to check.`)),k(`criterion (string, repeating)`,j(`Criterion to check.`))],compute:function(e,...t){let n=B(e),r=0,i=0;return vo(t,(e,t)=>{let a=n[e]?.[t]?.value;typeof a==`number`&&(r+=1,i+=a)},this.locale),r===0?new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):i/r},isExported:!0},DK={description:j(`The number of numeric values in dataset.`),args:[k(`value (number, any, range<number>, repeating)`,j(`Value or range to consider when counting.`))],compute:function(...e){return Eh(e,this.locale)},isExported:!0},OK={description:j(`The number of values in a dataset.`),args:[k(`value (any, range, repeating)`,j(`Value or range to consider when counting.`))],compute:function(...e){return Dh(e)},isExported:!0},kK={description:j(`The covariance of a dataset.`),args:[k(`data_y (any, range)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (any, range)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return gK(e,t,!1)},isExported:!0},AK={description:j(`The covariance of a dataset.`),args:[k(`data_y (any, range)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (any, range)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return gK(e,t,!1)},isExported:!0},jK={description:j(`The sample covariance of a dataset.`),args:[k(`data_y (any, range)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (any, range)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return gK(e,t,!0)},isExported:!0},MK={description:j(`Calculates the expected y-value for a specified x based on a linear regression of a dataset.`),args:[k(`x (number, range<number>)`,j(`The value(s) on the x-axis to forecast.`)),k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t,n){let{flatDataX:r,flatDataY:i}=hK(t,n);return r.length===0||i.length===0?new Ri(Eo):Lh([i],[r],co(B(e),e=>I(e,this.locale)),!0)},isExported:!0},NK={description:j(`Fits points to exponential growth trend.`),args:[k(`known_data_y (range<number>)`,j(`The array or range containing dependent (y) values that are already known, used to curve fit an ideal exponential growth curve.`)),k(`known_data_x (range<number>, default={1;2;3;...})`,j(`The values of the independent variable(s) corresponding with known_data_y.`)),k(`new_data_x (any, range, default=known_data_x)`,j(`The data points to return the y values for on the ideal curve fit.`)),k(`b (boolean, default=TRUE)`,j(`Given a general exponential form of y = b*m^x for a curve fit, calculates b if TRUE or forces b to be 1 and only calculates the m values if FALSE.`),uK)],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new N(Do(`known_data_y`)):Fh(Lh(Ih(Ka(e,`known_data_y`)),Ka(t,`known_data_x`),Ka(n,`new_data_y`),R(r)))}},PK={description:j(`Compute the intercept of the linear regression.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=hK(e,t);if(n.length===0||r.length===0)return new Ri(Eo);let[[],[i]]=jh([n],[r]);return i},isExported:!0},FK={description:j(`Nth largest element from a data set.`),args:[k(`data (any, range)`,j(`Array or range containing the dataset to consider.`)),k(`n (number)`,j(`The rank from largest to smallest of the element to return.`))],compute:function(e,t){let n=Math.trunc(I(t?.value,this.locale)),r=[],i,a=0;to([e],e=>{typeof e?.value==`number`&&(i=yo(r,e,`nextSmaller`,`asc`,r.length,(e,t)=>e[t].value),r.splice(i+1,0,e),a++,a>n&&(r.shift(),a--))});let o=r.shift();return o===void 0?new N(Eo):a<n?new N(j(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},IK={description:j(`Given partial data about a linear trend, calculates various parameters about the ideal linear trend using the least-squares method.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>, default={1;2;3;...})`,j(`The range representing the array or matrix of independent data.`)),k(`calculate_b (boolean, default=TRUE)`,j(`A flag specifying whether to compute the slope or not`),uK),k(`verbose (boolean, default=FALSE)`,j(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`),dK)],compute:function(e,t=[[]],n={value:!0},r={value:!1}){return e.length===0||e[0].length===0?new N(Do(`data_y`)):jh(Ka(t,`data_x`),Ka(e,`data_y`),R(n),R(r))},isExported:!0},LK={description:j(`Given partial data about an exponential growth curve, calculates various parameters about the best fit ideal exponential growth curve.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>, optional, default={1;2;3;...})`,j(`The range representing the array or matrix of independent data.`)),k(`calculate_b (boolean, default=TRUE)`,j(`A flag specifying whether to compute the slope or not`),uK),k(`verbose (boolean, default=FALSE)`,j(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`),dK)],compute:function(e,t=[[]],n={value:!0},r={value:!1}){if(e.length===0||e[0].length===0)return new N(Do(`data_y`));let i=jh(Ka(t,`data_x`),Ih(Ka(e,`data_y`)),R(n),R(r));for(let e=0;e<i.length;e++)i[e][0]=Math.exp(i[e][0]);return i},isExported:!0},RK={description:j(`Compute the Matthews correlation coefficient of a dataset.`),args:[k(`data_x (range)`,j(`The range representing the array or matrix of observed data.`)),k(`data_y (range)`,j(`The range representing the array or matrix of predicted data.`))],compute:function(e,t){let n=e.flat(),r=t.flat();if(Ch(n,r),n.length===0||r.length===0)return new Ri(Eo);let i=n.length,a=0,o=0,s=0,c=0;for(let e=0;e<i;++e){let t=R(n[e]);t===R(r[e])?t?o++:a++:t?c++:s++}return(o*a-s*c)/Math.sqrt((o+s)*(o+c)*(a+s)*(a+c))},isExported:!1},zK={description:j(`Maximum value in a numeric dataset.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the maximum value.`))],compute:function(...e){return Oh(e,this.locale)},isExported:!0},BK={description:j(`Maximum numeric value in a dataset.`),args:[k(`value (any, range, repeating)`,j(`Value or range to consider when calculating the maximum value.`))],compute:function(...e){let t=oo(e,(e,t)=>Math.max(t,e),-1/0,this.locale);return{value:t===-1/0?0:t,format:za(e[0])}},isExported:!0},VK={description:j(`Returns the maximum value in a range of cells, filtered by a set of criteria.`),args:[k(`range (range)`,j(`The range of cells from which the maximum will be determined.`)),k(`criteria_range (any, range, repeating)`,j(`Range to evaluate criteria.`)),k(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(e,...t){let n=-1/0;return vo(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n=n<i?i:n)},this.locale),n===-1/0?0:n},isExported:!0},HK={description:j(`Median value in a numeric dataset.`),args:[k(`value (any, range, repeating)`,j(`Value or range to consider when calculating the median value.`))],compute:function(...e){let t=[];return no(e,e=>{t.push(e)},this.locale),{value:vK(t,{value:.5},!0,this.locale),format:za(t[0])}},isExported:!0},UK={description:j(`Minimum value in a numeric dataset.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the minimum value.`))],compute:function(...e){return kh(e,this.locale)},isExported:!0},WK={description:j(`Minimum numeric value in a dataset.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the minimum value.`))],compute:function(...e){let t=oo(e,(e,t)=>Math.min(t,e),1/0,this.locale);return{value:t===1/0?0:t,format:za(e[0])}},isExported:!0},GK={description:j(`Returns the minimum value in a range of cells, filtered by a set of criteria.`),args:[k(`range (range)`,j(`The range of cells from which the minimum will be determined.`)),k(`criteria_range (any, range, repeating)`,j(`Range to evaluate criteria.`)),k(`criterion (string, repeating)`,j(`Criterion to check.`))],compute:function(e,...t){let n=1/0;return vo(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n=n>i?i:n)},this.locale),n===1/0?0:n},isExported:!0};function KK(e,t){let{flatDataX:n,flatDataY:r}=hK(e,t);if(n.length===0||r.length===0)return new Ri(Eo);let i=n.length,a=0,o=0,s=0,c=0,l=0;for(let e=0;e<i;e++){let t=n[e],i=r[e];a+=t,o+=i,s+=t*i,c+=t*t,l+=i*i}return(i*s-a*o)/Math.sqrt((i*c-a*a)*(i*l-o*o))}let qK={description:j(`Compute the Pearson product-moment correlation coefficient of a dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return KK(e,t)},isExported:!0},JK=qK,YK={description:j(`Value at a given percentile of a dataset.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`percentile (number)`,j(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return ZK.compute.bind(this)(e,t)},isExported:!0},XK={description:j(`Value at a given percentile of a dataset exclusive of 0 and 1.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`percentile (number)`,j(`The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned.`))],compute:function(e,t){return{value:vK([e],t,!1,this.locale),format:za(e)}},isExported:!0},ZK={description:j(`Value at a given percentile of a dataset.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`percentile (number)`,j(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return{value:vK([e],t,!0,this.locale),format:za(e)}},isExported:!0},QK={description:j(`Compute the coefficients of polynomial regression of the dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`)),k(`order (number)`,j(`The order of the polynomial to fit the data, between 1 and 6.`),fK),k(`intercept (boolean, default=TRUE)`,j(`A flag specifying whether to compute the intercept or not.`),pK)],compute:function(e,t,n,r={value:!0}){let{flatDataX:i,flatDataY:a}=hK(e,t);return i.length===0||a.length===0?new Ri(Eo):Mh(a,i,I(n,this.locale),R(r))},isExported:!1},$K={description:j(`Predict value by computing a polynomial regression of the dataset.`),args:[k(`x (number, range<number>)`,j(`The value(s) on the x-axis to forecast.`)),k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`)),k(`order (number)`,j(`The order of the polynomial to fit the data, between 1 and 6.`),fK),k(`intercept (boolean, default=TRUE)`,j(`A flag specifying whether to compute the intercept or not.`),pK)],compute:function(e,t,n,r,i={value:!0}){let a=I(r,this.locale),{flatDataX:o,flatDataY:s}=hK(t,n);if(o.length===0||s.length===0)return new Ri(Eo);let c=Mh(s,o,a,R(i)).flat();return co(B(e),e=>Ph(c,I(e,this.locale),a))},isExported:!1},eq={description:j(`Value nearest to a specific quartile of a dataset.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`quartile_number (number)`,j(`Which quartile value to return.`),mK)],compute:function(e,t){return nq.compute.bind(this)(e,t)},isExported:!0},tq={description:j(`Value nearest to a specific quartile of a dataset exclusive of 0 and 4.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`quartile_number (number)`,j(`Which quartile value, exclusive of 0 and 4, to return.`),[{value:1,label:j(`First quartile (25th percentile)`)},{value:2,label:j(`Median value (50th percentile)`)},{value:3,label:j(`Third quartile (75th percentile)`)}])],compute:function(e,t){let n={value:.25*Math.trunc(I(t,this.locale))};return{value:vK([e],n,!1,this.locale),format:za(e)}},isExported:!0},nq={description:j(`Value nearest to a specific quartile of a dataset.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`quartile_number (number)`,j(`Which quartile value to return.`),mK)],compute:function(e,t){let n={value:.25*Math.trunc(I(t,this.locale))};return{value:vK([e],n,!0,this.locale),format:za(e)}},isExported:!0},rq={description:j(`Returns the rank of a specified value in a dataset.`),args:[k(`value (number)`,j(`The value whose rank will be determined.`)),k(`data (range)`,j(`The range containing the dataset to consider.`)),k(`is_ascending (boolean, default=FALSE)`,j(`Whether to consider the values in data in descending or ascending order.`),[{value:!1,label:j(`Descending`)},{value:!0,label:j(`Ascending`)}])],compute:function(e,t,n={value:!1}){let r=R(n),i=I(e,this.locale),a=1,o=!1;for(let e of t)for(let t of e){if(typeof t.value!=`number`)continue;let e=I(t,this.locale);e===i?o=!0:e>i!==r&&a++}return o?a:new Ri(j(`Value not found in the given data.`))},isExported:!0},iq={description:j(`Compute the square of r, the Pearson product-moment correlation coefficient of a dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let n=KK(e,t);if(n instanceof Error)throw n;return n**2},isExported:!0},aq={description:j(`Compute the slope of the linear regression.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=hK(e,t);if(n.length===0||r.length===0)return new Ri(Eo);let[[i]]=jh([n],[r]);return i},isExported:!0},oq={description:j(`Nth smallest element in a data set.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`n (number)`,j(`The rank from smallest to largest of the element to return.`))],compute:function(e,t){let n=Math.trunc(I(t?.value,this.locale)),r=[],i,a=0;to([e],e=>{typeof e?.value==`number`&&(i=yo(r,e,`nextSmaller`,`asc`,r.length,(e,t)=>e[t].value),r.splice(i+1,0,e),a++,a>n&&(r.pop(),a--))});let o=r.pop();return o===void 0?new N(Eo):a<n?new N(j(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},sq={description:j(`Compute the Spearman rank correlation coefficient of a dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=hK(t,e);if(n.length===0||r.length===0)return new Ri(Eo);let i=n.length,a=n.map((e,t)=>[e,r[t]]);a.sort((e,t)=>e[0]-t[0]);for(let e=0;e<i;++e)a[e][0]=e;a.sort((e,t)=>e[1]-t[1]);let o=0;for(let e=0;e<i;++e)o+=(a[e][0]-e)**2;return 1-6*o/(i**3-i)},isExported:!1},cq={description:j(`Standard deviation.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(gq.compute.bind(this)(...e))},isExported:!0},lq={description:j(`Standard deviation of entire population.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(_q.compute.bind(this)(...e))},isExported:!0},uq={description:j(`Standard deviation.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(vq.compute.bind(this)(...e))},isExported:!0},dq={description:j(`Standard deviation of sample (text as 0).`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(yq.compute.bind(this)(...e))},isExported:!0},fq={description:j(`Standard deviation of entire population.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(bq.compute.bind(this)(...e))},isExported:!0},pq={description:j(`Standard deviation of entire population (text as 0).`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(xq.compute.bind(this)(...e))},isExported:!0},mq={description:j(`Calculates the standard error of the predicted y-value for each x in the regression of a dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=hK(e,t);return n.length===0||r.length===0?new Ri(Eo):jh([n],[r],!0,!0)[1][2]},isExported:!0},hq={description:j(`Fits points to linear trend derived via least-squares.`),args:[k(`known_data_y (number, range<number>)`,j(`The array or range containing dependent (y) values that are already known, used to curve fit an ideal linear trend.`)),k(`known_data_x (number, range<number>, optional, default={1;2;3;...})`,j(`The values of the independent variable(s) corresponding with known_data_y.`)),k(`new_data_x (number, range<number>, optional, default=known_data_x)`,j(`The data points to return the y values for on the ideal curve fit.`)),k(`b (boolean, optional, default=TRUE)`,j(`Given a general linear form of y = m*x+b for a curve fit, calculates b if TRUE or forces b to be 0 and only calculates the m values if FALSE, i.e. forces the curve fit to pass through the origin.`),uK)],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new N(Do(`known_data_y`)):Lh(Ka(e,`known_data_y`),Ka(t,`known_data_x`),Ka(n,`new_data_y`),R(r))}},gq={description:j(`Variance.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return _K(e,!0,!1,this.locale)},isExported:!0},_q={description:j(`Variance of entire population.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return _K(e,!1,!1,this.locale)},isExported:!0},vq={description:j(`Variance.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return _K(e,!0,!1,this.locale)},isExported:!0},yq={description:j(`Variance of sample (text as 0).`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return _K(e,!0,!0,this.locale)},isExported:!0},bq={description:j(`Variance of entire population.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return _K(e,!1,!1,this.locale)},isExported:!0},xq={description:j(`Variance of entire population (text as 0).`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return _K(e,!1,!0,this.locale)},isExported:!0};var Sq=l({DAVERAGE:()=>Tq,DCOUNT:()=>Eq,DCOUNTA:()=>Dq,DGET:()=>Oq,DMAX:()=>kq,DMIN:()=>Aq,DPRODUCT:()=>jq,DSTDEV:()=>Mq,DSTDEVP:()=>Nq,DSUM:()=>Pq,DVAR:()=>Fq,DVARP:()=>Iq});function Cq(e,t,n,r){let i=new Map,a=e.length;for(let t=a-1;t>=0;t--)i.set(L(e[t][0]).toUpperCase(),t);let o=t?.value;if(typeof o!=`number`&&typeof o!=`string`)throw new N(j(`The field must be a number or a string`));let s;if(typeof o==`number`){if(s=Math.trunc(o)-1,s<0||a-1<s)throw new N(j(`The field (%(fieldValue)s) must be one of %(dimRowDB)s or must be a number between 1 and %s inclusive.`,{fieldValue:o.toString(),dimRowDB:a.toString()}))}else{let e=L(t).toUpperCase();if(s=i.get(e)??-1,s===-1)throw new N(j(`The field (%s) must be one of %s.`,L(t),[...i.keys()].toString()))}let c=n[0].length;if(c<2)throw new N(j(`The criteria range contains %s row, it must be at least 2 rows.`,c.toString()));let l=new Set,u=e[0].length;for(let t=1;t<c;t++){let a=[],o=!0;for(let r=0;r<n.length;r++){let s=L(n[r][0]).toUpperCase(),c=i.get(s),l=n[r][t];if(l.value!==null)if(c!==void 0)a.push([e[c].slice(1,u)]),a.push(l);else{o=!1;break}}if(o)if(a.length>0)vo(a,(e,t)=>{l.add(t)},r,!0);else{l=new Set(Array(u-1).keys());break}}let d=e[s];return[...l].map(e=>d[e+1])}let wq=[k(`database (range)`,j(`The array or range containing the data to consider, structured in such a way that the first row contains the labels for each column's values.`)),k(`field (number, string)`,j(`Indicates which column in database contains the values to be extracted and operated on.`)),k(`criteria (range)`,j(`An array or range containing zero or more criteria to filter the database values by before operating.`))],Tq={description:j(`Average of a set of values from a table-like range.`),args:wq,compute:function(e,t,n){let r=Cq(e,t,n,this.locale);return bK.compute.bind(this)([r])},isExported:!0},Eq={description:j(`Counts values from a table-like range.`),args:wq,compute:function(e,t,n){let r=Cq(e,t,n,this.locale);return DK.compute.bind(this)([r])},isExported:!0},Dq={description:j(`Counts values and text from a table-like range.`),args:wq,compute:function(e,t,n){let r=Cq(e,t,n,this.locale);return OK.compute.bind(this)([r])},isExported:!0},Oq={description:j(`Single value from a table-like range.`),args:wq,compute:function(e,t,n){let r=Cq(e,t,n,this.locale);return r.length===1?r[0]:new N(j(`More than one match found in DGET evaluation.`))},isExported:!0},kq={description:j(`Maximum of values from a table-like range.`),args:wq,compute:function(e,t,n){let r=Cq(e,t,n,this.locale);return zK.compute.bind(this)([r])},isExported:!0},Aq={description:j(`Minimum of values from a table-like range.`),args:wq,compute:function(e,t,n){let r=Cq(e,t,n,this.locale);return UK.compute.bind(this)([r])},isExported:!0},jq={description:j(`Product of values from a table-like range.`),args:wq,compute:function(e,t,n){let r=Cq(e,t,n,this.locale);return RG.compute.bind(this)([r])},isExported:!0},Mq={description:j(`Standard deviation of population sample from table.`),args:wq,compute:function(e,t,n){let r=Cq(e,t,n,this.locale);return cq.compute.bind(this)([r])},isExported:!0},Nq={description:j(`Standard deviation of entire population from table.`),args:wq,compute:function(e,t,n){let r=Cq(e,t,n,this.locale);return fq.compute.bind(this)([r])},isExported:!0},Pq={description:j(`Sum of values from a table-like range.`),args:wq,compute:function(e,t,n){let r=Cq(e,t,n,this.locale);return tK.compute.bind(this)([r])},isExported:!0},Fq={description:j(`Variance of population sample from table-like range.`),args:wq,compute:function(e,t,n){let r=Cq(e,t,n,this.locale);return gq.compute.bind(this)([r])},isExported:!0},Iq={description:j(`Variance of a population from a table-like range.`),args:wq,compute:function(e,t,n){let r=Cq(e,t,n,this.locale);return bq.compute.bind(this)([r])},isExported:!0},Lq=j(`The cashflow_amounts and cashflow_dates ranges must have the same dimensions.`),Rq=j(`There must be both positive and negative values in cashflow_amounts.`),zq=e=>j(`The cost (%s) must be positive or null.`,e),Bq=e=>j(`The cost (%s) must be strictly positive.`,e),Vq=e=>j(`The frequency (%s) must be one of %s`,e,[1,2,4].toString()),Hq=e=>j(`The day_count_convention (%s) must be between 0 and 4 inclusive.`,e),Uq=e=>j(`The depreciation factor (%s) must be strictly positive.`,e),Wq=e=>j(`The discount (%s) must be different from -1.`,e),Gq=e=>j(`The discount (%s) must be strictly positive.`,e),Kq=e=>j(`The discount (%s) must be smaller than 1.`,e),qq=e=>j(`The effective_rate (%s) must be strictly positive.`,e),Jq=e=>j(`The end_period (%s) must be positive or null.`,e),Yq=(e,t)=>j(`The end_period (%(end)s) must be smaller or equal to the life (%(life)s).`,{end:e,life:t}),Xq=e=>j(`All the dates should be greater or equal to the first date in cashflow_dates (%s).`,e),Zq=(e,t)=>j(`The first_period (%(first)s) must be smaller or equal to the last_period (%(last)s).`,{first:e,last:t}),Qq=e=>j(`The first_period (%s) must be strictly positive.`,e),$q=e=>j(`The future_value (%s) must be strictly positive.`,e),eJ=e=>j(`The investment (%s) must be strictly positive.`,e),tJ=e=>j(`The issue (%s) must be positive or null.`,e),nJ=(e,t)=>j(`The last_period (%(last)s) must be smaller or equal to the number_of_periods (%(nPeriods)s).`,{last:e,nPeriods:t}),rJ=e=>j(`The last_period (%s) must be strictly positive.`,e),iJ=e=>j(`The life (%s) must be strictly positive.`,e),aJ=(e,t)=>j(`The maturity (%(maturity)s) must be strictly greater than the settlement (%(settlement)s).`,{maturity:t,settlement:e}),oJ=e=>j(`The month (%s) must be between 1 and 12 inclusive.`,e),sJ=e=>j(`The nominal_rate (%s) must be strictly positive.`,e),cJ=e=>j(`The number_of_periods (%s) must be different from zero.`,e),lJ=e=>j(`The number_of_periods (%s) must be strictly positive.`,e),uJ=e=>j(`The period must be between 1 and number_of_periods (%s)`,e),dJ=(e,t)=>j(`The period (%(period)s) must be less than or equal to %(lifeLimit)s.`,{period:e,lifeLimit:t}),fJ=e=>j(`The period (%s) must be positive or null.`,e),pJ=e=>j(`The periods_by_year (%s) must be strictly positive.`,e),mJ=(e,t)=>j(`The period (%(period)s) must be less than or equal life (%(life)s).`,{period:e,life:t}),hJ=e=>j(`The period (%s) must be strictly positive.`,e),gJ=e=>j(`The present_value (%s) must be strictly positive.`,e),_J=e=>j(`The price (%s) must be strictly positive.`,e),vJ=(e,t)=>j(`The purchase_date (%(purchaseDate)s) must be before the first_period_end (%(firstPeriodEnd)s).`,{purchaseDate:e,firstPeriodEnd:t}),yJ=e=>j(`The purchase_date (%s) must be positive or null.`,e),bJ=e=>j(`The rate_guess (%s) must be strictly greater than -1.`,e),xJ=e=>j(`The rate (%s) must be positive or null.`,e),SJ=e=>j(`The rate (%s) must be strictly positive.`,e),CJ=e=>j(`The redemption (%s) must be strictly positive.`,e),wJ=e=>j(`The salvage (%s) must be positive or null.`,e),TJ=(e,t)=>j(`The salvage (%(salvage)s) must be smaller or equal than the cost (%(cost)s).`,{salvage:e,cost:t}),EJ=(e,t)=>j(`The settlement date (%(settlement)s) must be greater or equal to the issue date (%(issue)s).`,{settlement:e,issue:t}),DJ=(e,t)=>j(`The settlement date (%(settlement)s) must at most one year after the maturity date (%(maturity)s).`,{settlement:e,maturity:t}),OJ=(e,t)=>j(`The settlement date (%(settlement)s) must be strictly greater than the issue date (%(issue)s).`,{settlement:e,issue:t}),kJ=e=>j(`The start_period (%s) must be positive or null.`,e),AJ=(e,t)=>j(`The start_period (%(start)s) must be smaller or equal to the end_period (%(end)s).`,{start:e,end:t}),jJ=e=>j(`The unit (%s) must be strictly positive.`,e),MJ=e=>j(`The yield (%s) must be positive or null.`,e);function NJ(e){return e.some(e=>e>0)&&e.some(e=>e<0)}function PJ(e){return![0,1,2,3,4].includes(e)}function FJ(e){return![1,2,4].includes(e)}function IJ(e,t,n){let r=z(e,n),i=z(t,n),a=z(e,n);return a.setFullYear(r.getFullYear()+1),i.getTime()<=a.getTime()}let LJ=[{value:0,label:j(`US (NASD) 30/360`)},{value:1,label:j(`Actual/Actual`)},{value:2,label:j(`Actual/360`)},{value:3,label:j(`Actual/365`)},{value:4,label:j(`European 30/360`)}];var RJ=l({DATE:()=>BJ,DATEDIF:()=>VJ,DATEVALUE:()=>HJ,DAY:()=>UJ,DAYS:()=>WJ,DAYS360:()=>GJ,EDATE:()=>KJ,EOMONTH:()=>qJ,HOUR:()=>JJ,ISOWEEKNUM:()=>YJ,MINUTE:()=>XJ,MONTH:()=>ZJ,MONTH_END:()=>mY,MONTH_START:()=>pY,NETWORKDAYS:()=>QJ,NETWORKDAYS_INTL:()=>tY,NOW:()=>nY,QUARTER:()=>hY,QUARTER_END:()=>_Y,QUARTER_START:()=>gY,SECOND:()=>rY,TIME:()=>iY,TIMEVALUE:()=>aY,TODAY:()=>oY,WEEKDAY:()=>sY,WEEKNUM:()=>cY,WORKDAY:()=>lY,WORKDAY_INTL:()=>uY,YEAR:()=>dY,YEARFRAC:()=>fY,YEAR_END:()=>yY,YEAR_START:()=>vY}),zJ=function(e){return e.WHOLE_YEARS=`Y`,e.WHOLE_MONTHS=`M`,e.WHOLE_DAYS=`D`,e.DAYS_WITHOUT_WHOLE_MONTHS=`MD`,e.MONTH_WITHOUT_WHOLE_YEARS=`YM`,e.DAYS_BETWEEN_NO_MORE_THAN_ONE_YEAR=`YD`,e}(zJ||{});let BJ={description:j(`Converts year/month/day into a date.`),args:[k(`year (number)`,j(`The year component of the date.`)),k(`month (number)`,j(`The month component of the date.`)),k(`day (number)`,j(`The day component of the date.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=Math.trunc(I(n,this.locale));if(r<0||r>9999)return new N(j(`The year (%s) must be between 0 and 9999 inclusive.`,r.toString()));r<1900&&(r+=1900);let o=ha(new P(r,i-1,a));return o<0?new N(j(`The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.`)):{value:o,format:this.locale.dateFormat}},isExported:!0},VJ={description:j(`Calculates the number of days, months, or years between two dates.`),args:[k(`start_date (date)`,j(`The start date to consider in the calculation. Must be a reference to a cell containing a DATE, a function returning a DATE type, or a number.`)),k(`end_date (date)`,j(`The end date to consider in the calculation. Must be a reference to a cell containing a DATE, a function returning a DATE type, or a number.`)),k(`unit (string)`,j(`A text abbreviation for unit of time.`),[{value:`Y`,label:j(`The number of whole years between start_date and end_date`)},{value:`M`,label:j(`The number of whole months between start_date and end_date`)},{value:`D`,label:j(`The number of days between start_date and end_date`)},{value:`MD`,label:j(`The number of days between start_date and end_date after subtracting whole months`)},{value:`YM`,label:j(`The number of whole months between start_date and end_date after subtracting whole years`)},{value:`YD`,label:j(`The number of days between start_date and end_date, assuming start_date and end_date were no more than one year apart`)}])],compute:function(e,t,n){let r=L(n).toUpperCase();if(!Object.values(zJ).includes(r))return new N(Wa(Object.values(zJ),L(n)));let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=ma(i),s=ma(a);if(a<i)return new N(j(`start_date (%s) should be on or before end_date (%s).`,o.toLocaleDateString(),s.toLocaleDateString()));switch(r){case`Y`:return wa(o,s);case`M`:return Sa(o,s);case`D`:return Ca(o,s);case`YM`:return Sa(o,s)-wa(o,s)*12;case`MD`:let e=s.getDate()-o.getDate();return e<0&&(e=_a(new P(s.getFullYear(),s.getMonth()-1,1))-Math.abs(e)),e;case`YD`:{if(Ta(i,a))return Ca(o,s);let e=new P(o.getFullYear(),s.getMonth(),s.getDate()),t=Ca(o,e);return t<0&&(e.setFullYear(o.getFullYear()+1),t=Ca(o,e)),t}}},isExported:!0},HJ={description:j(`Converts a date string to a date value.`),args:[k(`date_string (string)`,j(`The string representing the date.`))],compute:function(e){let t=L(e),n=ia(t,this.locale);return n===null?new N(j(`The date_string (%s) cannot be parsed to date/time.`,t.toString())):Math.trunc(n.value)},isExported:!0},UJ={description:j(`Day of the month that a specific date falls on.`),args:[k(`date (string)`,j(`The date from which to extract the day.`))],compute:function(e){return z(e,this.locale).getDate()},isExported:!0},WJ={description:j(`Number of days between two dates.`),args:[k(`end_date (date)`,j(`The end of the date range.`)),k(`start_date (date)`,j(`The start of the date range.`))],compute:function(e,t){let n=z(e,this.locale),r=z(t,this.locale),i=n.getTime()-r.getTime();return Math.round(i/Wi)},isExported:!0},GJ={description:j(`Number of days between two dates on a 360-day year (months of 30 days).`),args:[k(`start_date (date)`,j(`The start date to consider in the calculation.`)),k(`end_date (date)`,j(`The end date to consider in the calculation.`)),k(`method (boolean, default=false)`,j(`An indicator of what day count method to use.`),[{value:!1,label:j(`U.S. NASD method (default)`)},{value:!0,label:j(`European method`)}])],compute:function(e,t,n={value:!1}){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=xa(r,i,R(n)?4:0);return Math.sign(i-r)*Math.round(a*360)},isExported:!0},KJ={description:j(`Date a number of months before/after another date.`),args:[k(`start_date (date)`,j(`The date from which to calculate the result.`)),k(`months (number)`,j(`The number of months before (negative) or after (positive) 'start_date' to calculate.`))],compute:function(e,t){return{value:ha(ya(z(e,this.locale),Math.trunc(I(t,this.locale)),!1)),format:this.locale.dateFormat}},isExported:!0},qJ={description:j(`Last day of a month before or after a date.`),args:[k(`start_date (date)`,j(`The date from which to calculate the result.`)),k(`months (number)`,j(`The number of months before (negative) or after (positive) 'start_date' to consider.`))],compute:function(e,t){let n=z(e,this.locale),r=Math.trunc(I(t,this.locale));return{value:ha(new P(n.getFullYear(),n.getMonth()+r+1,0)),format:this.locale.dateFormat}},isExported:!0},JJ={description:j(`Hour component of a specific time.`),args:[k(`time (date)`,j(`The time from which to calculate the hour component.`))],compute:function(e){return z(e,this.locale).getHours()},isExported:!0},YJ={description:j(`ISO week number of the year.`),args:[k(`date (date)`,j(`The date for which to determine the ISO week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.`))],compute:function(e){let t=z(e,this.locale),n=t.getFullYear(),r=1;for(;new P(n,0,r).getDay()!==4;)r+=1;let i=new P(n,0,r-3),a=31;for(;new P(n,11,a).getDay()!==4;)--a;let o=new P(n,11,a+3),s;s=i.getTime()<=t.getTime()?t.getTime()<=o.getTime()?0:1:-1;let c;switch(s){case 0:c=i;break;case 1:c=new P(n,11,a+3+1);break;case-1:let e=1;for(;new P(n-1,0,e).getDay()!==4;)e+=1;c=new P(n-1,0,e-3);break}let l=(t.getTime()-c.getTime())/Wi;return Math.floor(l/7)+1},isExported:!0},XJ={description:j(`Minute component of a specific time.`),args:[k(`time (date)`,j(`The time from which to calculate the minute component.`))],compute:function(e){return z(e,this.locale).getMinutes()},isExported:!0},ZJ={description:j(`Month of the year a specific date falls in`),args:[k(`date (date)`,j(`The date from which to extract the month.`))],compute:function(e){return z(e,this.locale).getMonth()+1},isExported:!0},QJ={description:j(`Net working days between two provided days.`),args:[k(`start_date (date)`,j(`The start date of the period from which to calculate the number of net working days.`)),k(`end_date (date)`,j(`The end date of the period from which to calculate the number of net working days.`)),k(`holidays (date, range<date>, optional)`,j(`A range or array constant containing the date serial numbers to consider holidays.`))],compute:function(e,t,n){return tY.compute.bind(this)(e,t,{value:1},n)},isExported:!0};function $J(e){let t=e?.value;if(typeof t==`string`){uh(t.length===7&&[...t].every(e=>e===`0`||e===`1`),j(`When weekend is a string (%s) it must be composed of "0" or "1".`,t));let e=[];for(let n=0;n<7;n++)t[n]===`1`&&e.push((n+1)%7);return e}if(typeof t==`number`)return uh(1<=t&&t<=7||11<=t&&t<=17,j(`The weekend (%s) must be a string or a number in the range 1-7 or 11-17.`,t.toString())),t<=7?[t-2==-1?6:t-2,t-1]:[t-11];throw new N(j(`The weekend must be a number or a string.`))}let eY=[{value:1,label:j(`Saturday/Sunday are weekends`)},{value:2,label:j(`Sunday/Monday are weekends`)},{value:3,label:j(`Monday/Tuesday are weekends`)},{value:4,label:j(`Tuesday/Wednesday are weekends`)},{value:5,label:j(`Wednesday/Thursday are weekends`)},{value:6,label:j(`Thursday/Friday are weekends`)},{value:7,label:j(`Friday/Saturday are weekends`)},{value:11,label:j(`Sunday is the only weekend`)},{value:12,label:j(`Monday is the only weekend`)},{value:13,label:j(`Tuesday is the only weekend`)},{value:14,label:j(`Wednesday is the only weekend`)},{value:15,label:j(`Thursday is the only weekend`)},{value:16,label:j(`Friday is the only weekend`)},{value:17,label:j(`Saturday is the only weekend`)}],tY={description:j(`Net working days between two dates (specifying weekends).`),args:[k(`start_date (date)`,j(`The start date of the period from which to calculate the number of net working days.`)),k(`end_date (date)`,j(`The end date of the period from which to calculate the number of net working days.`)),k(`weekend (any, default=1)`,j(`A number or string representing which days of the week are considered weekends.`),eY),k(`holidays (date, range<date>, optional)`,j(`A range or array constant containing the dates to consider as holidays.`))],compute:function(e,t,n={value:1},r){let i=z(e,this.locale),a=z(t,this.locale),o=$J(n),s=new Set;r!==void 0&&to([r],e=>{let t=z(e,this.locale);s.add(t.getTime())});let c=i.getTime()>a.getTime(),l=P.fromTimestamp((c?i:a).getTime()),u=P.fromTimestamp((c?a:i).getTime()),d=l.getTime(),f=u.getTime(),p=0;for(;f<=d;)!o.includes(u.getDay())&&!s.has(f)&&(p+=1),u.setDate(u.getDate()+1),f=u.getTime();return c?-p:p},isExported:!0},nY={description:j(`Current date and time as a date value.`),args:[],compute:function(){let e=P.now(),t=e.getTime()-Ui.getTime(),n=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return{value:Math.floor(t/Wi)+n,format:sb(this.locale)}},isExported:!0},rY={description:j(`Minute component of a specific time.`),args:[k(`time (date)`,j(`The time from which to calculate the second component.`))],compute:function(e){return z(e,this.locale).getSeconds()},isExported:!0},iY={description:j(`Converts hour/minute/second into a time.`),args:[k(`hour (number)`,j(`The hour component of the time.`)),k(`minute (number)`,j(`The minute component of the time.`)),k(`second (number)`,j(`The second component of the time.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=Math.trunc(I(n,this.locale));return i+=Math.floor(a/60),a=a%60+(a<0?60:0),r+=Math.floor(i/60),i=i%60+(i<0?60:0),r%=24,r<0?new N(j(`The function [[FUNCTION_NAME]] result cannot be negative`)):{value:r/24+i/1440+a/(1440*60),format:this.locale.timeFormat}},isExported:!0},aY={description:j(`Converts a time string into its serial number representation.`),args:[k(`time_string (string)`,j(`The string that holds the time representation.`))],compute:function(e){let t=L(e),n=ia(t,this.locale);if(n===null)return new N(j(`The time_string (%s) cannot be parsed to date/time.`,t));let r=n.value-Math.trunc(n.value);return r<0?1+r:r},isExported:!0},oY={description:j(`Current date as a date value.`),args:[],compute:function(){let e=P.now();return{value:ha(new P(e.getFullYear(),e.getMonth(),e.getDate())),format:this.locale.dateFormat}},isExported:!0},sY={description:j(`Day of the week of the date provided (as number).`),args:[k(`date (date)`,j(`The date for which to determine the day of the week. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),k(`type (number, default=1)`,j(`A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1.`),[{value:1,label:j(`Numbers 1 (Sunday) trough 7 (Saturday)`)},{value:2,label:j(`Numbers 1 (Monday) trough 7 (Sunday)`)},{value:3,label:j(`Numbers 0 (Monday) trough 6 (Sunday)`)},{value:11,label:j(`Numbers 1 (Monday) trough 7 (Sunday)`)},{value:12,label:j(`Numbers 1 (Tuesday) trough 7 (Monday)`)},{value:13,label:j(`Numbers 1 (Wednesday) trough 7 (Tuesday)`)},{value:14,label:j(`Numbers 1 (Thursday) trough 7 (Wednesday)`)},{value:15,label:j(`Numbers 1 (Friday) trough 7 (Thursday)`)},{value:16,label:j(`Numbers 1 (Saturday) trough 7 (Friday)`)},{value:17,label:j(`Numbers 1 (Sunday) trough 7 (Saturday)`)}])],compute:function(e,t={value:1}){let n=z(e,this.locale),r=Math.round(I(t,this.locale)),i=n.getDay();if(!(1<=r&&r<=3)&&!(11<=r&&r<=17))return new N(j(`The type (%s) must be between 1 and 3 or between 11 and 17.`,r));switch(r){case 1:return i+1;case 2:return i===0?7:i;case 3:return i===0?6:i-1}let a=r-10,o=(i+1-a+7)%7;return o===0?7:o},isExported:!0},cY={description:j(`Week number of the year.`),args:[k(`date (date)`,j(`The date for which to determine the week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),k(`type (number, default=1)`,j(`A number representing the day that a week starts on. Sunday = 1.`),[{value:1,label:j(`Sunday`)},{value:2,label:j(`Monday`)},{value:11,label:j(`Monday`)},{value:12,label:j(`Tuesday`)},{value:13,label:j(`Wednesday`)},{value:14,label:j(`Thursday`)},{value:15,label:j(`Friday`)},{value:16,label:j(`Saturday`)},{value:17,label:j(`Sunday`)},{value:21,label:j(`ISO week number (Monday as first day of the week)`)}])],compute:function(e,t={value:1}){let n=z(e,this.locale),r=Math.round(I(t,this.locale));if(![1,2,11,12,13,14,15,16,17,21].includes(r))return new N(j(`The type (%s) is out of range.`,r.toString()));if(r===21)return YJ.compute.bind(this)(e);let i;i=r===1||r===2?r-1:r-10==7?0:r-10;let a=n.getFullYear(),o=1,s=new P(a,0,o);for(;s.getDay()!==i;)o+=1,s=new P(a,0,o);let c=(n.getTime()-s.getTime())/Wi;return c<0?1:Math.floor(c/7)+(o===1?1:2)},isExported:!0},lY={description:j(`Date after a number of workdays.`),args:[k(`start_date (date)`,j(`The date from which to begin counting.`)),k(`num_days (number)`,j(`The number of working days to advance from start_date. If negative, counts backwards.`)),k(`holidays (date, range<date>, optional)`,j(`A range or array constant containing the dates to consider holidays.`))],compute:function(e,t,n={value:null}){return uY.compute.bind(this)(e,t,{value:1},n)},isExported:!0},uY={description:j(`Date after a number of workdays (specifying weekends).`),args:[k(`start_date (date)`,j(`The date from which to begin counting.`)),k(`num_days (number)`,j(`The number of working days to advance from start_date. If negative, counts backwards.`)),k(`weekend (any, default=1)`,j(`A number or string representing which days of the week are considered weekends.`),eY),k(`holidays (date, range<date>, optional)`,j(`A range or array constant containing the dates to consider holidays.`))],compute:function(e,t,n={value:1},r){let i=z(e,this.locale),a=Math.trunc(I(t,this.locale));if(n.value===`1111111`)return new N(j(`The weekend must be different from '1111111'.`));let o=$J(n),s=new Set;r!==void 0&&to([r],e=>{let t=z(e,this.locale);s.add(t.getTime())});let c=P.fromTimestamp(i.getTime()),l=c.getTime(),u=Math.sign(a),d=Math.abs(a);for(;d>0;)c.setDate(c.getDate()+u),l=c.getTime(),!o.includes(c.getDay())&&!s.has(l)&&--d;let f=l-Ui.getTime();return{value:Math.round(f/Wi),format:this.locale.dateFormat}},isExported:!0},dY={description:j(`Year specified by a given date.`),args:[k(`date (date)`,j(`The date from which to extract the year.`))],compute:function(e){return z(e,this.locale).getFullYear()},isExported:!0},fY={description:j(`Exact number of years between two dates.`),args:[k(`start_date (date)`,j(`The start date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),k(`end_date (date)`,j(`The end date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),k(`day_count_convention (number, default=0)`,j(`An indicator of what day count method to use.`),LJ)],compute:function(e,t,n={value:0}){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=Math.trunc(I(n,this.locale));return r<0?new N(j(`The start_date (%s) must be positive or null.`,r)):i<0?new N(j(`The end_date (%s) must be positive or null.`,i)):0>a||a>4?new N(j(`The day_count_convention (%s) must be between 0 and 4 inclusive.`,a)):xa(r,i,a)}},pY={description:j(`First day of the month preceding a date.`),args:[k(`date (date)`,j(`The date from which to calculate the result.`))],compute:function(e){let t=z(e,this.locale);return{value:ha(new P(t.getFullYear(),t.getMonth(),1)),format:this.locale.dateFormat}}},mY={description:j(`Last day of the month following a date.`),args:[k(`date (date)`,j(`The date from which to calculate the result.`))],compute:function(e){return qJ.compute.bind(this)(e,{value:0})}},hY={description:j(`Quarter of the year a specific date falls in`),args:[k(`date (date)`,j(`The date from which to extract the quarter.`))],compute:function(e){return Math.ceil((z(e,this.locale).getMonth()+1)/3)}},gY={description:j(`First day of the quarter of the year a specific date falls in.`),args:[k(`date (date)`,j(`The date from which to calculate the start of quarter.`))],compute:function(e){let t=hY.compute.bind(this)(e);return{value:ha(new P(dY.compute.bind(this)(e),(t-1)*3,1)),format:this.locale.dateFormat}}},_Y={description:j(`Last day of the quarter of the year a specific date falls in.`),args:[k(`date (date)`,j(`The date from which to calculate the end of quarter.`))],compute:function(e){let t=hY.compute.bind(this)(e);return{value:ha(new P(dY.compute.bind(this)(e),t*3,0)),format:this.locale.dateFormat}}},vY={description:j(`First day of the year a specific date falls in.`),args:[k(`date (date)`,j(`The date from which to calculate the start of the year.`))],compute:function(e){return{value:ha(new P(dY.compute.bind(this)(e),0,1)),format:this.locale.dateFormat}}},yY={description:j(`Last day of the year a specific date falls in.`),args:[k(`date (date)`,j(`The date from which to calculate the end of the year.`))],compute:function(e){return{value:ha(new P(dY.compute.bind(this)(e)+1,0,0)),format:this.locale.dateFormat}}};var bY=l({DELTA:()=>xY});let xY={description:j(`Compare two numeric values, returning 1 if they're equal.`),args:[k(`number1 (number)`,j(`The first number to compare.`)),k(`number2 (number, default=0)`,j(`The second number to compare.`))],compute:function(e,t={value:0}){return+(I(e,this.locale)===I(t,this.locale))},isExported:!0};var SY=l({FILTER:()=>wY,SORT:()=>TY,SORTN:()=>EY,UNIQUE:()=>DY});function CY(e,t,...n){for(let e=0;e<n.length;e++){let t=e%2==0?`sort_column`:`is_ascending`;uh(n[e]!==void 0,j(`Value for parameter %s is missing in [[FUNCTION_NAME]].`,t))}let r=[],i=[],a=e.length;for(let o=0;o<n.length;o+=2){r.push(R(bh(n[o+1])?.value)?`asc`:`desc`);let s=n[o];if(Je(s)&&(s.length>1||s[0].length>1))uh(s.length===1&&s[0].length===a,j(`Wrong size for %s. Expected a range of size 1x%s. Got %sx%s.`,`sort_column${o+1}`,a,s.length,s[0].length)),i.push(s.flat().map(e=>e.value));else{let n=I(bh(s)?.value,t);if(n<1||n>e[0].length)return e;i.push(e.map(e=>e[n-1].value))}}if(i.length===0)for(let t=0;t<e[0].length;t++)i.push(e.map(e=>e[t].value)),r.push(`asc`);let o={desc:bz(`desc`),asc:bz(`asc`)},s=C(0,e.length);return s.sort((e,t)=>{for(let[n,a]of i.entries()){let i=a[e],s=a[t],c={value:i,type:i===null?`empty`:typeof i==`string`?`text`:typeof i},l={value:s,type:s===null?`empty`:typeof s==`string`?`text`:typeof s},u=o[r[n]](c,l);if(u!==0)return u}return 0}),s.map(t=>e[t])}let wY={description:j(`Returns a filtered version of the source range, returning only rows or columns that meet the specified conditions.`),args:[k(`range (any, range<any>)`,j(`The data to be filtered.`)),k(`condition (boolean, range<boolean>, repeating)`,j(`Column or row containing true or false values corresponding to the range.`))],compute:function(e,...t){let n=B(e),r=t.map(e=>co(B(e),e=>e.value));for(let e of r)if(!fh(e))return new N(j(`The arguments condition must be a single column or row.`));if(!ph(...t))return new N(j(`The arguments conditions must have the same dimensions.`));let i=r.map(e=>e.flat()),a=r[0].length===1?`row`:`col`;if(n=a===`row`?uo(n):n,i.some(e=>e.length!==n.length))return new N(j(`FILTER has mismatched sizes on the range and conditions.`));let o=[];for(let e=0;e<n.length;e++){let t=n[e];i.every(t=>(typeof t[e]==`boolean`||typeof t[e]==`number`)&&t[e])&&o.push(t)}return o.length?a===`row`?uo(o):o:new Ri(j(`No match found in FILTER evaluation`))},isExported:!1},TY={description:j(`Sorts the rows of a given array or range by the values in one or more columns.`),args:[k(`range (range)`,j(`The data to be sorted.`)),k(`sort_column (any, range<number>, repeating, optional)`,j(`The index of the column in range or a range outside of range containing the value by which to sort.`)),k(`is_ascending (boolean, repeating, optional)`,j(`TRUE or FALSE indicating whether to sort sort_column in ascending order. FALSE sorts in descending order.`),[{value:!0,label:j(`Ascending`)},{value:!1,label:j(`Descending`)}])],compute:function(e,...t){return uo(CY(uo(e),this.locale,...t))},isExported:!0},EY={description:j(`Returns the first n items in a data set after performing a sort.`),args:[k(`range (range)`,j(`The data to be sorted.`)),k(`n (number)`,j(`The number of items to return.`)),k(`display_ties_mode (number, default=0)`,j(`A number representing the way to display ties.`)),k(`sort_column (number, range<number>, repeating, optional)`,j(`The index of the column in range or a range outside of range containing the value by which to sort.`)),k(`is_ascending (boolean, repeating, optional)`,j(`TRUE or FALSE indicating whether to sort sort_column in ascending order. FALSE sorts in descending order.`),[{value:!0,label:j(`Ascending`)},{value:!1,label:j(`Descending`)}])],compute:function(e,t,...n){let r=I(t?.value??1,this.locale),i=n.length%2==0?0:I(n[0]?.value,this.locale),a=n.length%2==0?n:n.slice(1);if(r<0)return new N(j(`Wrong value of 'n'. Expected a positive number. Got %s.`,r));if(i<0||i>3)return new N(j(`Wrong value of 'display_ties_mode'. Expected a positive number between 0 and 3. Got %s.`,i));let o=CY(uo(e),this.locale,...a),s=(e,t)=>JSON.stringify(o[e].map(e=>e.value))===JSON.stringify(o[t].map(e=>e.value));switch(i){case 0:return uo(o.slice(0,r));case 1:for(let e=r;e<o.length;e++)if(!s(e,r-1))return uo(o.slice(0,e));return uo(o);case 2:{let e=[o[0]];for(let t=1;t<o.length;t++)for(let n=0;n<t&&!s(t,n);n++)n===t-1&&e.push(o[t]);return uo(e.slice(0,r))}case 3:{let e=[o[0]],t=1;for(let n=1;n<o.length&&(s(n,n-1)||t++,!(t>r));n++)e.push(o[n]);return uo(e)}}},isExported:!1},DY={description:j(`Unique rows in the provided source range.`),args:[k(`range (any, range<any>)`,j(`The data to filter by unique entries.`)),k(`by_column (boolean, default=FALSE)`,j(`Whether to filter the data by columns or by rows.`),[{value:!0,label:j(`Return unique columns`)},{value:!1,label:j(`Return unique rows`)}]),k(`exactly_once (boolean, default=FALSE)`,j(`Whether to return only entries with no duplicates.`),[{value:!0,label:j(`Return items that appear exactly once`)},{value:!1,label:j(`Return every distinct item`)}])],compute:function(e={value:``},t,n){if(!Je(e))return[[e]];let r=R(t?.value)||!1,i=R(n?.value)||!1;r||(e=uo(e));let a=new Map;for(let t of e){let e=JSON.stringify(t.map(e=>e.value)),n=a.get(e);n?n.count++:a.set(e,{data:t,count:1})}let o=[];for(let e of a.values())i&&e.count>1||o.push(e.data);return o.length?r?o:uo(o):new N(j(`No unique values found`))},isExported:!0};var OY=l({ACCRINTM:()=>NY,AMORLINC:()=>PY,COUPDAYBS:()=>IY,COUPDAYS:()=>FY,COUPDAYSNC:()=>LY,COUPNCD:()=>RY,COUPNUM:()=>zY,COUPPCD:()=>BY,CUMIPMT:()=>VY,CUMPRINC:()=>HY,DB:()=>UY,DDB:()=>GY,DISC:()=>KY,DOLLARDE:()=>qY,DOLLARFR:()=>JY,DURATION:()=>YY,EFFECT:()=>XY,FV:()=>QY,FVSCHEDULE:()=>$Y,INTRATE:()=>eX,IPMT:()=>nX,IRR:()=>iX,ISPMT:()=>aX,MDURATION:()=>oX,MIRR:()=>sX,NOMINAL:()=>cX,NPER:()=>lX,NPV:()=>dX,PDURATION:()=>fX,PMT:()=>mX,PPMT:()=>gX,PRICE:()=>vX,PRICEDISC:()=>yX,PRICEMAT:()=>bX,PV:()=>_X,RATE:()=>SX,RECEIVED:()=>CX,RRI:()=>wX,SLN:()=>TX,SYD:()=>EX,TBILLEQ:()=>kX,TBILLPRICE:()=>OX,TBILLYIELD:()=>AX,VDB:()=>jX,XIRR:()=>MX,XNPV:()=>NX,YIELD:()=>PX,YIELDDISC:()=>FX,YIELDMAT:()=>IX});let kY=[{value:1,label:j(`Annual`)},{value:2,label:j(`Semi-annual`)},{value:4,label:j(`Quarterly`)}],AY=[{value:0,label:j(`End of period (default)`)},{value:1,label:j(`Beginning of period`)}],jY=[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),kY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),LJ)];function MY(e,t,n,r,i=1e-10,a){let o=n,s,c,l,u=!1,d=0,f;do{if(l=e(o),isNaN(l)){uh(d<r&&a!==void 0,j(`Function [[FUNCTION_NAME]] didn't find any result.`)),d++,o=a(f),f=o;continue}s=o-l/t(o),c=Math.abs(s-o),o=s,u=c<i||Math.abs(l)<i,uh(d<r,j(`Function [[FUNCTION_NAME]] didn't find any result.`)),d++}while(!u);return o}let NY={description:j(`Accrued interest of security paying at maturity.`),args:[k(`issue (date)`,j(`The date the security was initially issued.`)),k(`maturity (date)`,j(`The maturity date of the security.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),LJ)],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(r,this.locale),c=I(n,this.locale),l=Math.trunc(I(i,this.locale));if(a<0)return new N(tJ(a));if(a>=o)return new N(aJ(a,o));if(PJ(l))return new N(Hq(l));if(s<=0)return new N(CJ(s));if(c<=0)return new N(SJ(c));let u=xa(a,o,l);return s*c*u},isExported:!0},PY={description:j(`Depreciation for an accounting period.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`purchase_date (date)`,j(`The date the asset was purchased.`)),k(`first_period_end (date)`,j(`The date the first period ended.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`period (number)`,j(`The single period within life for which to calculate depreciation.`)),k(`rate (number)`,j(`The deprecation rate.`)),k(`day_count_convention (number, optional)`,j(`An indicator of what day count method to use.`),LJ)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=I(e,this.locale),c=Math.trunc(I(t,this.locale)),l=Math.trunc(I(n,this.locale)),u=I(r,this.locale),d=I(i,this.locale),f=I(a,this.locale),p=Math.trunc(I(o,this.locale));if(s<=0)return new N(Bq(s));if(c<0)return new N(yJ(c));if(u<0)return new N(wJ(u));if(u>s)return new N(TJ(u,s));if(d<0)return new N(fJ(d));if(f<=0)return new N(SJ(f));if(PJ(p))return new N(Hq(p));if(c>l)return new N(vJ(c,l));let m=d<1&&d>0?1:Math.trunc(d),h=s*f,g=xa(c,l,p),_=c===l?h:h*g,v=s-_-h*m;return v>=u?m===0?_:h:u-v<h?h-(u-v):0},isExported:!0},FY={description:j(`Days in coupon period containing settlement date.`),args:jY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(aJ(i,a));if(FJ(o))return new N(Vq(o));if(PJ(s))return new N(Hq(s));if(s===1){let i=BY.compute.bind(this)(e,t,n,r).value,a=RY.compute.bind(this)(e,t,n,r).value;return I(a,this.locale)-I(i,this.locale)}return(s===3?365:360)/o},isExported:!0},IY={description:j(`Days from settlement until next coupon.`),args:jY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(aJ(i,a));if(FJ(o))return new N(Vq(o));if(PJ(s))return new N(Hq(s));let c=BY.compute.bind(this)(e,t,n,r).value,l=I(c,this.locale);if([1,2,3].includes(s))return i-l;if(s===4){let e=xa(l,i,s);return Math.round(e*360)}let u=z(i,this.locale),d=z(l,this.locale),f=d.getFullYear(),p=u.getFullYear(),m=d.getMonth()+1,h=u.getMonth()+1,g=d.getDate(),_=u.getDate();return m===2&&h===2&&va(d)&&va(u)&&(_=30),_===31&&(g===30||g===31)&&(_=30),m===2&&va(d)&&(g=30),g===31&&(g=30),(p-f)*360+(h-m)*30+(_-g)},isExported:!0},LY={description:j(`Days from settlement until next coupon.`),args:jY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(aJ(i,a));if(FJ(o))return new N(Vq(o));if(PJ(s))return new N(Hq(s));let c=RY.compute.bind(this)(e,t,n,r).value,l=I(c,this.locale);if([1,2,3].includes(s))return l-i;if(s===4){let e=xa(i,l,s);return Math.round(e*360)}let u=IY.compute.bind(this)(e,t,n,r);return I(FY.compute.bind(this)(e,t,n,r),this.locale)-I(u,this.locale)},isExported:!0},RY={description:j(`Next coupon date after the settlement date.`),args:jY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(aJ(i,a));if(FJ(o))return new N(Vq(o));if(PJ(s))return new N(Hq(s));let c=12/o,l=zY.compute.bind(this)(e,t,n,r);return{value:ha(ya(z(a,this.locale),-(I(l,this.locale)-1)*c,!0)),format:this.locale.dateFormat}},isExported:!0},zY={description:j(`Number of coupons between settlement and maturity.`),args:jY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(aJ(i,a));if(FJ(o))return new N(Vq(o));if(PJ(s))return new N(Hq(s));let c=1,l=a,u=12/o;for(;l>i;)l=ha(ya(z(l,this.locale),-u,!1)),c++;return c-1},isExported:!0},BY={description:j(`Last coupon date prior to or on the settlement date.`),args:jY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(aJ(i,a));if(FJ(o))return new N(Vq(o));if(PJ(s))return new N(Hq(s));let c=12/o,l=zY.compute.bind(this)(e,t,n,r);return{value:ha(ya(z(a,this.locale),-l*c,!0)),format:this.locale.dateFormat}},isExported:!0},VY={description:j(`Cumulative interest paid over a set of periods.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`first_period (number)`,j(`The number of the payment period to begin the cumulative calculation.`)),k(`last_period (number)`,j(`The number of the payment period to end the cumulative calculation.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),AY)],compute:function(e,t,n,r,i,a={value:0}){let o=I(r,this.locale),s=I(i,this.locale),c=I(e,this.locale),l=I(n,this.locale),u=I(t,this.locale),d=+!!R(a);if(u<=0)return new N(lJ(u));if(o<=0)return new N(Qq(o));if(s<=0)return new N(rJ(s));if(o>s)return new N(Zq(o,s));if(s>u)return new N(nJ(s,u));if(c<=0)return new N(SJ(c));if(l<=0)return new N(gJ(l));let f=0;for(let e=o;e<=s;e++)f+=tX(c,e,u,l,0,d);return f},isExported:!0},HY={description:j(`Cumulative principal paid over a set of periods.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`first_period (number)`,j(`The number of the payment period to begin the cumulative calculation.`)),k(`last_period (number)`,j(`The number of the payment period to end the cumulative calculation.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),AY)],compute:function(e,t,n,r,i,a={value:0}){let o=I(r,this.locale),s=I(i,this.locale),c=I(e,this.locale),l=I(n,this.locale),u=I(t,this.locale),d=+!!R(a);if(u<=0)return new N(lJ(u));if(o<=0)return new N(Qq(o));if(s<=0)return new N(rJ(s));if(o>s)return new N(Zq(o,s));if(s>u)return new N(nJ(s,u));if(c<=0)return new N(SJ(c));if(l<=0)return new N(gJ(l));let f=0;for(let e=o;e<=s;e++)f+=hX(c,e,u,l,0,d);return f},isExported:!0},UY={description:j(`Depreciation via declining balance method.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),k(`period (number)`,j(`The single period within life for which to calculate depreciation.`)),k(`month (number, optional)`,j(`The number of months in the first year of depreciation.`))],compute:function(e,t,n,r,...i){let a=I(e,this.locale),o=I(t,this.locale),s=I(n,this.locale),c=Math.trunc(I(r,this.locale)),l=i.length?Math.trunc(I(i[0],this.locale)):12,u=s+(l===12?0:1);if(a<0)return new N(zq(a));if(o<0)return new N(wJ(o));if(c<=0)return new N(hJ(c));if(s<=0)return new N(iJ(s));if(1>l||l>12)return new N(oJ(l));if(c>u)return new N(dJ(c,u));let d=l/12,f=1-(o/a)**(1/s);f=Math.round(f*1e3)/1e3;let p=a,m=a*(1-f*d);for(let e=1;e<c;e++)p=m,m=p*(1-f),e===s&&(m=p*(1-f*(1-d)));return{value:p-m,format:`#,##0.00`}},isExported:!0},WY=`#,##0.00`,GY={description:j(`Depreciation via double-declining balance method.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),k(`period (number)`,j(`The single period within life for which to calculate depreciation.`)),k(`factor (number, default=2)`,j(`The factor by which depreciation decreases.`))],compute:function(e,t,n,r,i={value:2}){let a=I(e,this.locale),o=I(t,this.locale),s=I(n,this.locale),c=I(r,this.locale),l=I(i,this.locale);if(a<0)return new N(zq(a));if(o<0)return new N(wJ(o));if(c<=0)return new N(hJ(c));if(s<=0)return new N(iJ(s));if(c>s)return new N(mJ(c,s));if(l<=0)return new N(Uq(l));if(a===0||o>=a)return{value:0,format:WY};let u=l/s;if(u>1)return{value:c===1?a-o:0,format:WY};if(c<=1)return{value:a*u,format:WY};let d=a*(1-u)**(c-1),f=a*(1-u)**c,p=f<o?d-o:d-f;return{value:Math.max(p,0),format:WY}},isExported:!0},KY={description:j(`Discount rate of a security based on price.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`price (number)`,j(`The price at which the security is bought per 100 face value.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),LJ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(n,this.locale),c=I(r,this.locale),l=Math.trunc(I(i,this.locale));if(a>=o)return new N(aJ(a,o));if(PJ(l))return new N(Hq(l));if(s<=0)return new N(_J(s));if(c<=0)return new N(CJ(c));let u=xa(a,o,l);return(c-s)/c/u},isExported:!0},qY={description:j(`Convert a decimal fraction to decimal value.`),args:[k(`fractional_price (number)`,j(`The price quotation given using fractional decimal conventions.`)),k(`unit (number)`,j(`The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.`))],compute:function(e,t){let n=I(e,this.locale),r=Math.trunc(I(t,this.locale));if(r<=0)return new N(jJ(r));let i=Math.trunc(n);return i+(n-i)*(10**Math.ceil(Math.log10(r))/r)},isExported:!0},JY={description:j(`Convert a decimal value to decimal fraction.`),args:[k(`decimal_price (number)`,j(`The price quotation given as a decimal value.`)),k(`unit (number)`,j(`The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.`))],compute:function(e,t){let n=I(e,this.locale),r=Math.trunc(I(t,this.locale));if(r<=0)return new N(jJ(r));let i=Math.trunc(n);return i+(n-i)*(r/10**Math.ceil(Math.log10(r)))},isExported:!0},YY={description:j(`Number of periods for an investment to reach a value.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`yield (number)`,j(`The expected annual yield of the security.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),kY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),LJ)],compute:function(e,t,n,r,i,a={value:0}){let o=Math.trunc(I(e,this.locale)),s=Math.trunc(I(t,this.locale)),c=I(n,this.locale),l=I(r,this.locale),u=Math.trunc(I(i,this.locale)),d=Math.trunc(I(a,this.locale));if(o>=s)return new N(aJ(o,s));if(FJ(u))return new N(Vq(u));if(PJ(d))return new N(Hq(d));if(c<0)return new N(xJ(c));if(l<0)return new N(MJ(l));let f=xa(o,s,d),p=f-Math.trunc(f)||1/u,m=Math.ceil(f*u),h=c/u,g=l/u,_=0,v=0;for(let e=1;e<=m;e++){let t=(h+ +(e===m))/(1+g)**e;v+=(p+(e-1)/u)*t,_+=t}return _===0?0:v/_},isExported:!0},XY={description:j(`Annual effective interest rate.`),args:[k(`nominal_rate (number)`,j(`The nominal interest rate per year.`)),k(`periods_per_year (number)`,j(`The number of compounding periods per year.`))],compute:function(e,t){let n=I(e,this.locale),r=Math.trunc(I(t,this.locale));return n<=0?new N(sJ(n)):r<=0?new N(pJ(r)):(1+n/r)**+r-1},isExported:!0};function ZY(e,t,n,r,i){return e===0?-(r+n*t):-r*(1+e)**t-n*(1+e*i)*((1+e)**t-1)/e}let QY={description:j(`Future value of an annuity investment.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`payment_amount (number)`,j(`The amount per period to be paid.`)),k(`present_value (number, default=0)`,j(`The current value of the annuity.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),AY)],compute:function(e,t,n,r={value:0},i={value:0}){return r||=0,i||=0,{value:ZY(I(e,this.locale),I(t,this.locale),I(n,this.locale),I(r,this.locale),+!!R(i)),format:`#,##0.00`}},isExported:!0},$Y={description:j(`Future value of principal from series of rates.`),args:[k(`principal (number)`,j(`The amount of initial capital or value to compound against.`)),k(`rate_schedule (number, range<number>)`,j(`A series of interest rates to compound against the principal.`))],compute:function(e,t){let n=I(e,this.locale);return io([t],(e,t)=>e*(1+I(t,this.locale)),n)},isExported:!0},eX={description:j(`Calculates effective interest rate.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`investment (number)`,j(`The amount invested in the security.`)),k(`redemption (number)`,j(`The amount to be received at maturity.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),LJ)],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(r,this.locale),c=I(n,this.locale),l=Math.trunc(I(i,this.locale));if(a>=o)return new N(aJ(a,o));if(c<=0)return new N(eJ(c));if(s<=0)return new N(CJ(s));if(PJ(l))return new N(Hq(l));let u=xa(a,o,l);return(s-c)/c/u},isExported:!0};function tX(e,t,n,r,i,a){return pX(e,n,r,i,a)-hX(e,t,n,r,i,a)}let nX={description:j(`Payment on the principal of an investment.`),args:[k(`rate (number)`,j(`The annualized rate of interest.`)),k(`period (number)`,j(`The amortization period, in terms of number of periods.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),AY)],compute:function(e,t,n,r,i={value:0},a={value:0}){return{value:tX(I(e,this.locale),I(t,this.locale),I(n,this.locale),I(r,this.locale),I(i,this.locale),+!!R(a)),format:`#,##0.00`}},isExported:!0},rX=.1,iX={description:j(`Internal rate of return given periodic cashflows.`),args:[k(`cashflow_amounts (number, range<number>)`,j(`An array or range containing the income or payments associated with the investment.`)),k(`rate_guess (number, default=${rX})`,j(`An estimate for what the internal rate of return will be.`))],compute:function(e,t={value:rX}){let n=I(t,this.locale);if(n<=-1)return new N(bJ(n));let r=!1,i=!1,a=[];if(no([e],({value:e})=>{e>0&&(r=!0),e<0&&(i=!0),a.push(e)},this.locale),!r||!i)return new N(Rq);let o=a.shift();function s(e,t,n){let r=n.length,i=0;return n.reduce((t,n)=>(i++,t+n*e**(r-i)),t*e**r)}function c(e,t,n){let r=n.length,i=0;return n.reduce((t,n)=>(i++,t+n*(r-i)*e**(r-i-1)),t*r*e**(r-1))}function l(e){return s(e,o,a)}function u(e){return c(e,o,a)}return{value:MY(l,u,n+1,20,1e-5)-1,format:`0%`}},isExported:!0},aX={description:j(`Returns the interest paid at a particular period of an investment.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`period (number)`,j(`The period for which you want to view the interest payment.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`))],compute:function(e,t,n,r){let i=I(e,this.locale),a=I(t,this.locale),o=I(n,this.locale),s=I(r,this.locale);return o===0?new N(cJ(o)):-1*(s-a/o*s)*i},isExported:!0},oX={description:j(`Modified Macaulay duration.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`yield (number)`,j(`The expected annual yield of the security.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),kY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i,a={value:0}){let o=YY.compute.bind(this)(e,t,n,r,i,a),s=I(r,this.locale),c=Math.trunc(I(i,this.locale));return I(o,this.locale)/(1+s/c)},isExported:!0},sX={description:j(`Modified internal rate of return.`),args:[k(`cashflow_amounts (range<number>)`,j(`A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.`)),k(`financing_rate (number)`,j(`The interest rate paid on funds invested.`)),k(`reinvestment_return_rate (number)`,j(`The return (as a percentage) earned on reinvestment of income received from the investment.`))],compute:function(e,t,n){let r=I(t,this.locale),i=I(n,this.locale),a=uo(e).flat().filter(e=>e.value!==null).map(e=>I(e,this.locale)),o=a.length,s=0,c=0;for(let e of C(0,o)){let t=a[e];t>=0?s+=t*(i+1)**(o-e-1):c+=t/(r+1)**e}if(c===0||s===0)return new N(Rq);let l=1/(o-1);return(-s/c)**l-1},isExported:!0},cX={description:j(`Annual nominal interest rate.`),args:[k(`effective_rate (number)`,j(`The effective interest rate per year.`)),k(`periods_per_year (number)`,j(`The number of compounding periods per year.`))],compute:function(e,t){let n=I(e,this.locale),r=Math.trunc(I(t,this.locale));return n<=0?new N(qq(n)):r<=0?new N(pJ(r)):((n+1)**(1/r)-1)*r},isExported:!0},lX={description:j(`Number of payment periods for an investment.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`payment_amount (number)`,j(`The amount of each payment made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),AY)],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=I(e,this.locale),o=I(t,this.locale),s=I(n,this.locale),c=I(r,this.locale),l=+!!R(i);if(a===0)return-(c+s)/o;let u=o*(1+a*l)/a;return Math.log((u-c)/(s+u))/Math.log(1+a)},isExported:!0};function uX(e,t,n,r){let i=0;return ao(n,(t,n)=>(i++,t+n/(1+e)**i),t,r)}let dX={description:j(`The net present value of an investment based on a series of periodic cash flows and a discount rate.`),args:[k(`discount (number)`,j(`The discount rate of the investment over one period.`)),k(`cashflow (number, range<number>, repeating)`,j(`The future cash flows.`))],compute:function(e,...t){let n=I(e,this.locale);return n===-1?new N(Wq(n)):{value:uX(n,0,t,this.locale),format:`#,##0.00`}},isExported:!0},fX={description:j(`Computes the number of periods needed for an investment to reach a value.`),args:[k(`rate (number)`,j(`The rate at which the investment grows each period.`)),k(`present_value (number)`,j(`The investment's current value.`)),k(`future_value (number)`,j(`The investment's desired future value.`))],compute:function(e,t,n){let r=I(e,this.locale),i=I(t,this.locale),a=I(n,this.locale);return r<=0?new N(SJ(r)):i<=0?new N(gJ(i)):a<=0?new N($q(a)):(Math.log(a)-Math.log(i))/Math.log(1+r)},isExported:!0};function pX(e,t,n,r,i){if(t<=0)throw new N(lJ(t));if(e===0)return-(r+n)/t;let a=-(n*(1+e)**t+r);return a=a*e/((1+e*i)*((1+e)**t-1)),a}let mX={description:j(`Periodic payment for an annuity investment.`),args:[k(`rate (number)`,j(`The annualized rate of interest.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),AY)],compute:function(e,t,n,r={value:0},i={value:0}){let a=I(t,this.locale),o=I(e,this.locale),s=+!!R(i),c=I(r,this.locale);return{value:pX(o,a,I(n,this.locale),c,s),format:`#,##0.00`}},isExported:!0};function hX(e,t,n,r,i,a){if(n<=0)throw new N(lJ(n));if(t<=0||t>n)throw new N(uJ(n));let o=pX(e,n,r,i,a);return a===1&&t===1?o:o+-ZY(e,a===0?t-1:t-2,o,r+o*a,0)*e}let gX={description:j(`Payment on the principal of an investment.`),args:[k(`rate (number)`,j(`The annualized rate of interest.`)),k(`period (number)`,j(`The amortization period, in terms of number of periods.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),AY)],compute:function(e,t,n,r,i={value:0},a={value:0}){let o=I(n,this.locale),s=I(e,this.locale),c=I(t,this.locale),l=+!!R(a),u=I(i,this.locale);return{value:hX(s,c,o,I(r,this.locale),u,l),format:`#,##0.00`}},isExported:!0},_X={description:j(`Present value of an annuity investment.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`payment_amount (number)`,j(`The amount per period to be paid.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),AY)],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=I(e,this.locale),o=I(t,this.locale),s=I(n,this.locale),c=I(r,this.locale),l=+!!R(i);return{value:a?-(s*(1+a*l)*((1+a)**o-1)/a+c)/(1+a)**o:-(c+s*o),format:`#,##0.00`}},isExported:!0},vX={description:j(`Price of a security paying periodic interest.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`yield (number)`,j(`The expected annual yield of the security.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),kY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),LJ)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(I(e,this.locale)),c=Math.trunc(I(t,this.locale)),l=I(n,this.locale),u=I(r,this.locale),d=I(i,this.locale),f=Math.trunc(I(a,this.locale)),p=Math.trunc(I(o,this.locale));if(s>=c)return new N(aJ(s,c));if(FJ(f))return new N(Vq(f));if(PJ(p))return new N(Hq(p));if(l<0)return new N(xJ(l));if(u<0)return new N(MJ(u));if(d<=0)return new N(CJ(d));let m=xa(s,c,p)*f,h=Math.ceil(m),g=m-Math.floor(m)||1,_=1+u/f,v=100*l/f;if(h===1)return(v+d)/(g*u/f+1)-v*(1-g);let y=0;for(let e=1;e<=h;e++)y+=v/_**(e-1+g);return d/_**(h-1+g)+y-v*(1-g)},isExported:!0},yX={description:j(`Price of a discount security.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`discount (number)`,j(`The discount rate of the security at time of purchase.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),LJ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(n,this.locale),c=I(r,this.locale),l=Math.trunc(I(i,this.locale));if(a>=o)return new N(aJ(a,o));if(PJ(l))return new N(Hq(l));if(s<=0)return new N(Gq(s));if(c<=0)return new N(CJ(c));let u=xa(a,o,l);return c-s*c*u},isExported:!0},bX={description:j(`Calculates the price of a security paying interest at maturity, based on expected yield.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`issue (date)`,j(`The date the security was initially issued.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`yield (number)`,j(`The expected annual yield of the security.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),LJ)],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(I(e,this.locale)),s=Math.trunc(I(t,this.locale)),c=Math.trunc(I(n,this.locale)),l=I(r,this.locale),u=I(i,this.locale),d=Math.trunc(I(a,this.locale));if(o<=c)return new N(OJ(o,c));if(o>=s)return new N(aJ(o,s));if(PJ(d))return new N(Hq(d));if(l<0)return new N(xJ(l));if(u<0)return new N(MJ(u));let f=xa(o,s,d),p=xa(o,c,d),m=100+xa(c,s,d)*l*100,h=1+f*u,g=p*l*100;return m/h-g},isExported:!0},xX=.1,SX={description:j(`Interest rate of an annuity investment.`),args:[k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`payment_per_period (number)`,j(`The amount per period to be paid.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),AY),k(`rate_guess (number, default=${xX})`,j(`An estimate for what the interest rate will be.`))],compute:function(e,t,n,r={value:0},i={value:0},a={value:xX}){let o=I(e,this.locale),s=I(t,this.locale),c=+!!R(i),l=I(a,this.locale)||xX,u=I(r,this.locale),d=I(n,this.locale);return o<=0?new N(lJ(o)):NJ([s,d,u])?l<=-1?new N(bJ(l)):(u-=s*c,d+=s*c,{value:MY(e=>{let t=(1+e)**+o,n=(t-1)/e;return u+d*t+s*n},e=>{let t=(1+e)**(o-1),n=((1+e)**+o-1)/e,r=o*t/e-n/e;return d*o*t+s*r},l,40,1e-5),format:`0%`}):new N(j(`There must be both positive and negative values in [payment_amount, present_value, future_value].`))},isExported:!0},CX={description:j(`Amount received at maturity for a security.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`investment (number)`,j(`The amount invested (irrespective of face value of each security).`)),k(`discount (number)`,j(`The discount rate of the security invested in.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),LJ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(n,this.locale),c=I(r,this.locale),l=Math.trunc(I(i,this.locale));return a>=o?new N(aJ(a,o)):PJ(l)?new N(Hq(l)):s<=0?new N(eJ(s)):c<=0?new N(Gq(c)):s/(1-c*xa(a,o,l))},isExported:!0},wX={description:j(`Computes the rate needed for an investment to reach a specific value within a specific number of periods.`),args:[k(`number_of_periods (number)`,j(`The number of periods.`)),k(`present_value (number)`,j(`The present value of the investment.`)),k(`future_value (number)`,j(`The future value of the investment.`))],compute:function(e,t,n){let r=I(e,this.locale),i=I(t,this.locale),a=I(n,this.locale);return r<=0?new N(lJ(r)):(a/i)**(1/r)-1},isExported:!0},TX={description:j(`Depreciation of an asset using the straight-line method.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`))],compute:function(e,t,n){let r=I(e,this.locale),i=I(t,this.locale),a=I(n,this.locale);return{value:(r-i)/a,format:`#,##0.00`}},isExported:!0},EX={description:j(`Depreciation via sum of years digit method.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),k(`period (number)`,j(`The single period within life for which to calculate depreciation.`))],compute:function(e,t,n,r){let i=I(e,this.locale),a=I(t,this.locale),o=I(n,this.locale),s=I(r,this.locale);if(s<=0)return new N(hJ(s));if(o<=0)return new N(iJ(o));if(s>o)return new N(mJ(s,o));let c=o*(o+1)/2,l=o-s+1;return{value:(i-a)*(l/c),format:`#,##0.00`}},isExported:!0};function DX(e,t,n){return 100*(1-n*xa(e,t,2))}let OX={description:j(`Price of a US Treasury bill.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`discount (number)`,j(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=I(n,this.locale);return r>=i?new N(aJ(r,i)):IJ(r,i,this.locale)?a<=0?new N(Gq(a)):a>=1?new N(Kq(a)):DX(r,i,a):new N(DJ(r,i))},isExported:!0},kX={description:j(`Equivalent rate of return for a US Treasury bill.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`discount (number)`,j(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=I(n,this.locale);if(r>=i)return new N(aJ(r,i));if(!IJ(r,i,this.locale))return new N(DJ(r,i));if(a<=0)return new N(Gq(a));if(a>=1)return new N(Kq(a));let o=WJ.compute.bind(this)({value:i},{value:r});if(o<=182)return 365*a/(360-a*o);let s=DX(r,i,a)/100,c=o/(o===366?366:365);return(-2*c+2*Math.sqrt(c**2-(2*c-1)*(1-1/s)))/(2*c-1)},isExported:!0},AX={description:j(`The yield of a US Treasury bill based on price.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`price (number)`,j(`The price at which the security is bought per 100 face value.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=I(n,this.locale);if(r>=i)return new N(aJ(r,i));if(!IJ(r,i,this.locale))return new N(DJ(r,i));if(a<=0)return new N(_J(a));let o=xa(r,i,2);return(100-a)/a*(1/o)},isExported:!0},jX={description:j(`Variable declining balance. WARNING : does not handle decimal periods.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),k(`start (number)`,j(`Starting period to calculate depreciation.`)),k(`end (number)`,j(`Ending period to calculate depreciation.`)),k(`factor (number, default=2)`,j(`The number of months in the first year of depreciation.`)),k(`no_switch (number, default=false)`,j(`Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation.`),[{value:!1,label:j(`Switch to straight-line depreciation`)},{value:!0,label:j(`Do not switch to straight-line depreciation`)}])],compute:function(e,t,n,r,i,a={value:2},o={value:!1}){a||=0;let s=I(e,this.locale),c=I(t,this.locale),l=I(n,this.locale),u=Math.trunc(I(r,this.locale)),d=Math.trunc(I(i,this.locale)),f=I(a,this.locale),p=R(o);if(s<0)return new N(zq(s));if(c<0)return new N(wJ(c));if(l<=0)return new N(iJ(l));if(u<0)return new N(kJ(u));if(d<0)return new N(Jq(d));if(u>d)return new N(AJ(u,d));if(d>l)return new N(Yq(d,l));if(f<=0)return new N(Uq(f));if(s===0)return 0;if(c>=s)return u<1?s-c:0;let m=f/l;if(m>=1)return u<1?s-c:0;let h=s,g=0,_=0,v=!1;for(let e=0;e<d;e++){if(!v||p){let t=h*m,n=l-e,r=(h-c)/n;!p&&r>t?(v=!0,g=r):g=t}let t=Math.max(h-g,c);e>=u&&(_+=h-t),h=t}return _},isExported:!0},MX={description:j(`Internal rate of return given non-periodic cash flows.`),args:[k(`cashflow_amounts (range<number>)`,j(`An range containing the income or payments associated with the investment.`)),k(`cashflow_dates (range<number>)`,j(`An range with dates corresponding to the cash flows in cashflow_amounts.`)),k(`rate_guess (number, default=${xX})`,j(`An estimate for what the internal rate of return will be.`))],compute:function(e,t,n={value:xX}){let r=I(n,this.locale);if(!ph(e,t))return new N(Lq);let i=e.flat().map(e=>I(e,this.locale)),a=t.flat().map(e=>I(e,this.locale));if(!NJ(i))return new N(Rq);if(a.some(e=>e<a[0]))return new N(Xq(a[0]));if(r<=-1)return new N(bJ(r));let o=new Map;for(let e of C(0,a.length)){let t=a[e];o.has(t)?o.set(t,o.get(t)+i[e]):o.set(t,i[e])}let s=Array.from(o.keys()),c=s.map(e=>o.get(e));return MY(e=>{let t=c[0];for(let n of C(1,c.length)){let r=(s[0]-s[n])/365;t+=c[n]*(1+e)**r}return t},e=>{let t=0;for(let n of C(1,c.length)){let r=(s[0]-s[n])/365;t+=r*c[n]*(1+e)**(r-1)}return t},r,40,1e-5,e=>e?e/10-.9:-.9)},isExported:!0},NX={description:j(`Net present value given to non-periodic cash flows..`),args:[k(`discount (number)`,j(`The discount rate of the investment over one period.`)),k(`cashflow_amounts (number, range<number>)`,j(`An range containing the income or payments associated with the investment.`)),k(`cashflow_dates (number, range<number>)`,j(`An range with dates corresponding to the cash flows in cashflow_amounts.`))],compute:function(e,t,n){let r=I(e,this.locale);if(!ph(t,n))return new N(Lq);let i=B(t).flat().map(e=>qa(e,this.locale)),a=B(n).flat().map(e=>qa(e,this.locale));if(a.some(e=>e<a[0]))return new N(Xq(a[0]));if(r<=0)return new N(SJ(r));if(i.length===1)return i[0];let o=new Map;for(let e of C(0,a.length)){let t=a[e];o.has(t)?o.set(t,o.get(t)+i[e]):o.set(t,i[e])}let s=Array.from(o.keys()),c=s.map(e=>o.get(e)),l=c[0];for(let e of C(1,c.length)){let t=(s[0]-s[e])/365;l+=c[e]*(1+r)**t}return l},isExported:!0},PX={description:j(`Annual yield of a security paying periodic interest.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`price (number)`,j(`The price at which the security is bought per 100 face value.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),kY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),LJ)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(I(e,this.locale)),c=Math.trunc(I(t,this.locale)),l=I(n,this.locale),u=I(r,this.locale),d=I(i,this.locale),f=Math.trunc(I(a,this.locale)),p=Math.trunc(I(o,this.locale));if(s>=c)return new N(aJ(s,c));if(FJ(f))return new N(Vq(f));if(PJ(p))return new N(Hq(p));if(l<0)return new N(xJ(l));if(u<=0)return new N(_J(u));if(d<=0)return new N(CJ(d));let m=xa(s,c,p)*f,h=Math.ceil(m),g=m-Math.floor(m)||1,_=100*l/f;if(h===1){let e=u+_*(1-g);return(d+_-e)*f*(1/g)/e}function v(e,t,n,r,i,a){let o=a-(e+i*(1-t))*r**(n-1+t);for(let e=1;e<=n;e++)o+=i*r**(e-1);return o}function y(e,t,n,r,i){let a=-(e+i*(1-t))*(n-1+t)*r**(n-2+t);for(let e=1;e<=n;e++)a+=i*(e-1)*r**(e-2);return a}function b(e){return v(u,g,h,e,_,d)}function ee(e){return y(u,g,h,e,_)}return(MY(b,ee,1+(l+1)/f,100,1e-5)-1)*f},isExported:!0},FX={description:j(`Annual yield of a discount security.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`price (number)`,j(`The price at which the security is bought per 100 face value.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),LJ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(n,this.locale),c=I(r,this.locale),l=Math.trunc(I(i,this.locale));if(a>=o)return new N(aJ(a,o));if(PJ(l))return new N(Hq(l));if(s<=0)return new N(_J(s));if(c<=0)return new N(CJ(c));let u=xa(a,o,l);return(c/s-1)/u},isExported:!0},IX={description:j(`Annual yield of a security paying interest at maturity.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`issue (date)`,j(`The date the security was initially issued.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`price (number)`,j(`The price at which the security is bought.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),LJ)],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(I(e,this.locale)),s=Math.trunc(I(t,this.locale)),c=Math.trunc(I(n,this.locale)),l=I(r,this.locale),u=I(i,this.locale),d=Math.trunc(I(a,this.locale));if(o>=s)return new N(aJ(o,s));if(PJ(d))return new N(Hq(d));if(o<c)return new N(EJ(o,c));if(l<0)return new N(xJ(l));if(u<=0)return new N(_J(u));let f=xa(c,s,d),p=xa(c,o,d),m=xa(o,s,d);return(100*(1+l*f)/(u+100*l*p)-1)/m},isExported:!0};var LX=l({CELL:()=>zX,ISBLANK:()=>qX,ISERR:()=>BX,ISERROR:()=>VX,ISFORMULA:()=>YX,ISLOGICAL:()=>HX,ISNA:()=>UX,ISNONTEXT:()=>WX,ISNUMBER:()=>GX,ISTEXT:()=>KX,NA:()=>JX});let RX=[{value:`address`,label:j(`Returns an absolute reference as plain text of the top left cell in reference.`)},{value:`col`,label:j(`Returns the column number of the cell in reference.`)},{value:`contents`,label:j(`Returns the value contained in the top left cell in reference.`)},{value:`format`,label:j(`Returns the format of the top left cell in reference.`)},{value:`row`,label:j(`Returns the row number of the top left cell in reference.`)},{value:`type`,label:j(`Returns the type of data in the cell in reference. The following values are returned: "b" for a blank cell, "l" (for label) if the cell contains plain text, and "v" (for value) if the cell contains any other type of data.`)}],zX={description:j(`Gets information about a cell.`),args:[k(`info_type (string)`,j(`The type of information requested.`),RX),k(`reference (any, range<any>)`,j(`The reference to the cell.`))],compute:function(e,t){let n=L(e).toLowerCase();if(!RX.map(e=>e.value).includes(n))return new N(j(`The info_type should be one of %s.`,RX.join(`, `)));let r=B(t)[0][0],i=r.position;if(i===void 0)return new N(j(`The reference is invalid.`));switch(n){case`address`:return(this.__originSheetId===i.sheetId?``:this.getters.getSheetName(i.sheetId)+`!`)+E(i.col,i.row,{colFixed:!0,rowFixed:!0});case`col`:return i.col+1;case`contents`:return r.value;case`format`:return r.format||``;case`row`:return i.row+1;case`type`:return r.value===null?`b`:iu(r.format)?`l`:typeof r.value==`number`||typeof r.value==`boolean`?`v`:`l`}return``},isExported:!0},BX={description:j(`Whether a value is an error other than #N/A.`),args:[k(`value (any)`,j(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return F(t)&&t!==M.NotAvailable},isExported:!0},VX={description:j(`Whether a value is an error.`),args:[k(`value (any)`,j(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return F(t)},isExported:!0},HX={description:j("Whether a value is `true` or `false`."),args:[k(`value (any)`,j(`The value to be verified as a logical TRUE or FALSE.`))],compute:function(e){return typeof e?.value==`boolean`},isExported:!0},UX={description:j(`Whether a value is the error #N/A.`),args:[k(`value (any)`,j(`The value to be verified as an error type.`))],compute:function(e){return e?.value===M.NotAvailable},isExported:!0},WX={description:j(`Whether a value is non-textual.`),args:[k(`value (any)`,j(`The value to be checked.`))],compute:function(e){return!KX.compute.bind(this)(e)},isExported:!0},GX={description:j(`Whether a value is a number.`),args:[k(`value (any)`,j(`The value to be verified as a number.`))],compute:function(e){return typeof e?.value==`number`},isExported:!0},KX={description:j(`Whether a value is text.`),args:[k(`value (any)`,j(`The value to be verified as text.`))],compute:function(e){return typeof e?.value==`string`&&F(e?.value)===!1},isExported:!0},qX={description:j(`Whether the referenced cell is empty`),args:[k(`value (any)`,j(`Reference to the cell that will be checked for emptiness.`))],compute:function(e){return e?.value===null},isExported:!0},JX={description:j(`Returns the error value #N/A.`),args:[],compute:function(){return{value:M.NotAvailable}},isExported:!0},YX={description:j(`Checks whether there is a reference to a cell that contains a formula, and returns TRUE or FALSE.`),args:[k(`cell_reference (any)`,j(`A reference to a cell.`))],compute:function(e){return e?.position===void 0?new Li(Ha):this.getters.getCell(e.position)?.isFormula??!1},isExported:!0};var XX=l({AND:()=>ZX,FALSE:()=>QX,IF:()=>$X,IFERROR:()=>eZ,IFNA:()=>tZ,IFS:()=>nZ,NOT:()=>rZ,OR:()=>iZ,SWITCH:()=>aZ,TRUE:()=>oZ,XOR:()=>sZ});let ZX={description:j("Logical `and` operator."),args:[k(`logical_expression (boolean, range<boolean>, repeating)`,j(`Expression or reference to a cell containing a logical value (TRUE/FALSE) or an expression that can be coerced to a logical value.`))],compute:function(...e){let{result:t,foundBoolean:n}=Jh(e);return n?t:new N(Eo)},isExported:!0},QX={description:j("Logical value `false`."),args:[],compute:function(){return!1},isExported:!0},$X={description:j(`Returns value depending on logical expression.`),args:[k(`logical_expression (boolean, range<boolean>)`,j(`An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.`)),k(`value_if_true (any, range)`,j(`The value the function returns if logical_expression is TRUE.`)),k(`value_if_false (any, range, default=FALSE)`,j(`The value the function returns if logical_expression is FALSE.`))],compute:function(e,t,n){return Sh(e)?fo($X.compute,[e,t,n]):(R(bh(e))?t:n)??{value:0}},isExported:!0},eZ={description:j(`Value if it is not an error, otherwise 2nd argument.`),args:[k(`value (any, range)`,j(`The value to return if value itself is not an error.`)),k(`value_if_error (any, range, default="empty")`,j(`The value the function returns if value is an error.`))],compute:function(e,t){return Sh(e)?fo(eZ.compute,[e,t]):(F(bh(e)?.value)?t:e)??{value:0}},isExported:!0},tZ={description:j(`Value if it is not an #N/A error, otherwise 2nd argument.`),args:[k(`value (any, range)`,j(`The value to return if value itself is not #N/A an error.`)),k(`value_if_error (any, range, default="empty")`,j(`The value the function returns if value is an #N/A error.`))],compute:function(e,t){return Sh(e)?fo(tZ.compute,[e,t]):(bh(e)?.value===M.NotAvailable?t:e)??{value:0}},isExported:!0},nZ={description:j(`Returns a value depending on multiple logical expressions.`),args:[k(`condition (any, range, repeating)`,j(`The condition to be evaluated. It can be a boolean, a number, an array, or a reference to any of those.`)),k(`value (any, range, repeating)`,j(`The value to be returned if its corresponding condition is TRUE.`))],compute:function(...e){if(e.length%2!=0)return new N(j(`Wrong number of arguments. Expected an even number of arguments.`));for(;e.length>0;){if(Sh(e[0]))return fo(nZ.compute,e);let t=R(bh(e.shift())),n=e.shift();if(t)return n??{value:0}}return new N(j(`No match.`))},isExported:!0},rZ={description:j(`Returns opposite of provided logical value.`),args:[k(`logical_expression (boolean)`,j(`An expression or reference to a cell holding an expression that represents some logical value.`))],compute:function(e){return!R(e)},isExported:!0},iZ={description:j("Logical `or` operator."),args:[k(`logical_expression (boolean, range<boolean>, repeating)`,j(`Expression or reference to a cell containing a logical value (TRUE/FALSE) or an expression that can be coerced to a logical value.`))],compute:function(...e){let{result:t,foundBoolean:n}=Yh(e);return n?t:new N(Eo)},isExported:!0},aZ={description:j(`Returns a value by comparing cases to an expression.`),args:[k(`expression (number, boolean, string)`,j(`The value to be checked.`)),k(`case (any, repeating)`,j(`Case to be checked against expression.`)),k(`value (any, repeating)`,j(`Value to be returned if its corresponding case matches expression.`)),k(`default (any, default="empty")`,j(`An optional default value to be returned if none of the cases match expression.`))],compute:function(e,...t){let n=t.length%2==0?Ba(e):t.pop();for(let n=0;n<t.length;n+=2){let r=t[n];if(r&&F(r.value))return r;if(e?.value===r?.value)return t[n+1]||{value:0}}return n||{value:0}},isExported:!0},oZ={description:j("Logical value `true`."),args:[],compute:function(){return!0},isExported:!0},sZ={description:j("Logical `xor` operator."),args:[k(`logical_expression (boolean, range<boolean>, repeating)`,j(`Expression or reference to a cell containing a logical value (TRUE/FALSE) or an expression that can be coerced to a logical value.`))],compute:function(...e){let t=!1,n=!1;return mo(e,e=>(t=!0,n=n?!e:e,!0)),t?n:new N(Eo)},isExported:!0};function cZ(e,t){let n=t.getPivotId(e);if(!n)throw new N(j(`There is no pivot with id "%s"`,e));return n}function lZ(e,t,n){let{measures:r}=n.getPivotCoreDefinition(e);if(!r.find(e=>e.id===t))throw new N(j(`The argument %s is not a valid measure. Here are the measures: %s`,t,`(${r.map(e=>e.id).join(`, `)})`))}function uZ(e){if(e.length%2!=0)throw new N(j(`Function PIVOT takes an even number of arguments.`))}function dZ(e,t,n){let r=[],i=e.getters.getPivotCoreDefinition(t);if(i.type===`SPREADSHEET`&&i.dataSet){let{sheetId:t,zone:n}=i.dataSet,a=wn(n),o=e.getters.getRangeFromSheetXC(t,a);if(o===void 0||o.invalidXc||o.invalidSheetName)throw new Li;if(e.__originCellPosition&&o.sheetId===e.__originSheetId&&In(D(e.__originCellPosition),n))throw new Ii;r.push(o)}for(let i of n)i.computedBy&&r.push(...e.getters.getMeasureFullDependencies(t,i));let a=e.__originCellPosition;a&&r.length&&(e.updateDependencies?.(a),e.addDependencies?.(a,r))}var fZ=l({ADDRESS:()=>hZ,CHOOSE:()=>MZ,COLUMN:()=>gZ,COLUMNS:()=>_Z,DROP:()=>NZ,FORMULATEXT:()=>FZ,HLOOKUP:()=>vZ,INDEX:()=>yZ,INDIRECT:()=>bZ,LOOKUP:()=>xZ,MATCH:()=>SZ,OFFSET:()=>jZ,PIVOT:()=>AZ,PIVOT_HEADER:()=>kZ,PIVOT_VALUE:()=>OZ,ROW:()=>CZ,ROWS:()=>wZ,TAKE:()=>PZ,VLOOKUP:()=>TZ,XLOOKUP:()=>DZ});let pZ=[{value:!0,label:j(`A1 style (default)`)},{value:!1,label:j(`R1C1 style`)}],mZ=[{value:!0,label:j(`Approximate match (default)`)},{value:!1,label:j(`Exact match`)}],hZ={description:j(`Returns a cell reference as a string. `),args:[k(`row (number)`,j(`The row number of the cell reference. `)),k(`column (number)`,j(`The column number (not name) of the cell reference. A is column number 1. `)),k(`absolute_relative_mode (number, default=1)`,j(`An indicator of whether the reference is row/column absolute.`),[{value:1,label:j(`Absolute row and column (e.g. $A$1)`)},{value:2,label:j(`Absolute row, relative column (e.g. A$1)`)},{value:3,label:j(`Relative row, absolute column (e.g. $A1)`)},{value:4,label:j(`Relative row and column (e.g. A1)`)}]),k(`use_a1_notation (boolean, default=TRUE)`,j(`A boolean indicating whether to use A1 style notation or R1C1 style notation.`),pZ),k(`sheet (string, optional)`,j(`A string indicating the name of the sheet into which the address points.`))],compute:function(e,t,n={value:1},r={value:!0},i){let a=Ya(e,this.locale),o=Ya(t,this.locale);if(a<1)return new N(hh(a));if(o<1)return new N(hh(o));let s=Ya(n,this.locale);if(![1,2,3,4].includes(s))return new N(Ua(1,4,s));let c=R(r),l;if(c){let e={rowFixed:[1,2].includes(s),colFixed:[1,3].includes(s)};l=E(o-1,a-1,e)}else l=([1,2].includes(s)?`R${a}`:`R[${a}]`)+([1,3].includes(s)?`C${o}`:`C[${o}]`);return i===void 0?l:Xo(L(i),l)},isExported:!0},gZ={description:j(`Column number of a specified cell.`),args:[k(`cell_reference (any, range<any>, default='this cell')`,j(`The cell whose column number will be returned. Column A corresponds to 1. By default, the function use the cell in which the formula is entered.`))],compute:function(e){if(e===void 0)return this.__originCellPosition===void 0?new N(j(`In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.`)):this.__originCellPosition.col+1;let t=B(e),n=t[0][0];if(n===void 0)return new N(j(`The range is out of bounds.`));if(n.position===void 0)return new Li(Ha);let r=n.position.col;return t.length===1?r+1:so(t.length,1,e=>({value:r+e+1}))},isExported:!0},_Z={description:j(`Number of columns in a specified array or range.`),args:[k(`range (any, range<any>)`,j(`The range whose column count will be returned.`))],compute:function(e){let t=B(e);return t[0][0]===void 0?new N(j(`The range is out of bounds.`)):t[0][0].value===M.InvalidReference?t[0][0]:t.length},isExported:!0},vZ={description:j(`Horizontal lookup`),args:[k(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),k(`range (any, range)`,j(`The range to consider for the search. The first row in the range is searched for the key specified in search_key.`)),k(`index (number)`,j(`The row index of the value to be returned, where the first row in range is numbered 1.`)),k(`is_sorted (boolean, default=true)`,j(`Indicates whether the row to be searched (the first row of the specified range) is sorted, in which case the closest match for search_key will be returned.`),mZ)],compute:function(e,t,n,r={value:!0}){let i=Math.trunc(I(n?.value,this.locale)),a=B(t);if(1>i||i>a[0].length)return new N(j(`[[FUNCTION_NAME]] evaluates to an out of bounds range.`));let o=(e,t)=>e[t][0].value,s=a[R(r.value)?yo(a,e,`nextSmaller`,`asc`,a.length,o):bo(a,e,`wildcard`,a.length,o,this.lookupCaches)];return s===void 0?Ba(e):s[i-1]},isExported:!0},yZ={description:j(`Returns the content of a cell, specified by row and column offset.`),args:[k(`reference (any, range)`,j(`The range of cells from which the values are returned.`)),k(`row (number, default=0)`,j(`The index of the row to be returned from within the reference range of cells.`)),k(`column (number, default=0)`,j(`The index of the column to be returned from within the reference range of cells.`))],compute:function(e,t={value:0},n={value:0}){let r=B(e),i=I(t.value,this.locale),a=I(n.value,this.locale);return a<0||a-1>=r.length||i<0||i-1>=r[0].length?new N(j(`Index out of range.`)):i===0&&a===0?r:i===0?[r[a-1]]:a===0?r.map(e=>[e[i-1]]):r[a-1][i-1]},isExported:!0},bZ={description:j(`Returns the content of a cell, specified by a string.`),args:[k(`reference (string)`,j(`The range of cells from which the values are returned.`)),k(`use_a1_notation (boolean, default=TRUE)`,j(`A boolean indicating whether to use A1 style notation (TRUE) or R1C1 style notation (FALSE).`),pZ)],compute:function(e,t={value:!0}){let n=e?.value?.toString();if(!n)return new Li(j(`Reference should be defined.`));if(!R(t))return new N(j(`R1C1 notation is not supported.`));let r=this.__originSheetId,i=this.__originCellPosition;i&&this.updateDependencies?.(i);let a=this.getters.getNamedRange(n),o=a?a.range:this.getters.getRangeFromSheetXC(r,n);if(o===void 0||o.invalidXc||o.invalidSheetName)return new Li;i&&this.addDependencies?.(i,[o]);let s=[];for(let e=o.zone.left;e<=o.zone.right;e++){let t=[];for(let n=o.zone.top;n<=o.zone.bottom;n++){let r={sheetId:o.sheetId,col:e,row:n};t.push(this.getFormulaResult(r))}s.push(t)}return s.length===1&&s[0].length===1?s[0][0]:s},isExported:!0},xZ={description:j(`Look up a value.`),args:[k(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),k(`search_array (any, range)`,j(`One method of using this function is to provide a single sorted row or column search_array to look through for the search_key with a second argument result_range. The other way is to combine these two arguments into one search_array where the first row or column is searched and a value is returned from the last row or column in the array. If search_key is not found, a non-exact match may be returned.`)),k(`result_range (any, range, optional)`,j(`The range from which to return a result. The value returned corresponds to the location where search_key is found in search_range. This range must be only a single row or column and should not be used if using the search_result_array method.`))],compute:function(e,t,n){let r=B(t),i=B(n),a=r.length,o=r[0].length,s=o>=a,c=yo(r,e,`nextSmaller`,`asc`,s?o:a,s?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value);return c===-1||s&&r[0][c]===void 0||!s&&r[c][o-1]===void 0?Ba(e):i[0].length===0?s?r[a-1][c]:r[c][o-1]:(a=i.length,o=i[0].length,a!==1&&o!==1?new N(j(`The result_range must be a single row or a single column.`)):a>1?c>a-1?new N(j(`[[FUNCTION_NAME]] evaluates to an out of range row value %s.`,c+1)):i[c][0]:c>o-1?new N(j(`[[FUNCTION_NAME]] evaluates to an out of range column value %s.`,c+1)):i[0][c])},isExported:!0},SZ={description:j(`Position of item in range that matches value.`),args:[k(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),k(`range (any, range)`,j(`The one-dimensional array to be searched.`)),k(`search_type (number, default=1)`,j(`The search method is a number 1, 0 or -1 indicating which value to return. 1 finds the largest value less than or equal to search_key when range is sorted in ascending order. 0 finds the exact value when range is unsorted. -1 finds the smallest value greater than or equal to search_key when range is sorted in descending order.`),[{value:1,label:j(`Ascending order (default)`)},{value:0,label:j(`Exact match`)},{value:-1,label:j(`Descending order`)}])],compute:function(e,t,n={value:1}){let r=I(n,this.locale),i=B(t),a=i.length,o=i[0].length;if(a!==1&&o!==1)return new N(j(`The range must be a single row or a single column.`));let s=-1,c=a===1?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,l=a===1?i[0].length:i.length;switch(r=Math.sign(r),r){case 1:s=yo(i,e,`nextSmaller`,`asc`,l,c);break;case 0:s=bo(i,e,`wildcard`,l,c,this.lookupCaches);break;case-1:s=yo(i,e,`nextGreater`,`desc`,l,c);break}return a===1&&i[0][s]===void 0||a!==1&&i[s]===void 0?Ba(e):s+1},isExported:!0},CZ={description:j(`Row number of a specified cell.`),args:[k(`cell_reference (any, range<any>, default='this cell')`,j(`The cell whose row number will be returned. By default, this function uses the cell in which the formula is entered.`))],compute:function(e){if(e===void 0)return this.__originCellPosition?.row===void 0?new N(j(`In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.`)):this.__originCellPosition.row+1;let t=B(e),n=t[0][0];if(n===void 0)return new N(j(`The range is out of bounds.`));if(n.position===void 0)return new Li(Ha);let r=n.position.row;return t[0].length===1?r+1:so(1,t[0].length,(e,t)=>({value:r+t+1}))},isExported:!0},wZ={description:j(`Number of rows in a specified array or range.`),args:[k(`range (any, range<any>)`,j(`The range whose row count will be returned.`))],compute:function(e){let t=B(e);return t[0][0]===void 0?new N(j(`The range is out of bounds.`)):t[0][0].value===M.InvalidReference?t[0][0]:t[0].length},isExported:!0},TZ={description:j(`Vertical lookup.`),args:[k(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),k(`range (any, range)`,j(`The range to consider for the search. The first column in the range is searched for the key specified in search_key.`)),k(`index (number)`,j(`The column index of the value to be returned, where the first column in range is numbered 1.`)),k(`is_sorted (boolean, default=true)`,j(`Indicates whether the column to be searched (the first column of the specified range) is sorted, in which case the closest match for search_key will be returned.`),mZ)],compute:function(e,t,n,r={value:!0}){let i=Math.trunc(I(n?.value,this.locale)),a=B(t);if(1>i||i>a.length)return new N(j(`[[FUNCTION_NAME]] evaluates to an out of bounds range.`));let o=(e,t)=>e[0][t].value,s=R(r.value)?yo(a,e,`nextSmaller`,`asc`,a[0].length,o):bo(a,e,`wildcard`,a[0].length,o,this.lookupCaches),c=a[i-1][s];return c===void 0?Ba(e):c},isExported:!0},EZ={0:`strict`,1:`nextGreater`,"-1":`nextSmaller`,2:`wildcard`},DZ={description:j(`Search a range for a match and return the corresponding item from a second range.`),args:[k(`search_key (string,number,boolean)`,j(`The value to search for.`)),k(`lookup_range (any, range)`,j(`The range to consider for the search. Should be a single column or a single row.`)),k(`return_range (any, range)`,j(`The range containing the return value. Should have the same dimensions as lookup_range.`)),k(`if_not_found (any, optional)`,j(`If a valid match is not found, return this value.`)),k(`match_mode (any, default=0)`,j(`Specifies how to match search_key with the items in lookup_range. `),[{value:0,label:j(`Exact match (default)`)},{value:-1,label:j(`Exact match or next smaller item`)},{value:1,label:j(`Exact match or next larger item`)},{value:2,label:j(`Wildcard character match`)}]),k(`search_mode (any, default=1)`,j(`Specifies the search mode to use. By default, a first to last search will be used.`),[{value:1,label:j(`Search first to last (default)`)},{value:-1,label:j(`Search last to first`)},{value:2,label:j(`Binary search (sorted ascending order)`)},{value:-2,label:j(`Binary search (sorted descending order)`)}])],compute:function(e,t,n,r,i={value:0},a={value:1}){let o=Math.trunc(I(i.value,this.locale)),s=Math.trunc(I(a.value,this.locale)),c=B(t),l=B(n);if(c.length!==1&&c[0].length!==1)return new N(j(`lookup_range should be either a single row or single column.`));if(![1,-1,2,-2].includes(s))return new N(j(`search_mode should be a value in [-1, 1, -2, 2].`));if(![-1,0,1,2].includes(o))return new N(j(`match_mode should be a value in [-1, 0, 1, 2].`));let u=c.length===1?`col`:`row`;if(o===2&&[-2,2].includes(s))return new N(j(`The search and match mode combination is not supported for XLOOKUP evaluation.`));if(u===`col`?l[0].length!==c[0].length:l.length!==c.length)return new N(j(`return_range should have the same dimensions as lookup_range.`));let d=u===`col`?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,f=u===`col`?c[0].length:c.length,p=EZ[o],m=s===-1,h=s===2||s===-2?yo(c,e,p,s===2?`asc`:`desc`,f,d):bo(c,e,p,f,d,this.lookupCaches,m);return h===-1?r===void 0?Ba(e):[[r]]:u===`col`?l.map(e=>[e[h]]):[l[h]]},isExported:!0},OZ={description:j(`Get the value from a pivot.`),args:[k(`pivot_id (number,string)`,j(`ID of the pivot.`)),k(`measure_name (string)`,j(`Name of the measure.`)),k(`domain_field_name (string,repeating,optional)`,j(`Field name.`)),k(`domain_value (number,string,boolean,repeating,optional)`,j(`Value.`))],compute:function(e,t,...n){let r=L(e),i=L(t),a=cZ(r,this.getters);lZ(a,i,this.getters),uZ(n);let o=this.getters.getPivot(a),s=this.getters.getPivotCoreDefinition(a);dZ(this,a,s.measures.filter(e=>e.id===i)),o.init({reload:o.needsReevaluation});let c=o.assertIsValid({throwOnError:!1});if(c)return c;if(!o.areDomainArgsFieldsValid(n)){let e=j(`Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.`,`=PIVOT(${r})`);return{value:M.GenericError,message:j(`Dimensions don't match the pivot definition`)+`. `+e}}let l=o.parseArgsToPivotDomain(n);return this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(a)?.trackValue(i,l),o.getPivotCellValueAndFormat(i,l)}},kZ={description:j(`Get the header of a pivot.`),args:[k(`pivot_id (number,string)`,j(`ID of the pivot.`)),k(`domain_field_name (string,repeating,optional)`,j(`Field name.`)),k(`domain_value (number,string,value,repeating,optional)`,j(`Value.`))],compute:function(e,...t){let n=L(e),r=cZ(n,this.getters);uZ(t);let i=this.getters.getPivot(r);dZ(this,r,[]),i.init({reload:i.needsReevaluation});let a=i.assertIsValid({throwOnError:!1});if(a)return a;if(!i.areDomainArgsFieldsValid(t)){let e=j(`Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.`,`=PIVOT(${n})`);return{value:M.GenericError,message:j(`Dimensions don't match the pivot definition`)+`. `+e}}let o=i.parseArgsToPivotDomain(t);this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(r)?.trackHeader(o);let s=o.at(-1);if(s?.field===`measure`)return i.getPivotMeasureValue(L(s.value),o);let{value:c,format:l}=i.getPivotHeaderValueAndFormat(o);return{value:c,format:!s||s.field===`measure`||s.value===`false`?void 0:l}}},AZ={description:j(`Get a pivot table.`),args:[k(`pivot_id (string)`,j(`ID of the pivot.`)),k(`row_count (number, optional)`,j(`number of rows`)),k(`include_total (boolean, default=TRUE)`,j(`Whether to include total/sub-totals or not.`)),k(`include_column_titles (boolean, default=TRUE)`,j(`Whether to include the column titles or not.`)),k(`column_count (number, optional)`,j(`number of columns`)),k(`include_measure_titles (boolean, default=TRUE)`,j(`Whether to include the measure titles row or not.`))],compute:function(e,t,n,r,i,a){let o=cZ(L(e),this.getters),s=this.getters.getPivot(o),c=this.getters.getPivotCoreDefinition(o),l=Ug(c,t,n,r,i,a,this.locale);if(l.numberOfRows<0)return new N(j(`The number of rows must be positive.`));if(l.numberOfColumns<0)return new N(j(`The number of columns must be positive.`));dZ(this,o,c.measures),s.init({reload:s.needsReevaluation});let u=s.assertIsValid({throwOnError:!1});if(u)return u;let d=s.getCollapsedTableStructure();if(d.numberOfCells>5e5)return new N(Uy(d.numberOfCells,this.locale));let f=d.getPivotCells(l),p=this.getters.getPivotName(o),{numberOfCols:m,numberOfRows:h}=d.getPivotTableDimensions(l);if(h===0)return[[{value:p}]];let g=[];for(let e of C(0,m)){g[e]=[];for(let t of C(0,h)){let n=f[e][t];switch(n.type){case`EMPTY`:g[e].push({value:``});break;case`HEADER`:let t=s.getPivotHeaderValueAndFormat(n.domain);g[e].push(Pg(n.domain,t));break;case`MEASURE_HEADER`:g[e].push(s.getPivotMeasureValue(n.measure,n.domain));break;case`VALUE`:g[e].push(s.getPivotCellValueAndFormat(n.measure,n.domain));break;case`ROW_GROUP_NAME`:let r=s.definition.rows.find(e=>e.nameWithGranularity===n.rowField)?.displayName;g[e].push({value:r||``});break}}}return(l.displayColumnHeaders||l.displayMeasuresRow)&&f[0][0].type===`EMPTY`&&(g[0][0]={value:p}),g}},jZ={description:j(`Returns a range reference shifted by a specified number of rows and columns from a starting cell reference.`),args:[k(`cell_reference (any, range<any>)`,j(`The starting point from which to count the offset rows and columns.`)),k(`offset_rows (number)`,j(`The number of rows to offset by.`)),k(`offset_columns (number)`,j(`The number of columns to offset by.`)),k(`height (number, default='height of cell_reference')`,j(`The number of rows of the range to return starting at the offset target.`)),k(`width (number, default='width of cell_reference')`,j(`The number of columns of the range to return starting at the offset target.`))],compute:function(e,t,n,r,i){if(e===void 0)return new Li(Ha);let a=B(e),o=a[0][0];if(o===void 0)return new N(j(`The range is out of bounds.`));if(o.position===void 0)return new Li(Ha);let s=a[0].length,c=a.length;if(r){let e=I(r,this.locale);if(e<1)return new N(j(`Height value is %(_height)s. It should be greater than or equal to 1.`,{_height:e}));s=e}if(i){let e=I(i,this.locale);if(e<1)return new N(j(`Width value is %(_width)s. It should be greater than or equal to 1.`,{_width:e}));c=e}let l=I(t,this.locale),u=I(n,this.locale),d=this.__originCellPosition;d&&this.updateDependencies?.(d);let f=o.position.col+u,p=o.position.row+l;if(f<0||p<0)return new Li(j(`OFFSET evaluates to an out of bounds range.`));let m={left:f,top:p,right:f+c-1,bottom:p+s-1},h=o.position.sheetId,g=this.getters.getRangeFromZone(h,m);return g.invalidXc||g.invalidSheetName?new Li:(d&&this.addDependencies?.(d,[g]),so(c,s,(e,t)=>this.getFormulaResult({sheetId:h,col:f+e,row:p+t})))}},MZ={description:j(`Returns an element from a list of choices based on index.`),args:[k(`index (number)`,j(`Which choice to return.`)),k(`choice (any, range<any>, repeating)`,j(`A potential value to return. May be a reference to a cell or an individual value.`))],compute:function(e,...t){let n=Math.floor(I(e,this.locale))-1;return n<0||n>=t.length?new N(j(`Index for CHOOSE is invalid. Valid values are between 1 and %(choices)s inclusive.`,{choices:t.length})):t[n]??new N(j(`Choice is undefined.`))},isExported:!0},NZ={description:j(`Excludes a specified number of rows or columns from the start or end of an array.`),args:[k(`array (range)`,j(`The array from which to drop rows or columns`)),k(`rows (number)`,j(`The number of rows to drop. A negative value drops from the end of the array.`)),k(`columns (number, optional)`,j(`The number of columns to exclude. A negative value drops from the end of the array.`))],compute:function(e,t,n){let r=I(t,this.locale),i=I(n,this.locale),a=e;if(Math.abs(i)>=e.length||Math.abs(r)>=e[0].length)return new N(j(`The number of rows or column to exclude must be smaller than the number of elements in the array.`));a=i>=0?a.slice(i):a.slice(0,a.length+i);for(let e=0;e<a.length;e++)r>=0?a[e]=a[e].slice(r):a[e]=a[e].slice(0,a[e].length+r);return a},isExported:!0},PZ={description:j(`Returns a specified number of contiguous rows or columns from the start or end of an array.`),args:[k(`array (range)`,j(`The array from which to take rows or columns.`)),k(`rows (number)`,j(`The number of rows to take. A negative value takes from the end of the array.`)),k(`columns (number, optional)`,j(`The number of columns to take. A negative value takes from the end of the array.`))],compute:function(e,t,n){let r=t?I(t,this.locale):e[0].length,i=I(n,this.locale),a=e;if((Math.abs(i)>=e.length||i===0)&&(i=e.length),Math.abs(r)>=e[0].length&&(r=e[0].length),a=i>=0?a.slice(0,i):a.slice(a.length+i,a.length),r===0)return new N(j(`The number of rows can not be zero.`));for(let e=0;e<a.length;e++)r>0?a[e]=a[e].slice(0,r):a[e]=a[e].slice(a[e].length+r,a[e].length);return a},isExported:!0},FZ={description:j(`Returns a formula as a string.`),args:[k(`cell_reference (any)`,j(`A reference to a cell.`))],compute:function(e){if(e?.position===void 0)return new Li(Ha);let t=this.getters.getCell(e.position);return t?.isFormula?t.compiledFormula.toFormulaString(this.getters):new Ri(j(`The cell does not contain a formula.`))},isExported:!0};var IZ=l({ADD:()=>LZ,CONCAT:()=>RZ,DIVIDE:()=>zZ,EQ:()=>UZ,GT:()=>GZ,GTE:()=>KZ,LT:()=>qZ,LTE:()=>JZ,MINUS:()=>YZ,MULTIPLY:()=>XZ,NE:()=>ZZ,POW:()=>QZ,SPILLED_RANGE:()=>$Z,UMINUS:()=>eQ,UNARY_PERCENT:()=>tQ,UPLUS:()=>nQ});let LZ={description:j(`Sum of two numbers.`),args:[k(`value1 (number)`,j(`The first addend.`)),k(`value2 (number)`,j(`The second addend.`))],compute:function(e,t){return{value:I(e,this.locale)+I(t,this.locale),format:e?.format||t?.format}}},RZ={description:j(`Concatenation of two values.`),args:[k(`value1 (string)`,j(`The value to which value2 will be appended.`)),k(`value2 (string)`,j(`The value to append to value1.`))],compute:function(e,t){return L(e)+L(t)},isExported:!0},zZ={description:j(`One number divided by another.`),args:[k(`dividend (number)`,j(`The number to be divided.`)),k(`divisor (number)`,j(`The number to divide by.`))],compute:function(e,t){let n=I(t,this.locale);return n===0?new Vi(j(`The divisor must be different from zero.`)):{value:I(e,this.locale)/n,format:e?.format||t?.format}}};function BZ(e){return e===void 0||e.value===null}let VZ={number:0,string:``,boolean:!1};function HZ(e,t,n=2e-16){return Math.abs(e-t)<n}let UZ={description:j(`Equal.`),args:[k(`value1 (string, number, boolean)`,j(`The first value.`)),k(`value2 (string, number, boolean)`,j(`The value to test against value1 for equality.`))],compute:function(e,t){if(F(e?.value))return e;if(F(t?.value))return t;let n=BZ(e)?VZ[typeof t?.value]:e?.value,r=BZ(t)?VZ[typeof e?.value]:t?.value;return typeof n==`string`&&(n=n.toUpperCase()),typeof r==`string`&&(r=r.toUpperCase()),typeof n==`number`&&typeof r==`number`?{value:HZ(n,r)}:{value:n===r}}};function WZ(e,t,n){if(F(e?.value))return e;if(F(t?.value))return t;let r=BZ(e)?VZ[typeof t?.value]:e?.value,i=BZ(t)?VZ[typeof e?.value]:t?.value;typeof r!=`number`&&(r=L(r).toUpperCase()),typeof i!=`number`&&(i=L(i).toUpperCase());let a=typeof r,o=typeof i;return a===`string`&&o===`number`?{value:!0}:o===`string`&&a===`number`?{value:!1}:{value:n(r,i)}}let GZ={description:j(`Strictly greater than.`),args:[k(`value1 (number, string, boolean)`,j(`The value to test as being greater than value2.`)),k(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){return WZ(e,t,(e,t)=>typeof e==`number`&&typeof t==`number`?!HZ(e,t)&&e>t:e>t)}},KZ={description:j(`Greater than or equal to.`),args:[k(`value1 (number, string, boolean)`,j(`The value to test as being greater than or equal to value2.`)),k(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){return WZ(e,t,(e,t)=>typeof e==`number`&&typeof t==`number`?HZ(e,t)||e>t:e>=t)}},qZ={description:j(`Less than.`),args:[k(`value1 (number, string, boolean)`,j(`The value to test as being less than value2.`)),k(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){let n=KZ.compute.bind(this)(e,t);return F(n.value)?n:{value:!n.value}}},JZ={description:j(`Less than or equal to.`),args:[k(`value1 (number, string, boolean)`,j(`The value to test as being less than or equal to value2.`)),k(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){let n=GZ.compute.bind(this)(e,t);return F(n.value)?n:{value:!n.value}}},YZ={description:j(`Difference of two numbers.`),args:[k(`value1 (number)`,j(`The minuend, or number to be subtracted from.`)),k(`value2 (number)`,j(`The subtrahend, or number to subtract from value1.`))],compute:function(e,t){return{value:I(e,this.locale)-I(t,this.locale),format:e?.format||t?.format}}},XZ={description:j(`Product of two numbers`),args:[k(`factor1 (number)`,j(`The first multiplicand.`)),k(`factor2 (number)`,j(`The second multiplicand.`))],compute:function(e,t){return{value:I(e,this.locale)*I(t,this.locale),format:e?.format||t?.format}}},ZZ={description:j(`Not equal.`),args:[k(`value1 (string, number, boolean)`,j(`The first value.`)),k(`value2 (string, number, boolean)`,j(`The value to test against value1 for inequality.`))],compute:function(e,t){let n=UZ.compute.bind(this)(e,t);return F(n.value)?n:{value:!n.value}}},QZ={description:j(`A number raised to a power.`),args:[k(`base (number)`,j(`The number to raise to the exponent power.`)),k(`exponent (number)`,j(`The exponent to raise base to.`))],compute:function(e,t){return LG.compute.bind(this)(e,t)}},$Z={description:j(`Gets the spilled range of an array formula.`),args:[k(`ref (any, range<any>)`,j(`The reference to get the spilled range from.`))],compute:function(e){if(e===void 0)return new Li(Ha);let t=B(e);if(t.length!==1||t[0].length!==1)return new N(j(`Only single-cell references are allowed to get the spilled range.`));let n=t[0][0];if(F(n.value))return n;if(n.position===void 0)return new Li(Ha);let r=this.__originCellPosition;r&&this.updateDependencies?.(r);let i=this.getters.getSpreadZone(n.position);if(i===void 0)return new Li;let a=this.getters.getRangeFromZone(this.__originSheetId,i);return r&&this.addDependencies?.(r,[a]),so(i.right-i.left+1,i.bottom-i.top+1,(e,t)=>this.getFormulaResult({sheetId:a.sheetId,col:i.left+e,row:i.top+t}))},hidden:!0},eQ={description:j(`A number with the sign reversed.`),args:[k(`value (number)`,j(`The number to have its sign reversed. Equivalently, the number to multiply by -1.`))],compute:function(e){return{value:-I(e,this.locale),format:e?.format}}},tQ={description:j(`Value interpreted as a percentage.`),args:[k(`percentage (number)`,j(`The value to interpret as a percentage.`))],compute:function(e){return I(e,this.locale)/100}},nQ={description:j(`A specified number, unchanged.`),args:[k(`value (any)`,j(`The number to return.`))],compute:function(e={value:null}){return e}},$=e=>({transform:t=>t*e,inverseTransform:t=>t/e}),rQ={transform:e=>e,inverseTransform:e=>e},iQ=1e-10,aQ=.0254,oQ=aQ/72,sQ=.3048,cQ=.9144,lQ=1609.34,uQ=1852,dQ=946073047258e4,fQ={g:{...rQ,category:`weight`},u:{...$(166053e-29),category:`weight`},grain:{...$(.0647989),category:`weight`},ozm:{...$(28.3495),category:`weight`},lbm:{...$(453.592),category:`weight`},stone:{...$(6350.29),category:`weight`},sg:{...$(14593.90294),category:`weight`},cwt:{...$(45359.237),category:`weight`},uk_cwt:{...$(50802.3),category:`weight`},ton:{...$(907184.74),category:`weight`},uk_ton:{...$(1016046.9),category:`weight`},m:{...rQ,category:`distance`},km:{...$(1e3),category:`distance`},ang:{...$(iQ),category:`distance`},Picapt:{...$(oQ),category:`distance`},pica:{...$(aQ/6),category:`distance`},in:{...$(aQ),category:`distance`},ft:{...$(sQ),category:`distance`},yd:{...$(cQ),category:`distance`},ell:{...$(1.143),category:`distance`},mi:{...$(lQ),category:`distance`},survey_mi:{...$(1609.34),category:`distance`},Nmi:{...$(uQ),category:`distance`},ly:{...$(dQ),category:`distance`},parsec:{...$(0x6da012f95c9fd0),category:`distance`},sec:{...rQ,category:`time`},min:{...$(60),category:`time`},hr:{...$(3600),category:`time`},day:{...$(86400),category:`time`},yr:{...$(31556952),category:`time`},Pa:{...rQ,category:`pressure`},bar:{...$(1e5),category:`pressure`},mmHg:{...$(133.322),category:`pressure`},Torr:{...$(133.322),category:`pressure`},psi:{...$(6894.76),category:`pressure`},atm:{...$(101325),category:`pressure`},N:{...rQ,category:`force`},dyn:{...$(1e-5),category:`force`},pond:{...$(.00980665),category:`force`},lbf:{...$(4.44822),category:`force`},J:{...rQ,category:`energy`},eV:{...$(160218e-24),category:`energy`},e:{...$(1e-7),category:`energy`},flb:{...$(1.3558179483),category:`energy`},c:{...$(4.184),category:`energy`},cal:{...$(4.1868),category:`energy`},BTU:{...$(1055.06),category:`energy`},Wh:{...$(3600),category:`energy`},HPh:{...$(2684520),category:`energy`},W:{...rQ,category:`power`},PS:{...$(735.499),category:`power`},HP:{...$(745.7),category:`power`},T:{...rQ,category:`magnetism`},ga:{...$(1e-4),category:`magnetism`},K:{...rQ,category:`temperature`},C:{transform:e=>e+273.15,inverseTransform:e=>e-273.15,category:`temperature`},F:{transform:e=>(e-32)*5/9+273.15,inverseTransform:e=>(e-273.15)*9/5+32,category:`temperature`},Rank:{...$(5/9),category:`temperature`},Reau:{transform:e=>e*1.25+273.15,inverseTransform:e=>(e-273.15)/1.25,category:`temperature`},"m^3":{...rQ,category:`volume`,order:3},"ang^3":{...$(iQ**3),category:`volume`,order:3},"Picapt^3":{...$(oQ**3),category:`volume`,order:3},tsp:{...$(492892e-11),category:`volume`},tspm:{...$(5e-6),category:`volume`},tbs:{...$(14786764825785619e-21),category:`volume`},"in^3":{...$(aQ**3),category:`volume`,order:3},oz:{...$(295735295625e-16),category:`volume`},cup:{...$(237e-6),category:`volume`},pt:{...$(.0004731765),category:`volume`},uk_pt:{...$(568261e-9),category:`volume`},qt:{...$(.0009463529),category:`volume`},l:{...$(.001),category:`volume`},uk_qt:{...$(.0011365225),category:`volume`},gal:{...$(.0037854118),category:`volume`},uk_gal:{...$(.00454609),category:`volume`},"ft^3":{...$(sQ**3),category:`volume`,order:3},bushel:{...$(.0352390704),category:`volume`},barrel:{...$(.158987295),category:`volume`},"yd^3":{...$(cQ**3),category:`volume`,order:3},MTON:{...$(1.13267386368),category:`volume`},GRT:{...$(2.83168),category:`volume`},"mi^3":{...$(lQ**3),category:`volume`,order:3},"Nmi^3":{...$(uQ**3),category:`volume`,order:3},"ly^3":{...$(dQ**3),category:`volume`,order:3},"m^2":{...rQ,category:`area`,order:2},"ang^2":{...$(iQ**2),category:`area`,order:2},"Picapt^2":{...$(oQ**2),category:`area`,order:2},"in^2":{...$(aQ**2),category:`area`,order:2},"ft^2":{...$(sQ**2),category:`area`,order:2},"yd^2":{...$(cQ**2),category:`area`,order:2},ar:{...$(100),category:`area`},Morgen:{...$(2500),category:`area`},uk_acre:{...$(4046.8564224),category:`area`},us_acre:{...$(4046.8726098743),category:`area`},ha:{...$(1e4),category:`area`},"mi^2":{...$(lQ**2),category:`area`,order:2},"Nmi^2":{...$(uQ**2),category:`area`,order:2},"ly^2":{...$(dQ**2),category:`area`,order:2},bit:{...rQ,category:`information`},byte:{...$(8),category:`information`},"m/s":{...rQ,category:`speed`},"m/hr":{...$(1/3600),category:`speed`},"km/hr":{...$(1/3.6),category:`speed`},mph:{...$(.44704),category:`speed`},kn:{...$(.5144444444),category:`speed`},admkn:{...$(.5147733333),category:`speed`}},pQ={shweight:`cwt`,lcwt:`uk_cwt`,hweight:`uk_cwt`,LTON:`uk_ton`,brton:`uk_ton`,pc:`parsec`,Pica:`Picapt`,d:`day`,mn:`min`,s:`sec`,p:`Pa`,at:`atm`,dy:`dyn`,ev:`eV`,hh:`HPh`,wh:`Wh`,btu:`BTU`,h:`HP`,cel:`C`,fah:`F`,kel:`K`,us_pt:`pt`,L:`l`,lt:`l`,ang3:`ang^3`,ft3:`ft^3`,in3:`in^3`,ly3:`ly^3`,m3:`m^3`,mi3:`mi^3`,yd3:`yd^3`,Nmi3:`Nmi^3`,Picapt3:`Picapt^3`,"Pica^3":`Picapt^3`,Pica3:`Picapt^3`,regton:`GRT`,ang2:`ang^2`,ft2:`ft^2`,in2:`in^2`,ly2:`ly^2`,m2:`m^2`,mi2:`mi^2`,Nmi2:`Nmi^2`,Picapt2:`Picapt^2`,"Pica^2":`Picapt^2`,Pica2:`Picapt^2`,yd2:`yd^2`,"m/h":`m/hr`,"m/sec":`m/s`},mQ={"":1,Y:1e24,Z:1e21,E:0xde0b6b3a7640000,P:0x38d7ea4c68000,T:0xe8d4a51000,G:1e9,M:1e6,k:1e3,h:100,da:10,e:10,d:.1,c:.01,m:.001,u:1e-6,n:1e-9,p:1e-12,f:1e-15,a:1e-18,z:1e-21,y:1e-21,Yi:2**80,Zi:2**70,Ei:2**60,Pi:2**50,Ti:2**40,Gi:2**30,Mi:2**20,ki:2**10},hQ={weight:j(`Weight`),distance:j(`Distance`),time:j(`Time`),pressure:j(`Pressure`),force:j(`Force`),energy:j(`Energy`),power:j(`Power`),magnetism:j(`Magnetism`),temperature:j(`Temperature`),volume:j(`Volume`),area:j(`Area`),information:j(`Information`),speed:j(`Speed`)},gQ=Object.entries(fQ).map(([e,t])=>({value:e,label:_Q(t.category)}));function _Q(e){return hQ[e]??``}function vQ(e){for(let[t,n]of Object.entries(mQ)){if(t&&!e.startsWith(t))continue;let r=e.slice(t.length),i=fQ[r];if(!i&&pQ[r]&&(i=fQ[pQ[r]]),i)return{...i,factor:i.order?n**+i.order:n}}}var yQ=l({CONVERT:()=>bQ});let bQ={description:j(`Converts a numeric value to a different unit of measure.`),args:[k(`value (number)`,j(`the numeric value in start_unit to convert to end_unit`)),k(`start_unit (string)`,j(`The starting unit, the unit currently assigned to value`),gQ),k(`end_unit (string)`,j(`The unit of measure into which to convert value`),gQ)],compute:function(e,t,n){let r=I(e,this.locale),i=L(t),a=L(n),o=vQ(i),s=vQ(a);return o?s?o.category===s.category?{value:s.inverseTransform(o.factor*o.transform(r))/s.factor,format:e?.format}:{value:M.GenericError,message:j(`Incompatible units of measure ('%s' vs '%s')`,_Q(o.category),_Q(s.category))}:{value:M.GenericError,message:j(`Invalid units of measure ('%s')`,a)}:{value:M.GenericError,message:j(`Invalid units of measure ('%s')`,i)}},isExported:!0};var xQ=l({CHAR:()=>TQ,CLEAN:()=>EQ,CONCATENATE:()=>DQ,EXACT:()=>OQ,FIND:()=>kQ,FORMAT_LARGE_NUMBER:()=>AQ,JOIN:()=>jQ,LEFT:()=>MQ,LEN:()=>NQ,LOWER:()=>PQ,MID:()=>FQ,PROPER:()=>IQ,REGEXEXTRACT:()=>RQ,REGEXREPLACE:()=>zQ,REGEXTEST:()=>LQ,REPLACE:()=>BQ,RIGHT:()=>VQ,SEARCH:()=>HQ,SPLIT:()=>UQ,SUBSTITUTE:()=>WQ,TEXT:()=>YQ,TEXTAFTER:()=>ZQ,TEXTBEFORE:()=>QQ,TEXTJOIN:()=>GQ,TEXTSPLIT:()=>KQ,TRIM:()=>qQ,UPPER:()=>JQ,VALUE:()=>XQ});let SQ=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,CQ=[{value:0,label:j(`Case-sensitive (default)`)},{value:1,label:j(`Case-insensitive`)}],wQ=[{value:0,label:j(`Don't match to end (default)`)},{value:1,label:j(`Match to end`)}],TQ={description:j(`Gets character associated with number.`),args:[k(`table_number (number)`,j(`The number of the character to look up from the current Unicode table in decimal format.`))],compute:function(e){let t=Math.trunc(I(e,this.locale));return t<1?new N(j(`The table_number (%s) is out of range.`,t)):String.fromCharCode(t)},isExported:!0},EQ={description:j(`Remove non-printable characters from a piece of text.`),args:[k(`text (string)`,j(`The text whose non-printable characters are to be removed.`))],compute:function(e){let t=L(e),n=``;for(let e of t)e&&e.charCodeAt(0)>31&&(n+=e);return n},isExported:!0},DQ={description:j(`Appends strings to one another.`),args:[k(`string (string, range<string>, repeating)`,j(`String to append in sequence.`))],compute:function(...e){return io(e,(e,t)=>e+L(t),``)},isExported:!0},OQ={description:j(`Tests whether two strings are identical.`),args:[k(`string1 (string)`,j(`The first string to compare.`)),k(`string2 (string)`,j(`The second string to compare.`))],compute:function(e,t){return L(e)===L(t)},isExported:!0},kQ={description:j(`First position of string found in text, case-sensitive.`),args:[k(`search_for (string)`,j(`The string to look for within text_to_search.`)),k(`text_to_search (string)`,j(`The text to search for the first occurrence of search_for.`)),k(`starting_at (number, default=1)`,j(`The character within text_to_search at which to start the search.`))],compute:function(e,t,n={value:1}){let r=L(e),i=L(t),a=I(n,this.locale);if(i===``)return new N(j(`The text_to_search must be non-empty.`));if(a<1)return new N(j(`The starting_at (%s) must be greater than or equal to 1.`,a));let o=i.indexOf(r,a-1);return o===-1?new N(j(`In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.`,r,i)):o+1},isExported:!0},AQ={description:j(`Apply a large number format`),args:[k(`value (number)`,j(`The number.`)),k(`unit (string, optional)`,j(`The formatting unit. Use 'k', 'm', or 'b' to force the unit`),[{value:`k`,label:j(`Thousand`)},{value:`m`,label:j(`Million`)},{value:`b`,label:j(`Billion`)}])],compute:function(e,t){return{value:I(e,this.locale),format:Xl(e,t,this.locale)}}},jQ={description:j(`Concatenates elements of arrays with delimiter.`),args:[k(`delimiter (string)`,j(`The character or string to place between each concatenated value.`)),k(`value_or_array (string, range<string>, repeating)`,j(`Value to be appended using delimiter.`))],compute:function(e,...t){let n=L(e);return io(t,(e,t)=>(e?e+n:``)+L(t),``)}},MQ={description:j(`Substring from beginning of specified string.`),args:[k(`text (string)`,j(`The string from which the left portion will be returned.`)),k(`number_of_characters (number, optional)`,j(`The number of characters to return from the left side of string.`))],compute:function(e,...t){let n=t.length?I(t[0],this.locale):1;return n<0?new N(j(`The number_of_characters (%s) must be positive or null.`,n)):L(e).substring(0,n)},isExported:!0},NQ={description:j(`Length of a string.`),args:[k(`text (string)`,j(`The string whose length will be returned.`))],compute:function(e){return L(e).length},isExported:!0},PQ={description:j(`Converts a specified string to lowercase.`),args:[k(`text (string)`,j(`The string to convert to lowercase.`))],compute:function(e){return L(e).toLowerCase()},isExported:!0},FQ={description:j(`A segment of a string.`),args:[k(`text (string)`,j(`The string to extract a segment from.`)),k(`starting_at (number)`,j(`The index from the left of string from which to begin extracting. The first character in string has the index 1.`)),k(`extract_length (number)`,j(`The length of the segment to extract.`))],compute:function(e,t,n){let r=L(e),i=I(t,this.locale),a=I(n,this.locale);return i<1?new N(j(`The starting_at argument (%s) must be positive greater than one.`,i.toString())):a<0?new N(j(`The extract_length argument (%s) must be positive or null.`,a)):r.slice(i-1,i+a-1)},isExported:!0},IQ={description:j(`Capitalizes each word in a specified string.`),args:[k(`text_to_capitalize (string)`,j(`The text which will be returned with the first letter of each word in uppercase and all other letters in lowercase.`))],compute:function(e){return L(e).replace(SQ,e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())},isExported:!0},LQ={description:j(`Checks whether a string matches the supplied regular expression.`),args:[k(`text (string)`,j(`The string to test.`)),k(`pattern (string)`,j(`The regular expression pattern to match against the text.`)),k(`case_sensitivity (number, default=0)`,j(`Whether the match is case-sensitive.`),[{value:0,label:j(`Case-sensitive`)},{value:1,label:j(`Case-insensitive`)}])],compute:function(e,t,n={value:0}){let r=L(e),i=L(t),a=I(n,this.locale);if(i===``)return!0;if(r===``)return!1;if(a!==0&&a!==1)return new N(j(`The case_sensitivity (%s) must be 0 or 1.`,a));let o=a===1?`gi`:`g`,s;try{s=new RegExp(i,o)}catch{return new N(j(`Invalid regular expression`))}return s.test(r)},isExported:!0},RQ={description:j(`Extract text from a string based on the supplied regular expression.`),args:[k(`text (string)`,j(`The string on which you want to extract text.`)),k(`pattern (string)`,j(`The regular expression pattern to match against the text.`)),k(`return_mode (number, default=0)`,j(`0 = first match, 1 = all matches as an array, 2 = capturing groups from the first match as an array.`),[{value:0,label:j(`First match`)},{value:1,label:j(`All matches`)},{value:2,label:j(`Capture groups of first match`)}]),k(`case_sensitivity (number, default=0)`,j(`Whether the match is case-sensitive.`),[{value:0,label:j(`Case-sensitive`)},{value:1,label:j(`Case-insensitive`)}])],compute:function(e,t,n={value:0},r={value:0}){let i=L(e),a=L(t),o=I(n,this.locale),s=I(r,this.locale);if(i===``||a===``)return{value:``};if(o<0||o>2)return new N(j(`The return_mode (%s) must be 0, 1 or 2.`,o));if(s!==0&&s!==1)return new N(j(`The case_sensitivity (%s) must be 0 or 1.`,s));let c=s===1?`gi`:`g`,l;try{l=new RegExp(a,c)}catch{return new N(j(`Invalid regular expression`))}let u=[...i.matchAll(l)];return u.length===0?{value:M.NotAvailable,message:j(`No matches found.`)}:o===0?u[0][0]:o===1?u.map(e=>[e[0]]):u[0].length<2?new N(j(`No capturing groups found.`)):u[0].slice(1).map(e=>[e])},isExported:!0},zQ={description:j(`Replace text in a string based on the supplied regular expression.`),args:[k(`text (string)`,j(`The string in which you want to replace text.`)),k(`pattern (string)`,j(`The regular expression pattern to match against the text.`)),k(`replacement (string)`,j(`The text to use as the replacement.`)),k(`occurrence (number, default=0)`,j(`0 = replace all matches. A negative number counts from the end.`)),k(`case_sensitivity (number, default=0)`,j(`Whether the match is case-sensitive.`),[{value:0,label:j(`Case-sensitive`)},{value:1,label:j(`Case-insensitive`)}])],compute:function(e,t,n,r={value:0},i={value:0}){let a=L(e),o=L(t),s=L(n),c=I(r,this.locale),l=I(i,this.locale);if(l!==0&&l!==1)return new N(j(`The case_sensitivity (%s) must be 0 or 1.`,l));let u=l===1?`gi`:`g`,d;try{d=new RegExp(o,u)}catch{return new N(j(`Invalid regular expression`))}if(c!==0){let e=[...a.matchAll(d)];if(e.length===0||Math.abs(c)>e.length)return a;let t=c>0?c-1:e.length+c,n=e[t][0].length,r=e[t].index;return a.substring(0,r)+s+a.substring(r+n)}return a.replace(d,s)},isExported:!0},BQ={description:j(`Replaces part of a text string with different text.`),args:[k(`text (string)`,j(`The text, a part of which will be replaced.`)),k(`position (number)`,j(`The position where the replacement will begin (starting from 1).`)),k(`length (number)`,j(`The number of characters in the text to be replaced.`)),k(`new_text (string)`,j(`The text which will be inserted into the original text.`))],compute:function(e,t,n,r){let i=I(t,this.locale);if(i<1)return new N(j(`The position (%s) must be greater than or equal to 1.`,i));let a=L(e),o=I(n,this.locale),s=L(r);return a.substring(0,i-1)+s+a.substring(i-1+o)},isExported:!0},VQ={description:j(`A substring from the end of a specified string.`),args:[k(`text (string)`,j(`The string from which the right portion will be returned.`)),k(`number_of_characters (number, optional)`,j(`The number of characters to return from the right side of string.`))],compute:function(e,...t){let n=t.length?I(t[0],this.locale):1;if(n<0)return new N(j(`The number_of_characters (%s) must be positive or null.`,n));let r=L(e),i=r.length;return r.substring(i-n,i)},isExported:!0},HQ={description:j(`First position of string found in text, ignoring case.`),args:[k(`search_for (string)`,j(`The string to look for within text_to_search.`)),k(`text_to_search (string)`,j(`The text to search for the first occurrence of search_for.`)),k(`starting_at (number, default=1)`,j(`The character within text_to_search at which to start the search.`))],compute:function(e,t,n={value:1}){let r=L(e).toLowerCase(),i=L(t).toLowerCase(),a=I(n,this.locale);if(i===``)return{value:M.GenericError,message:j(`The text_to_search must be non-empty.`)};if(a<1)return{value:M.GenericError,message:j(`The starting_at (%s) must be greater than or equal to 1.`,a)};let o=i.indexOf(r,a-1);return o===-1?{value:M.GenericError,message:j(`In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.`,r,i)}:{value:o+1}},isExported:!0},UQ={description:j(`Split text by specific character delimiter(s).`),args:[k(`text (string)`,j(`The text to divide.`)),k(`delimiter (string)`,j(`The character or characters to use to split text.`)),k(`split_by_each (boolean, default=true})`,j(`Whether or not to divide text around each character contained in delimiter.`)),k(`remove_empty_text (boolean, default=true)`,j(`Whether or not to remove empty text messages from the split results. The default behavior is to treat consecutive delimiters as one (if TRUE). If FALSE, empty cells values are added between consecutive delimiters.`))],compute:function(e,t,n={value:!0},r={value:!0}){let i=L(e),a=Ze(L(t)),o=R(n),s=R(r);if(a.length<=0)return new N(j(`The delimiter (%s) must be not be empty.`,a));let c=o?RegExp(`[${a}]`,`g`):new RegExp(a,`g`),l=i.split(c);return s&&(l=l.filter(e=>e!==``)),uo([l])},isExported:!1},WQ={description:j(`Replaces existing text with new text in a string.`),args:[k(`text_to_search (string)`,j(`The text within which to search and replace.`)),k(`search_for (string)`,j(`The string to search for within text_to_search.`)),k(`replace_with (string)`,j(`The string that will replace search_for.`)),k(`occurrence_number (number, optional)`,j(`The instance of search_for within text_to_search to replace with replace_with. By default, all occurrences of search_for are replaced; however, if occurrence_number is specified, only the indicated instance of search_for is replaced.`))],compute:function(e,t,n,r){let i=I(r,this.locale);if(i<0)return new N(j(`The occurrenceNumber (%s) must be positive or null.`,i));let a=L(e),o=L(t);if(o===``)return a;let s=L(n),c=new RegExp(Ze(o),`g`);if(i===0)return a.replace(c,s);let l=0;return a.replace(c,e=>++l===i?s:e)},isExported:!0},GQ={description:j(`Combines text from multiple strings and/or arrays.`),args:[k(`delimiter (string)`,j(`A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.`)),k(`ignore_empty (boolean)`,j(`A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.`),[{value:!0,label:j(`Ignore empty cells`)},{value:!1,label:j(`Include empty cells (default)`)}]),k(`texts (string, range<string>, repeating)`,j(`Text item to join.`))],compute:function(e,t={value:!0},...n){let r=L(e),i=R(t),a=0;return io(n,(e,t)=>i&&L(t)===``?e:(a++?e+r:``)+L(t),``)},isExported:!0},KQ={description:j(`Splits text into rows or columns using specified column and row delimiters.`),args:[k(`text (string)`,j(`The text to split.`)),k(`col_delimiter (string, range<string>)`,j(`Character or string to split columns by.`)),k(`row_delimiter (string, range<string>, optional)`,j(`Character or string to split rows by.`)),k(`ignore_empty (boolean, default=false)`,j(`Whether to ignore empty cells.`),[{value:!1,label:j(`Include empty cells (default)`)},{value:!0,label:j(`Ignore empty cells`)}]),k(`match_mode (number, default=0)`,j(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),CQ),k(`pad_with (string, default="${M.NotAvailable}")`,j(`The value to use for padding empty cells.`))],compute:function(e,t,n,r={value:!1},i={value:0},a=new Ri){let o=L(e);if(o.length<=0)return new N(j(`No text to split.`));if(t===void 0&&n===void 0)return new N(j(`At least one delimiter must be provided.`));let s=B(t).flat().map(e=>Ze(L(e))),c=B(n).flat().map(e=>Ze(L(e)));if(s.some(e=>e===``)||c.some(e=>e===``))return new N(j(`The delimiters cannot be empty values.`));let l=R(r),u=I(i,this.locale);if(![0,1].includes(u))return new N(j(`match_mode should be a value of 0 or 1.`));let d=[],f=u===1?`gi`:`g`,p=c.filter(e=>!s.includes(e)),m=p.length?o.split(new RegExp(p.join(`|`),f)):[o];l&&(m=m.filter(e=>e!==``));let h=new RegExp(s.join(`|`),f);for(let e of m){let t=s.length?e.split(h):[e];l&&(t=t.filter(e=>e!==``)),d.push(t.map(e=>({value:e})))}let g=Math.max(...d.map(e=>e.length));for(let e of d)for(;e.length<g;)e.push(a);return uo(d)},isExported:!0},qQ={description:j(`Removes space characters.`),args:[k(`text (string)`,j(`The text or reference to a cell containing text to be trimmed.`))],compute:function(e){return Rt(L(e))},isExported:!0},JQ={description:j(`Converts a specified string to uppercase.`),args:[k(`text (string)`,j(`The string to convert to uppercase.`))],compute:function(e){return L(e).toUpperCase()},isExported:!0},YQ={description:j(`Converts a number to text according to a specified format.`),args:[k(`number (number)`,j(`The number, date or time to format.`)),k(`format (string)`,j(`The case-sensitive format of the result, enclosed in quotation marks. Examples: "0.00" rounded to 2 decimal places, "hh:mm:ss" for hour:minutes:seconds.`))],compute:function(e,t){return H(I(e,this.locale),{format:L(t),locale:this.locale})},isExported:!0},XQ={description:j(`Converts a string to a numeric value.`),args:[k(`value (number)`,j(`the string to be converted`))],compute:function(e){return I(e,this.locale)},isExported:!0},ZQ={description:j(`Returns text that occurs after a given substring or delimiter.`),args:[k(`text (string)`,j(`The source text.`)),k(`delimiter (string)`,j(`The substring after which text will be returned.`)),k(`instance_num (number, default=1)`,j(`The desired instance of the delimiter after which we extract the text. A negative number searches from the end.`)),k(`match_mode (number, default=0)`,j(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),CQ),k(`match_end (number, default=0))`,j(`Whether to treat the end of text as a delimiter.`),wQ),k(`if_not_found (string, default="${M.NotAvailable}")`,j(`Value to return if the delimiter is not found.`))],compute:function(e,t,n={value:1},r={value:0},i={value:0},a=new Ri){let o=L(e),s=I(n,this.locale),c=I(r,this.locale),l=I(i,this.locale);if(s===0)return new N(j(`The instance_num (%s) must not be zero.`,s));if(c!==0&&c!==1)return new N(j(`match_mode should have a value of 0 or 1.`));if(l!==0&&l!==1)return new N(j(`match_end should have a value of 0 or 1.`));let u=L(t);if(u===``)return Math.sign(s)>0?{value:o}:{value:``};let d=c===1?`gi`:`g`,f=Ze(u),p=new RegExp(f,d),m=[...o.matchAll(p)].map(e=>e.index+f.length);if(s<0&&(m=m.reverse()),l&&Math.abs(s)===m.length+1)return Math.sign(s)>0?{value:``}:{value:o};let h=m[Math.abs(s)-1];return h===void 0?a:{value:o.substring(h)}},isExported:!0},QQ={description:j(`Returns text that occurs before a given substring or delimiter.`),args:[k(`text (string)`,j(`The source text.`)),k(`delimiter (string)`,j(`The substring after which text will be returned.`)),k(`instance_num (number, default=1)`,j(`The desired instance of the delimiter before which we extract the text. A negative number searches from the end.`)),k(`match_mode (number, default=0)`,j(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),CQ),k(`match_end (number, default=0))`,j(`Whether to match a delimiter against the end of the text.`),wQ),k(`if_not_found (string, default="${M.NotAvailable}")`,j(`Value to return if the delimiter is not found.`))],compute:function(e,t,n={value:1},r={value:0},i={value:0},a=new Ri){let o=L(e),s=I(n,this.locale),c=I(r,this.locale),l=I(i,this.locale);if(s===0)return new N(j(`The instance_num (%s) must not be zero.`,s));if(c!==0&&c!==1)return new N(j(`match_mode should have a value of 0 or 1.`));if(l!==0&&l!==1)return new N(j(`match_end should have a value of 0 or 1.`));let u=L(t);if(u===``)return Math.sign(s)>0?{value:``}:{value:o};let d=c===1?`gi`:`g`,f=Ze(u),p=new RegExp(f,d),m=[...o.matchAll(p)].map(e=>e.index+f.length);if(s<0&&(m=m.reverse()),l&&Math.abs(s)===m.length+1)return Math.sign(s)>0?{value:o}:{value:``};let h=m[Math.abs(s)-1];return h===void 0?a:{value:o.substring(0,h-u.length)}},isExported:!0};var $Q=l({HYPERLINK:()=>e$});let e$={description:j(`Creates a hyperlink in a cell.`),args:[k(`url (string)`,j(`The full URL of the link enclosed in quotation marks.`)),k(`link_label (string, optional)`,j(`The text to display in the cell, enclosed in quotation marks.`))],compute:function(e,t){let n=L(e).trim(),r=L(t)||n;return n===``?r:ut(r,n)},isExported:!0},t$=[{name:j(`Array`),functions:_W},{name:j(`Database`),functions:Sq},{name:j(`Date`),functions:RJ},{name:j(`Filter`),functions:SY},{name:j(`Financial`),functions:OY},{name:j(`Info`),functions:LX},{name:j(`Lookup`),functions:fZ},{name:j(`Logical`),functions:XX},{name:j(`Math`),functions:qW},{name:j(`Operator`),functions:IZ},{name:j(`Statistical`),functions:lK},{name:j(`Text`),functions:xQ},{name:j(`Engineering`),functions:bY},{name:j(`Web`),functions:$Q},{name:j(`Parser`),functions:yQ}];for(let e of t$){let t=e.functions;for(let n in t){let r=t[n];r.category=r.category||e.name,n=n.replace(/_/g,`.`),Fo.add(n,{isExported:!1,...r})}}let n$={},r$={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:26,HEADER_WIDTH:48,DESKTOP_BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:96,DEFAULT_CELL_HEIGHT:23,SCROLLBAR_WIDTH:15},i$={autoCompleteProviders:oT,autofillModifiersRegistry:JL,autofillRulesRegistry:YL,cellMenuRegistry:kP,colMenuRegistry:HP,errorTypes:Pi,functionRegistry:Fo,featurePluginRegistry:Bz,iconsOnCellRegistry:CL,statefulUIPluginRegistry:Vz,coreViewsPluginRegistry:Hz,corePluginRegistry:zz,rowMenuRegistry:YP,sidePanelRegistry:ZM,figureRegistry:Ay,chartSidePanelComponentRegistry:rk,chartDataSourceSidePanelComponentRegistry:JD,chartComponentRegistry:sy,chartTypeRegistry:sS,chartSubtypeRegistry:Hv,chartDataSourceRegistry:oS,topbarMenuRegistry:AB,topbarComponentRegistry:XB,clickableCellRegistry:Yz,otRegistry:vR,inverseCommandRegistry:Qz,urlRegistry:Au,cellPopoverRegistry:_w,numberFormatMenuRegistry:gB,repeatLocalCommandTransformRegistry:uz,repeatCommandTransformRegistry:lz,clipboardHandlersRegistries:zF,pivotRegistry:Uj,pivotTimeAdapterRegistry:$h,pivotSidePanelRegistry:iM,pivotNormalizationValueRegistry:jg,supportedPivotPositionalFormulaRegistry:_I,pivotToFunctionValueRegistry:Mg,migrationStepRegistry:UC,chartJsExtensionRegistry:zd},a$={arg:k,isEvaluationError:F,toBoolean:R,toJsDate:z,toNumber:I,toString:L,toNormalizedPivotValue:Dg,toFunctionPivotValue:kg,toXC:E,toZone:yn,toUnboundedZone:vn,toCartesian:sn,numberToLetters:Zt,lettersToNumber:Qt,UuidGenerator:Rd,formatValue:H,createCurrencyFormat:Ul,ColorGenerator:ui,computeTextWidth:bd,createEmptyWorkbookData:lw,createEmptySheet:cw,createEmptyExcelSheet:uw,rgbaToHex:Br,colorToRGBA:Vr,positionToZone:D,isDefined:w,isMatrix:Je,lazy:xt,genericRepeat:YB,createAction:h,createActions:p,transformRangeData:cr,deepEquals:T,overlap:Nn,union:kn,isInside:Fn,deepCopy:x,expandZoneOnInsertion:Tn,reduceZoneOnDeletion:On,unquote:et,getMaxObjectId:yg,getFirstPivotFunction:Jj,getNumberOfPivotFunctions:Xj,parseDimension:Sg,isDateOrDatetimeField:Cg,makeFieldProposal:Zj,periodYearToComparable:Qh,insertTokenAfterArgSeparator:$j,insertTokenAfterLeftParenthesis:eM,mergeContiguousZones:ar,getPivotHighlights:XA,pivotTimeAdapter:eg,UNDO_REDO_PIVOT_COMMANDS:BL,createPivotFormula:Eg,areDomainArgsFieldsValid:Tg,splitReference:Yo,sanitizeSheetName:nt,getUniqueText:Kt,isNumber:Pa,isDateTime:na,createCustomFields:Rg,schemeToColorScale:Bh,isDateTimeFormat:Il,jsDateToNumber:ga,numberToJsDate:ma,DateTime:P,parseFormat:ol,isFormula:qt,domainToColRowDomain:mj,collapseHierarchicalDisplayName:Wg,PositionMap:tN},o$={isMarkdownLink:ct,parseMarkdownLink:dt,markdownLink:ut,openLink:Fu,urlRepresentation:Pu},s$={Checkbox:IT,Section:Z,Select:Ty,RoundColorPicker:ST,ChartDataSeries:XD,ChartErrorSection:eO,ChartLabelRange:ZD,ChartRangeDataSourceComponent:vO,ChartTitle:oO,ChartPanel:sk,ChartFigure:Oy,ChartJsComponent:Gp,ClickableCellSortIcon:vI,ZoomableChartJsComponent:$v,Grid:gI,GridOverlay:GF,ScorecardChart:Rm,GaugeChartComponent:ay,LineConfigPanel:HO,BarConfigPanel:nO,PieChartDesignPanel:GO,GenericChartConfigPanel:tO,ChartWithAxisDesignPanel:hO,GenericZoomableChartDesignPanel:gO,LineChartDesignPanel:UO,GaugeChartConfigPanel:IO,GaugeChartDesignPanel:LO,ScorecardChartConfigPanel:JO,ScorecardChartDesignPanel:YO,GeoChartDesignPanel:BO,RadarChartDesignPanel:KO,WaterfallChartDesignPanel:nk,ComboChartDesignPanel:NO,FunnelChartDesignPanel:FO,SunburstChartDesignPanel:XO,TreeMapChartDesignPanel:tk,ChartTypePicker:ak,FigureComponent:jy,MenuPopover:wy,Popover:by,SelectionInput:jT,ValidationMessages:$D,AddDimensionButton:tj,PivotDimensionGranularity:rj,PivotDimensionOrder:ij,PivotDimension:nj,PivotLayoutConfigurator:cj,PivotHTMLRenderer:bI,PivotDeferUpdate:QA,PivotTitleSection:lj,CogWheelMenu:KD,TextInput:BD,SidePanelCollapsible:ww,RadioSelection:cO,GeoChartRegionSelectSection:RO,ChartDashboardMenu:Ey,FullScreenFigure:yI,NumberInput:rO,TopBar:HV,Composer:Jw},c$={useDragAndDropListItems:wT,useHighlights:dk,useHighlightsOnHover:uk},l$={useStoreProvider:mr,DependencyContainer:ur,CellPopoverStore:vw,ComposerFocusStore:Er,CellComposerStore:TF,FindAndReplaceStore:jk,HighlightStore:cT,DelayedHoveredCellStore:My,HoveredTableStore:HF,ModelStore:yr,NotificationStore:lT,RendererStore:Cr,SelectionInputStore:AT,SpreadsheetStore:wr,useStore:O,useLocalStore:hr,SidePanelStore:$M,PivotSidePanelStore:nM,PivotMeasureDisplayPanelStore:JA,ClientFocusStore:ZP,GridRenderer:$F};function u$(e,t){return Fo.add(e,t),{addFunction:(e,t)=>u$(e,t)}}let d$={DEFAULT_LOCALE:V,HIGHLIGHT_COLOR:ee,PIVOT_STATIC_TABLE_CONFIG:Be,PIVOT_INSERT_TABLE_STYLE_ID:Ve,ChartTerms:Py,FIGURE_ID_SPLITTER:`??`,GRID_ICON_EDGE_LENGTH:17,GRID_ICON_MARGIN:2,CHART_TYPES:zh},f$={...jv,...gv};e.AbstractCellClipboardHandler=WL,e.AbstractChart=Kp,e.AbstractFigureClipboardHandler=sW,e.CellErrorType=M,e.ClientDisconnectedError=ez,e.CommandResult=Ou,e.CompiledFormula=Rc,e.CorePlugin=SI,e.CoreViewPlugin=XI,e.DEFAULT_LOCALE=V,e.DEFAULT_LOCALES=Io,e.DispatchResult=Eu,e.EvaluationError=N,e.LocalTransportService=ZB,e.Model=JU,e.PivotRuntimeDefinition=uj,e.Registry=A,e.Revision=$R,e.SPREADSHEET_DIMENSIONS=r$,e.Spreadsheet=GV,e.SpreadsheetPivotTable=jj,e.UIPlugin=KL,e.__info__=n$,e.addFunction=u$,e.addRenderingLayer=Sr,e.astToFormula=xF,e.canExecuteInReadonly=Tu,e.categories=t$,e.chartHelpers=f$,e.components=s$,e.constants=d$,e.convertAstNodes=Ws,e.coreTypes=Cu,e.createAutocompleteArgumentsProvider=Uz,e.findCellInNewZone=Kn,e.functionCache=Ic,e.getCaretDownSvg=xb,e.getCaretUpSvg=Sb,e.helpers=a$,e.hooks=c$,e.invalidateCFEvaluationCommands=vu,e.invalidateChartEvaluationCommands=gu,e.invalidateDependenciesCommands=_u,e.invalidateEvaluationCommands=hu,e.isCoreCommand=wu,e.isSheetDependent=lu,e.iterateAstNodes=Gs,e.links=o$,e.load=JC,e.lockedSheetAllowedCommands=Su,e.parse=Hs,e.parseTokens=Us,e.readonlyAllowedCommands=xu,e.registries=i$,e.setDefaultSheetViewSize=Re,e.setTranslationMethod=ji,e.stores=l$,e.tokenColors=Ke,e.tokenize=ss,n$.version=`19.3.12`,n$.date=`2026-07-20T11:02:44.416Z`,n$.hash=`2b42707`})(this.o_spreadsheet=this.o_spreadsheet||{},owl);
956
+ `),`_rels/.rels`)}function KU(e){let t={},n=[];for(let r of e.sheets){let e=r.name.slice(0,31);e=Kt(e,n,{compute:(e,t)=>e.slice(0,31-String(t).length)+t}),n.push(e),e!==r.name&&(t[r.name]=e,r.name=e)}if(!Object.keys(t).length)return e;let r=Object.keys(t).sort((e,t)=>t.length-e.length),i=JSON.stringify(e);for(let e of r){let n=RegExp(`'?${Ze(e)}'?!`,`g`);i=i.replaceAll(n,n=>{let r=t[e];return n.replace(e,r)})}return JSON.parse(i)}function qU(e){for(let t of e.sheets)t.tables=t.tables.filter(e=>Ln(yn(e.range)).numberOfRows>1);return e}var JU=class e extends lr{corePlugins=[];statefulUIPlugins=[];range;session;isReplayingCommand=!1;renderers={};status=0;config;corePluginConfig;coreViewPluginConfig;uiPluginConfig;state;selection;getters;coreGetters;uuidGenerator;handlers=[];uiHandlers=[];coreHandlers=[];constructor(e={},t={},n=[],r=new Rd,i=!1){let a=performance.now();console.debug(`##### Model creation #####`),super(),Mi(),n=nw(e,n);let o=JC(e,i);this.state=new sH,this.uuidGenerator=r,this.config=this.setupConfig(t),this.getters={isReadonly:()=>this.config.mode===`readonly`||this.config.mode===`dashboard`,isDashboard:()=>this.config.mode===`dashboard`},this.session=this.setupSession(o.revisionId),this.coreGetters={},this.range=new iH(this.coreGetters),this.coreGetters.getRangeString=this.range.getRangeString.bind(this.range),this.coreGetters.getRangeFromSheetXC=this.range.getRangeFromSheetXC.bind(this.range),this.coreGetters.createAdaptedRanges=this.range.createAdaptedRanges.bind(this.range),this.coreGetters.getRangeData=this.range.getRangeData.bind(this.range),this.coreGetters.getRangeDataFromXc=this.range.getRangeDataFromXc.bind(this.range),this.coreGetters.getRangeDataFromZone=this.range.getRangeDataFromZone.bind(this.range),this.coreGetters.getRangeFromRangeData=this.range.getRangeFromRangeData.bind(this.range),this.coreGetters.getRangeFromZone=this.range.getRangeFromZone.bind(this.range),this.coreGetters.recomputeRanges=this.range.recomputeRanges.bind(this.range),this.coreGetters.isRangeValid=this.range.isRangeValid.bind(this.range),this.coreGetters.extendRange=this.range.extendRange.bind(this.range),this.coreGetters.getRangesUnion=this.range.getRangesUnion.bind(this.range),this.coreGetters.removeRangesSheetPrefix=this.range.removeRangesSheetPrefix.bind(this.range),this.coreGetters.copyFormulaStringForSheet=this.range.copyFormulaStringForSheet.bind(this.range),this.selection=new oH(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 zz.getAll())this.setupCorePlugin(e,o);Object.assign(this.getters,this.coreGetters),this.session.loadInitialMessages(n);for(let e of Hz.getAll()){let t=this.setupCoreViewPlugin(e);this.handlers.push(t),this.uiHandlers.push(t),this.coreHandlers.push(t)}for(let e of Vz.getAll()){let t=this.setupUiPlugin(e);this.statefulUIPlugins.push(t),this.handlers.push(t),this.uiHandlers.push(t)}for(let e of Bz.getAll()){let t=this.setupUiPlugin(e);this.handlers.push(t),this.uiHandlers.push(t)}if(this.config.mode!==`export_verification`&&(this.dispatch(`START`),this.selection.observe(this,{handleEvent:()=>this.trigger(`update`)}),this.setupSessionEvents(),this.joinSession(),t.snapshotRequested||e[`[Content_Types].xml`]&&!this.getters.isReadonly())){let e=performance.now();console.debug(`Snapshot requested`),this.session.snapshot(this.exportData()),console.debug(`Snapshot taken in`,performance.now()-e,`ms`)}console.debug(`Model created in`,performance.now()-a,`ms`),console.debug(`######`)}joinSession(){this.session.join(this.config.client)}async leaveSession(){let e=this.getters.isReadonly()?void 0:xt(()=>this.exportData());await this.session.leave(e)}setupUiPlugin(e){let t=new e(this.uiPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}for(let n of e.layers)this.renderers[n]||(this.renderers[n]=[]),this.renderers[n].push(t);return t}setupCoreViewPlugin(e){let t=new e(this.coreViewPluginConfig);for(let n of e.getters){if(!(n in t))throw Error(`Invalid getter name: ${n} for plugin ${t.constructor}`);if(n in this.getters)throw Error(`Getter "${n}" is already defined.`);this.getters[n]=t[n].bind(t)}return t}setupCorePlugin(e,t){let n=new e(this.corePluginConfig);for(let t of e.getters){if(!(t in n))throw Error(`Invalid getter name: ${t} for plugin ${n.constructor}`);if(t in this.coreGetters)throw Error(`Getter "${t}" is already defined.`);this.coreGetters[t]=n[t].bind(n)}n.import(t),this.corePlugins.push(n),this.coreHandlers.push(n),this.handlers.push(n)}onRemoteRevisionReceived({commands:e}){for(let t of e){let e=this.status;this.status=2,this.dispatchToHandlers(this.statefulUIPlugins,t),this.status=e}this.finalize()}setupSession(e){return new tz(tH({initialRevisionId:e,recordChanges:this.state.recordChanges.bind(this.state),dispatch:e=>{if(!this.checkDispatchAllowedRemoteCommand(e).isSuccessful){this.dispatchToHandlers(this.coreHandlers,{type:`UNDO`,commands:[e]});return}this.isReplayingCommand=!0,this.dispatchToHandlers(this.coreHandlers,e),this.isReplayingCommand=!1}}),this.config.transportService,e,new KV(this.getters))}setupSessionEvents(){this.session.on(`remote-revision-received`,this,this.onRemoteRevisionReceived),this.session.on(`revision-undone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`UNDO`,{commands:e}),this.finalize()}),this.session.on(`revision-redone`,this,({commands:e})=>{this.dispatchFromCorePlugin(`REDO`,{commands:e}),this.finalize()}),this.session.on(`unexpected-revision-id`,this,()=>this.trigger(`unexpected-revision-id`)),this.session.on(`collaborative-event-received`,this,()=>{this.trigger(`update`)})}setupConfig(e){let t=e.client||{id:this.uuidGenerator.smallUuid(),name:j(`Anonymous`).toString()},n=e.transportService||new ZB,r=e.mode===`readonly`||e.mode===`dashboard`||e.mode===`export_verification`;return{...e,mode:e.mode||`normal`,custom:e.custom||{},external:this.setupExternalConfig(e.external||{}),transportService:r?new qV(n):n,client:t,moveClient:()=>{},snapshotRequested:!1,notifyUI:e=>this.trigger(`notify-ui`,e),raiseBlockingErrorUI:e=>this.trigger(`raise-error-ui`,{text:e}),customColors:e.customColors||[]}}setupExternalConfig(e){let t=e.loadLocales||(()=>Promise.resolve(Io));return{...e,loadLocales:t}}setupCorePluginConfig(){return{getters:this.coreGetters,stateObserver:this.state,range:this.range,dispatch:this.dispatchFromCorePlugin,canDispatch:this.canDispatch,custom:this.config.custom,external:this.config.external}}setupCoreViewPluginConfig(){return{getters:this.getters,stateObserver:this.state,custom:this.config.custom,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}setupUiPluginConfig(){return{getters:this.getters,stateObserver:this.state,dispatch:this.dispatch,canDispatch:this.canDispatch,selection:this.selection,moveClient:this.session.move.bind(this.session),custom:this.config.custom,uiActions:this.config,session:this.session,defaultCurrency:this.config.defaultCurrency,customColors:this.config.customColors||[],external:this.config.external}}checkDispatchAllowed(e){let t=wu(e)?this.checkDispatchAllowedCoreCommand(e):this.checkDispatchAllowedLocalCommand(e);return this.processCommandResults(t)}processCommandResults(e){return e.some(e=>e!==`Success`)?new Eu(e.flat()):Eu.Success}checkDispatchAllowedRemoteCommand(e){let t=this.coreHandlers.map(t=>t.allowDispatch(e));return this.processCommandResults(t)}checkDispatchAllowedCoreCommand(e){return this.handlers.map(t=>t.allowDispatch(e))}checkDispatchAllowedLocalCommand(e){return this.uiHandlers.map(t=>t.allowDispatch(e))}finalize(){this.status=3;for(let e of this.handlers)e.finalize();this.status=0,this.trigger(`command-finalized`)}canDispatch=(e,t)=>this.checkDispatchAllowed(YU(e,t));dispatch=(e,t)=>{let n=YU(e,t),r=this.status;if(this.getters.isReadonly()&&!Tu(n))return new Eu(`Readonly`);if(!this.session.canApplyOptimisticUpdate())return new Eu(`WaitingSessionConfirmation`);switch(r){case 0:let t=this.checkDispatchAllowed(n);if(!t.isSuccessful)return this.trigger(`update`),this.trigger(`command-rejected`,{command:n,result:t}),t;this.status=1;let{changes:r,commands:i}=this.state.recordChanges(()=>{let t=performance.now();wu(n)&&this.state.addCommand(n),this.dispatchToHandlers(this.handlers,n),this.finalize();let r=performance.now()-t;r>5&&console.debug(e,r,`ms`)});this.session.save(n,i,r),this.status=0,this.trigger(`update`);break;case 1:if(wu(n)){let e=this.checkDispatchAllowed(n);if(!e.isSuccessful)return e;this.state.addCommand(n)}this.dispatchToHandlers(this.handlers,n);break;case 3:throw Error(`Cannot dispatch commands in the finalize state`);case 2:if(wu(n))throw Error(`A UI plugin cannot dispatch ${e} while handling a core command`);this.dispatchToHandlers(this.handlers,n)}return Eu.Success};dispatchFromCorePlugin=(e,t)=>{let n=YU(e,t),r=this.status;this.status=2;let i=this.isReplayingCommand?this.coreHandlers:this.handlers;return this.dispatchToHandlers(i,n),this.status=r,Eu.Success};dispatchToHandlers(e,t){let n=wu(t);for(let r of e)!n&&r instanceof SI||r.beforeHandle(t);for(let r of e)!n&&r instanceof SI||r.handle(t);this.trigger(`command-dispatched`,t)}drawLayer(e,t){let n=this.renderers[t];if(n)for(let r of n)e.ctx.save(),r.drawLayer(e,t),e.ctx.restore()}exportData(){let t=this._exportData(!0),n=this._exportData(!1),r={...this.config,mode:`export_verification`,client:{id:`exporter`,name:`exporter`},snapshotRequested:!1,transportService:new ZB};return T(n,new e(x(t),r)._exportData(!1))?t:(n.isNotSquishable=!0,n)}_exportData(e){let t=lw();for(let n of this.handlers)n instanceof SI&&n.export(t,e);return t.revisionId=this.session.getRevisionId()||`START_REVISION`,t=x(t),t}updateMode(e){this.config.mode=e,this.trigger(`update`)}async exportXLSX(){this.dispatch(`EVALUATE_CELLS`);let e=dw();for(let t of this.handlers)t instanceof xI&&await t.exportForExcel(e);return e=x(e),LU(e)}};function YU(e,t={}){let n=x(t);return n.type=e,n}function XU(e){return!OO.includes(e.horizontalGroupBy)||!OO.includes(e.verticalGroupBy)?`InvalidChartDefinition`:`Success`}let ZU={sequence:110,dataSeriesLimit:1,allowedDefinitionKeys:[...Kp.commonKeys,`dataSource`,`dataSetStyles`,`showValues`,`colorScale`,`missingValueColor`,`axesDesign`,`horizontalGroupBy`,`verticalGroupBy`,`legendPosition`],validateDefinition(e,t){return e.checkValidations(t,XU)},fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){let n=`left`;return e.legendPosition===`right`&&(n=`right`),{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},title:e.title||{text:``},type:`calendar`,showValues:e.showValues,axesDesign:e.axesDesign,legendPosition:n,horizontalGroupBy:`day_of_week`,verticalGroupBy:`month_number`}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractData:n}){let r=t_(t,n(),e),{labels:i,datasets:a}=mp(t,r);return{chartJsConfig:{type:`calendar`,data:{labels:i,datasets:a},options:{...rh,indexAxis:`x`,layout:N_(t,r),scales:Yf(t,a),plugins:{title:Q_(t,e),legend:{display:!1},tooltip:rv(t,r),chartShowValuesPlugin:q_(t,r),chartColorScalePlugin:Xf(t,r),background:{color:t.background}}}}}}},QU={sequence:15,allowedDefinitionKeys:[...Kp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`aggregated`,`axesDesign`,`showValues`,`hideDataMarkers`,`zoomable`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){return{...t,backgroundColor:zm(t.background||`#FFFFFF`),fontColor:zm(xf(t.background)),dataSets:n,labelRange:r,verticalAxis:Df(t)}},getDefinitionFromContextCreation(e,t){let n=e.dataSetStyles??{};if(e.dataSource?.type===`range`){let t=e.dataSource?.dataSets?.[0]?.dataSetId;for(let r of e.dataSource?.dataSets||[])n[r.dataSetId]={...e.dataSetStyles?.[r.dataSetId]||{},type:r.dataSetId===t?`bar`:`line`}}return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:n,aggregated:e.aggregated,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`combo`,axesDesign:e.axesDesign,showValues:e.showValues,hideDataMarkers:e.hideDataMarkers,zoomable:e.zoomable,humanize:e.humanize}},getRuntime(e,t,{extractData:n},r,i){let a=Qg(t,n(),e);return{chartJsConfig:{type:`bar`,data:{labels:a.labels,datasets:yp(t,a)},options:{...rh,layout:M_(t,a),scales:Jf(t,a),plugins:{title:Q_(t,e),legend:z_(t,a),tooltip:nv(t,a),chartShowValuesPlugin:K_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},$U={sequence:100,dataSeriesLimit:1,allowedDefinitionKeys:[...Kp.commonKeys,`dataSource`,`dataSetStyles`,`axesDesign`,`legendPosition`,`horizontal`,`aggregated`,`showValues`,`funnelColors`,`cumulative`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},aggregated:e.aggregated??!1,legendPosition:`none`,title:e.title||{text:``},type:`funnel`,showValues:e.showValues,axesDesign:e.axesDesign,funnelColors:e.funnelColors,horizontal:!0,cumulative:e.cumulative??!0,humanize:e.humanize}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractData:n},r,i){let a=s_(t,n(),e);return{chartJsConfig:{type:`funnel`,data:{labels:a.labels,datasets:Sp(t,a)},options:{...rh,indexAxis:`y`,layout:M_(t,a),scales:ap(t,a),plugins:{title:Q_(t,e),legend:{display:!1},tooltip:uv(t,a),chartShowValuesPlugin:K_(t,a),background:{color:t.background}},...i}}}}},eW={sequence:90,dataSeriesLimit:1,allowedDefinitionKeys:[...Kp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`colorScale`,`missingValueColor`,`region`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`geo`,humanize:e.humanize}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractData:n},r,i){let a=o_(t,n(),e);return{chartJsConfig:{type:`choropleth`,data:{datasets:xp(t,a)},options:{...rh,layout:M_(t,a),scales:ip(t,a),plugins:{title:Q_(t,e),tooltip:lv(t,a),legend:{display:!1},background:{color:t.background}},...i}}}}},tW={sequence:80,dataSeriesLimit:2,allowedDefinitionKeys:[...Kp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showValues`,`aggregated`,`axesDesign`,`stacked`,`horizontal`],fromStrDefinition:e=>({...e,horizontal:!0,stacked:!0}),toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`pyramid`,axesDesign:e.axesDesign,horizontal:!0,stacked:!0,showValues:e.showValues,humanize:e.humanize}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){if(t.dataSource.type!==`range`)return;let{dataSetsValues:i}=n_(t,CO(e,t.dataSource),e),a=Math.max(...i.map(e=>Math.max(...e.data.map(e=>U(e)?Math.abs(e.value):-1/0))));return{...t,horizontal:!0,backgroundColor:zm(t.background||`#FFFFFF`),fontColor:zm(xf(t.background)),dataSets:n,labelRange:r,verticalAxis:Df(t),maxValue:a}},getRuntime(e,t,{extractData:n},r,i){let a=n_(t,n(),e);return{chartJsConfig:{type:`bar`,data:{labels:a.labels,datasets:pp(t,a)},options:{...rh,indexAxis:`y`,layout:M_(t,a),scales:np(t,a),plugins:{title:Q_(t,e),legend:F_(t,a),tooltip:sv(t,a),chartShowValuesPlugin:Y_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},nW={sequence:80,allowedDefinitionKeys:[...Kp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showValues`,`aggregated`,`stacked`,`fillArea`,`hideDataMarkers`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},stacked:e.stacked??!1,aggregated:e.aggregated??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`radar`,fillArea:e.fillArea??!1,showValues:e.showValues??!1,hideDataMarkers:e.hideDataMarkers,humanize:e.humanize}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){return{...t,backgroundColor:zm(t.background||`#FFFFFF`),fontColor:zm(xf(t.background)),dataSets:n,labelRange:r}},getRuntime(e,t,{extractData:n},r,i){let a=a_(t,n(),e);return{chartJsConfig:{type:`radar`,data:{labels:a.labels,datasets:bp(t,a)},options:{...rh,layout:M_(t,a),scales:rp(t,a),plugins:{title:Q_(t,e),legend:V_(t,a),tooltip:cv(t,a),chartShowValuesPlugin:K_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},rW={sequence:60,allowedDefinitionKeys:[...Kp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showValues`,`labelsAsText`,`aggregated`,`axesDesign`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getContextCreation:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSource:t.fromContextCreation(e),dataSetStyles:e.dataSetStyles??{},labelsAsText:e.labelsAsText??!1,legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`scatter`,aggregated:e.aggregated??!1,axesDesign:e.axesDesign,showValues:e.showValues,humanize:e.humanize}},getDefinitionForExcel(e,t,{dataSets:n,labelRange:r}){return{...t,backgroundColor:zm(t.background||`#FFFFFF`),fontColor:zm(xf(t.background)),dataSets:n,labelRange:r,verticalAxis:Df(t)}},getRuntime(e,t,{extractData:n},r,i){let a=r_(t,n(),e);return{chartJsConfig:{type:`line`,data:{labels:a.labels,datasets:_p(t,a)},options:{...rh,layout:M_(t,a),scales:ep(t,a),plugins:{title:Q_(t,e),legend:R_(t,a),tooltip:iv(t,a),chartShowValuesPlugin:K_(t,a),background:{color:t.background}},...i}},customizableSeries:a.dataSetsValues.map(({dataSetId:e,label:t})=>({dataSetId:e,label:t}))}}},iW={sequence:30,allowedDefinitionKeys:[...Kp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showValues`,`showLabels`,`valuesDesign`,`groupColors`,`pieHolePercentage`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSetStyles:e.dataSetStyles??{},dataSource:t.fromHierarchicalContextCreation(e),legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`sunburst`,showValues:e.showValues,showLabels:e.showLabels,valuesDesign:e.valuesDesign,groupColors:e.groupColors,humanize:e.humanize,pieHolePercentage:e.pieHolePercentage}},getContextCreation(e,t,n){return{...e,...t.getHierarchicalContextCreation(n)}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractHierarchicalData:n},r,i){let a=c_(t,n(),e);return{chartJsConfig:{type:`doughnut`,data:{datasets:wp(t,a)},options:{cutout:t.pieHolePercentage===void 0?`25%`:`${t.pieHolePercentage}%`,...rh,layout:M_(t,a),plugins:{title:Q_(t,e),legend:H_(t,a),tooltip:dv(t,a),sunburstLabelsPlugin:J_(t,a),sunburstHoverPlugin:{enabled:!0},background:{color:t.background}},...i}}}}},aW={sequence:100,allowedDefinitionKeys:[...Kp.commonKeys,`dataSource`,`legendPosition`,`dataSetStyles`,`showHeaders`,`headerDesign`,`showLabels`,`valuesDesign`,`coloringOptions`,`showValues`],fromStrDefinition:e=>e,toStrDefinition:e=>e,copyInSheetId:e=>e,duplicateInDuplicatedSheet:e=>e,transformDefinition:e=>e,validateDefinition:()=>`Success`,updateRanges:e=>e,getDefinitionFromContextCreation(e,t){return{background:e.background,dataSetStyles:e.dataSetStyles??{},dataSource:t.fromHierarchicalContextCreation(e),legendPosition:e.legendPosition??`top`,title:e.title||{text:``},type:`treemap`,showValues:e.showValues,showHeaders:e.showHeaders,headerDesign:e.headerDesign,showLabels:e.showLabels,valuesDesign:e.valuesDesign,coloringOptions:e.treemapColoringOptions,humanize:e.humanize}},getContextCreation(e,t,n){return{...e,treemapColoringOptions:e.coloringOptions,...t.getHierarchicalContextCreation(n)}},getDefinitionForExcel:()=>void 0,getRuntime(e,t,{extractHierarchicalData:n},r,i){let a=c_(t,n(),e);return{chartJsConfig:{type:`treemap`,data:{labels:a.labels,datasets:kp(t,a)},options:{...rh,layout:M_(t,a),plugins:{title:Q_(t,e),legend:{display:!1},tooltip:fv(t,a),background:{color:t.background}},...i}}}}};sS.add(`bar`,_v),sS.add(`combo`,QU),sS.add(`line`,Ov),sS.add(`pie`,kv),sS.add(`scorecard`,nm),sS.add(`gauge`,Cv),sS.add(`scatter`,rW),sS.add(`waterfall`,Av),sS.add(`pyramid`,tW),sS.add(`radar`,nW),sS.add(`geo`,eW),sS.add(`funnel`,$U),sS.add(`sunburst`,iW),sS.add(`treemap`,aW),sS.add(`calendar`,ZU),Hv.add(`line`,{matcher:e=>e.type===`line`&&!e.stacked&&!e.fillArea,displayName:j(`Line`),chartType:`line`,chartSubtype:`line`,subtypeDefinition:{stacked:!1,fillArea:!1},category:`line`,preview:`o-spreadsheet-ChartPreview.LINE_CHART`}).add(`stacked_line`,{matcher:e=>e.type===`line`&&!e.fillArea&&!!e.stacked,displayName:j(`Stacked Line`),chartType:`line`,chartSubtype:`stacked_line`,subtypeDefinition:{stacked:!0,fillArea:!1},category:`line`,preview:`o-spreadsheet-ChartPreview.STACKED_LINE_CHART`}).add(`area`,{matcher:e=>e.type===`line`&&!e.stacked&&!!e.fillArea,displayName:j(`Area`),chartType:`line`,chartSubtype:`area`,subtypeDefinition:{stacked:!1,fillArea:!0},category:`area`,preview:`o-spreadsheet-ChartPreview.AREA_CHART`}).add(`stacked_area`,{matcher:e=>e.type===`line`&&e.stacked&&!!e.fillArea,displayName:j(`Stacked Area`),chartType:`line`,chartSubtype:`stacked_area`,subtypeDefinition:{stacked:!0,fillArea:!0},category:`area`,preview:`o-spreadsheet-ChartPreview.STACKED_AREA_CHART`}).add(`scatter`,{displayName:j(`Scatter`),chartType:`scatter`,chartSubtype:`scatter`,category:`misc`,preview:`o-spreadsheet-ChartPreview.SCATTER_CHART`}).add(`column`,{matcher:e=>e.type===`bar`&&!e.stacked&&!e.horizontal,displayName:j(`Column`),chartType:`bar`,chartSubtype:`column`,subtypeDefinition:{stacked:!1,horizontal:!1},category:`column`,preview:`o-spreadsheet-ChartPreview.COLUMN_CHART`}).add(`stacked_column`,{matcher:e=>e.type===`bar`&&e.stacked&&!e.horizontal,displayName:j(`Stacked Column`),chartType:`bar`,chartSubtype:`stacked_column`,subtypeDefinition:{stacked:!0,horizontal:!1},category:`column`,preview:`o-spreadsheet-ChartPreview.STACKED_COLUMN_CHART`}).add(`bar`,{matcher:e=>e.type===`bar`&&!e.stacked&&!!e.horizontal,displayName:j(`Bar`),chartType:`bar`,chartSubtype:`bar`,subtypeDefinition:{horizontal:!0,stacked:!1},category:`bar`,preview:`o-spreadsheet-ChartPreview.BAR_CHART`}).add(`stacked_bar`,{matcher:e=>e.type===`bar`&&e.stacked&&!!e.horizontal,displayName:j(`Stacked Bar`),chartType:`bar`,chartSubtype:`stacked_bar`,subtypeDefinition:{horizontal:!0,stacked:!0},category:`bar`,preview:`o-spreadsheet-ChartPreview.STACKED_BAR_CHART`}).add(`combo`,{displayName:j(`Combo`),chartSubtype:`combo`,chartType:`combo`,category:`line`,preview:`o-spreadsheet-ChartPreview.COMBO_CHART`}).add(`pie`,{matcher:e=>e.type===`pie`&&!e.isDoughnut,displayName:j(`Pie`),chartSubtype:`pie`,chartType:`pie`,subtypeDefinition:{isDoughnut:!1},category:`pie`,preview:`o-spreadsheet-ChartPreview.PIE_CHART`}).add(`doughnut`,{matcher:e=>e.type===`pie`&&!!e.isDoughnut,displayName:j(`Doughnut`),chartSubtype:`doughnut`,chartType:`pie`,subtypeDefinition:{isDoughnut:!0},category:`pie`,preview:`o-spreadsheet-ChartPreview.DOUGHNUT_CHART`}).add(`gauge`,{displayName:j(`Gauge`),chartSubtype:`gauge`,chartType:`gauge`,category:`misc`,preview:`o-spreadsheet-ChartPreview.GAUGE_CHART`}).add(`scorecard`,{displayName:j(`Scorecard`),chartSubtype:`scorecard`,chartType:`scorecard`,category:`misc`,preview:`o-spreadsheet-ChartPreview.SCORECARD_CHART`}).add(`waterfall`,{displayName:j(`Waterfall`),chartSubtype:`waterfall`,chartType:`waterfall`,category:`misc`,preview:`o-spreadsheet-ChartPreview.WATERFALL_CHART`}).add(`pyramid`,{displayName:j(`Population Pyramid`),chartSubtype:`pyramid`,chartType:`pyramid`,category:`misc`,preview:`o-spreadsheet-ChartPreview.POPULATION_PYRAMID_CHART`}).add(`radar`,{matcher:e=>e.type===`radar`&&!e.fillArea,displayName:j(`Radar`),chartSubtype:`radar`,chartType:`radar`,subtypeDefinition:{fillArea:!1},category:`misc`,preview:`o-spreadsheet-ChartPreview.RADAR_CHART`}).add(`filled_radar`,{matcher:e=>e.type===`radar`&&!!e.fillArea,displayName:j(`Filled Radar`),chartType:`radar`,chartSubtype:`filled_radar`,subtypeDefinition:{fillArea:!0},category:`misc`,preview:`o-spreadsheet-ChartPreview.FILLED_RADAR_CHART`}).add(`geo`,{displayName:j(`Geo Chart`),chartSubtype:`geo`,chartType:`geo`,category:`misc`,preview:`o-spreadsheet-ChartPreview.GEO_CHART`}).add(`funnel`,{displayName:j(`Funnel`),chartSubtype:`funnel`,chartType:`funnel`,category:`misc`,preview:`o-spreadsheet-ChartPreview.FUNNEL_CHART`}).add(`sunburst`,{matcher:e=>e.type===`sunburst`,displayName:j(`Sunburst`),chartSubtype:`sunburst`,chartType:`sunburst`,category:`hierarchical`,preview:`o-spreadsheet-ChartPreview.SUNBURST_CHART`}).add(`treemap`,{matcher:e=>e.type===`treemap`,displayName:j(`Tree Map`),chartType:`treemap`,chartSubtype:`treemap`,category:`hierarchical`,preview:`o-spreadsheet-ChartPreview.TREE_MAP_CHART`}).add(`calendar`,{displayName:j(`Calendar`),chartSubtype:`calendar`,chartType:`calendar`,category:`misc`,preview:`o-spreadsheet-ChartPreview.CALENDAR_CHART`});var oW=class extends WL{queuedBordersToAdd={};copy(e){let t=e.sheetId;if(e.zones.length===0)return;let{rowsIndexes:n,columnsIndexes:r}=e,i=[];for(let e of n){let n=[];for(let i of r){let r={col:i,row:e,sheetId:t};n.push(this.getters.getCellBorder(r))}i.push(n)}return{borders:i}}paste(e,t,n){let r=e.sheetId;if(n.pasteOption===`asValue`)return;let i=e.zones;if(!n.isCutOperation)this.pasteFromCopy(r,i,t.borders);else{let{left:e,top:n}=i[0];this.pasteZone(r,e,n,t.borders)}this.executeQueuedChanges(r)}pasteZone(e,t,n,r){for(let[i,a]of r.entries())for(let[r,o]of a.entries()){let a={col:t+r,row:n+i,sheetId:e};this.pasteBorder(o,a)}}pasteBorder(e,t){let n={...this.getters.getCellBorder(t),...e},r=JSON.stringify(n);this.queuedBordersToAdd[r]||(this.queuedBordersToAdd[r]=[]),this.queuedBordersToAdd[r].push(D(t))}executeQueuedChanges(e){for(let t in this.queuedBordersToAdd){let n=this.queuedBordersToAdd[t],r=JSON.parse(t),i=cn(n,[]);this.dispatch(`SET_BORDERS_ON_TARGET`,{sheetId:e,target:i,border:r})}this.queuedBordersToAdd={}}},sW=class extends UL{copy(e){}},cW=class extends sW{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);if(n.tag!==`carousel`)return;let r={...n},i=this.getters.getCarousel(e.figureId),a={};for(let e of i.items)if(e.type===`chart`){let t=this.getters.getChart(e.chartId);if(!t)throw Error(`No chart for the given id: ${e.chartId}`);a[e.chartId]=t}return{figureId:e.figureId,copiedFigure:r,copiedCarousel:i,copiedCharts:a,copiedSheetId:t}}getPasteTarget(e){return{zones:[],figureId:new Rd().smallUuid(),sheetId:e}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=e.sheetId,{width:o,height:s}=t.copiedFigure,c=this.getters.getMaxAnchorOffset(a,s,o),{left:l,top:u}=r[0],d={x:0,y:0};l>c.col&&(l=c.col,d.x=c.offset.x),u>c.row&&(u=c.row,d.y=c.offset.y),this.dispatch(`CREATE_CAROUSEL`,{figureId:i,sheetId:a,definition:{items:[]},col:l,row:u,offset:d,size:{height:s,width:o}});let f=new Rd,p=x(t.copiedCarousel.items);for(let e of p){if(e.type!==`chart`)continue;let n=t.copiedCharts[e.chartId],r=f.smallUuid(),o=yO.fromDefinition(this.getters,a,n.copyInSheetId(a)).getDefinition();this.dispatch(`CREATE_CHART`,{figureId:i,chartId:r,sheetId:a,definition:o}),e.chartId=r}this.dispatch(`UPDATE_CAROUSEL`,{sheetId:a,figureId:i,definition:{...t.copiedCarousel,items:p}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.copiedSheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},lW=class extends sW{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);if(n.tag!==`chart`)return;let r={...n},i=this.getters.getChartFromFigureId(e.figureId);if(!i)throw Error(`No chart for the given id: ${e.figureId}`);let a=i;return{figureId:e.figureId,copiedFigure:r,copiedChart:a}}getPasteTarget(e,t,n,r){return{zones:[],figureId:new Rd().smallUuid(),sheetId:e}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=e.sheetId,{width:o,height:s}=t.copiedFigure,c=t.copiedChart,l=yO.fromDefinition(this.getters,a,c.copyInSheetId(a)).getDefinition();l=yO.fromStrDefinition(this.getters,a,l).getDefinition();let u=this.getters.getMaxAnchorOffset(a,s,o),{left:d,top:f}=r[0],p={x:0,y:0};d>u.col&&(d=u.col,p.x=u.offset.x),f>u.row&&(f=u.row,p.y=u.offset.y),this.dispatch(`CREATE_CHART`,{figureId:i,chartId:new Rd().smallUuid(),sheetId:a,definition:l,col:d,row:f,offset:p,size:{height:s,width:o}}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.copiedChart.sheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},uW=class extends WL{uuidGenerator=new Rd;queuedChanges={};copy(e){if(!e.zones.length)return;let{rowsIndexes:t,columnsIndexes:n}=e,r=e.sheetId,i=[];for(let e of t){let t=[];for(let i of n){let n=Array.from(this.getters.getRulesByCell(r,i,e));t.push({position:{col:i,row:e,sheetId:r},rules:n})}i.push(t)}return{cfRules:i}}paste(e,t,n){if(this.queuedChanges={},n.pasteOption===`asValue`)return;let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t):this.pasteFromCopy(i,r,t.cfRules,n),this.executeQueuedChanges()}pasteFromCut(e,t,n){let r=t[0];this.pasteZone(e,r.left,r.top,n.cfRules,{isCutOperation:!0})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){let o={col:t+r,row:n+a,sheetId:e};this.pasteCf(s,o,i?.isCutOperation)}}pasteCf(e,t,n){if(e?.rules&&e.rules.length>0){let r=D(e.position),i=D(t);for(let a of e.rules){let o=[];if(n&&o.push(r),e.position.sheetId===t.sheetId)this.adaptCFRules(e.position.sheetId,a,[i],o);else{this.adaptCFRules(e.position.sheetId,a,[],o);let n=this.getCFToCopyTo(t.sheetId,a);this.adaptCFRules(t.sheetId,n,[i],[])}}}}adaptCFRules(e,t,n,r){this.queuedChanges[e]||(this.queuedChanges[e]=[]);let i=this.queuedChanges[e].find(e=>e.cf.id===t.id);i?(i.toAdd.push(...n),i.toRemove.push(...r)):this.queuedChanges[e].push({toAdd:n,toRemove:r,cf:t})}executeQueuedChanges(){for(let e in this.queuedChanges)for(let{toAdd:t,toRemove:n,cf:r}of this.queuedChanges[e]){let i=this.getters.getAdaptedCfRanges(e,r,t,n);if(i){if(i.length===0){this.dispatch(`REMOVE_CONDITIONAL_FORMAT`,{id:r.id,sheetId:e});continue}this.dispatch(`ADD_CONDITIONAL_FORMAT`,{cf:{id:r.id,rule:r.rule,stopIfTrue:r.stopIfTrue},ranges:i,sheetId:e})}}}getCFToCopyTo(e,t){let n=this.getters.getConditionalFormats(e).find(e=>e.stopIfTrue===t.stopIfTrue&&T(e.rule,t.rule)),r=this.queuedChanges[e];return!n&&r&&(n=r.find(e=>e.cf.stopIfTrue===t.stopIfTrue&&T(e.cf.rule,t.rule))?.cf),n||{...t,id:this.uuidGenerator.smallUuid(),ranges:[]}}},dW=class extends WL{uuidGenerator=new Rd;queuedChanges={};copy(e){let{rowsIndexes:t,columnsIndexes:n}=e,r=e.sheetId,i=[];for(let e of t){let t=[];for(let i of n){let n={sheetId:r,col:i,row:e},a=this.getters.getValidationRuleForCell(n);t.push({position:n,rule:a})}i.push(t)}return{dvRules:i}}paste(e,t,n){if(this.queuedChanges={},n.pasteOption)return;let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t):this.pasteFromCopy(i,r,t.dvRules),this.executeQueuedChanges()}pasteFromCut(e,t,n){let r=t[0];this.pasteZone(e,r.left,r.top,n.dvRules,{isCutOperation:!0})}pasteZone(e,t,n,r,i){for(let[a,o]of r.entries())for(let[r,s]of o.entries()){let o={col:t+r,row:n+a,sheetId:e};this.pasteDataValidation(s,o,i?.isCutOperation)}}pasteDataValidation(e,t,n){if(e){let r=D(t),i=D(e.position),a=e.rule;if(!a){let e=this.getters.getValidationRuleForCell(t);e&&this.adaptDataValidationRule(t.sheetId,e,[],[r]);return}let o=[];if(n&&o.push(i),e.position.sheetId===t.sheetId){let n=this.getDataValidationRuleToCopyTo(t.sheetId,a,!1);this.adaptDataValidationRule(e.position.sheetId,n,[r],o)}else{let n=this.getters.getValidationRuleForCell(e.position);n&&this.adaptDataValidationRule(e.position.sheetId,n,[],o);let i=this.getDataValidationRuleToCopyTo(t.sheetId,a);this.adaptDataValidationRule(t.sheetId,i,[r],[])}}}getDataValidationRuleToCopyTo(e,t,n=!0){let r=this.getters.getDataValidationRules(e).find(e=>T(t.criterion,e.criterion)&&t.isBlocking===e.isBlocking),i=this.queuedChanges[e];return!r&&i&&(r=i.find(e=>T(t.criterion,e.rule.criterion)&&t.isBlocking===e.rule.isBlocking)?.rule),r||{...t,id:n?this.uuidGenerator.smallUuid():t.id,ranges:[]}}adaptDataValidationRule(e,t,n,r){this.queuedChanges[e]||(this.queuedChanges[e]=[]);let i=this.queuedChanges[e].find(e=>e.rule.id===t.id);i?(i.toAdd.push(...n),i.toRemove.push(...r)):this.queuedChanges[e].push({toAdd:n,toRemove:r,rule:t})}executeQueuedChanges(){for(let e in this.queuedChanges)for(let{toAdd:t,toRemove:n,rule:r}of this.queuedChanges[e]){let i=cn([...cn(r.ranges.map(e=>e.zone),n),...t],[]);if(i.length===0){this.dispatch(`REMOVE_DATA_VALIDATION_RULE`,{sheetId:e,id:r.id});continue}this.dispatch(`ADD_DATA_VALIDATION_RULE`,{rule:{id:r.id,criterion:r.criterion,isBlocking:r.isBlocking},ranges:i.map(t=>this.getters.getRangeDataFromZone(e,t)),sheetId:e})}}},fW=class extends sW{copy(e){let t=e.sheetId,n=this.getters.getFigure(t,e.figureId);if(!n)throw Error(`No figure for the given id: ${e.figureId}`);let r={...n};if(n.tag!==`image`)return;let i=x(this.getters.getImage(e.figureId));return{figureId:e.figureId,copiedFigure:r,copiedImage:i,sheetId:t}}getPasteTarget(e,t,n,r){return{sheetId:e,zones:[],figureId:new Rd().smallUuid()}}paste(e,t,n){if(!e.figureId)return;let{zones:r,figureId:i}=e,a=this.getters.getActiveSheetId(),{width:o,height:s}=t.copiedFigure,c=x(t.copiedImage),l=this.getters.getMaxAnchorOffset(a,s,o),{left:u,top:d}=r[0],f={x:0,y:0};u>l.col&&(u=l.col,f.x=l.offset.x),d>l.row&&(d=l.row,f.y=l.offset.y),this.dispatch(`CREATE_IMAGE`,{figureId:i,sheetId:a,col:u,row:d,offset:f,size:{height:s,width:o},definition:c}),n.isCutOperation&&this.dispatch(`DELETE_FIGURE`,{sheetId:t.sheetId,figureId:t.copiedFigure.id}),this.dispatch(`SELECT_FIGURE`,{figureId:i})}isPasteAllowed(e,t,n,r){return t.length===0?`EmptyTarget`:r?.pasteOption===void 0?`Success`:`WrongFigurePasteOption`}},pW=class extends WL{copy(e){let t=this.getters.getActiveSheetId(),{rowsIndexes:n,columnsIndexes:r}=e,i=[];for(let e of n){let n=[];for(let i of r){let r={col:i,row:e,sheetId:t};n.push(this.getters.getMerge(r))}i.push(n)}return{merges:i,sheetId:t}}paste(e,t,n){if(n.isCutOperation){let e=t.merges.flat().filter(w);this.dispatch(`REMOVE_MERGE`,{sheetId:t.sheetId,target:e})}this.pasteFromCopy(e.sheetId,e.zones,t.merges,n)}pasteZone(e,t,n,r){for(let[i,a]of r.entries())for(let[r,o]of a.entries()){let a={col:t+r,row:n+i,sheetId:e};this.pasteMerge(o,a)}}pasteMerge(e,t){if(!e||this.getters.isInMerge(t))return;let{sheetId:n,col:r,row:i}=t;this.dispatch(`ADD_MERGE`,{sheetId:n,force:!0,target:[{left:r,top:i,right:r+e.right-e.left,bottom:i+e.bottom-e.top}]})}},mW=class extends WL{copy(e){return{zones:e.clippedZones,sheetId:e.sheetId}}paste(e,t,n){if(n.isCutOperation){let n=e.zones[0];this.dispatch(`MOVE_RANGES`,{target:t.zones,sheetId:t.sheetId,sheetName:this.getters.getSheetName(t.sheetId),targetSheetId:e.sheetId,col:n.left,row:n.top})}}},hW=class extends WL{isPasteAllowed(e,t,n,r){if(!(`cells`in n))return`Success`;let{xSplit:i,ySplit:a}=this.getters.getPaneDivisions(e);return Qn(qT(t,n.cells),i,a)?`FrozenPaneOverlap`:`Success`}},gW=class extends WL{copy(e,t,n=`copyPaste`){let r=e.sheetId,{rowsIndexes:i,columnsIndexes:a,zones:o}=e,s=new Set,c=[];for(let e of i){let l=[];c.push(l);for(let c of a){let a={col:c,row:e,sheetId:r},u=this.getters.getTable(a);if(!u){l.push({});continue}let d=this.getters.getCoreTable(a),f=d?.range.zone,p;if(!s.has(u.id)&&d&&f&&o.some(e=>In(f,e))){s.add(u.id);let{numberOfRows:e}=Ln(f);for(let n=f.top;n<=f.bottom;n++)!t&&!i.includes(n)&&e--;let n=d.range,r=this.getters.extendRange(d.range,`ROW`,n.zone.top+e-1-n.zone.bottom);p={range:this.getters.getRangeData(r),config:d.config,type:d.type}}if(u.isPivotTable){let t=u.range.zone.top===e&&u.range.zone.left===c,n=o.some(e=>In(u.range.zone,e));(t||n)&&s.add(u.id)}n!==`shiftCells`&&l.push({table:p,style:this.getTableStyleToCopy(a),isWholeTableCopied:s.has(u.id)})}}return{tableCells:c,sheetId:e.sheetId}}getTableStyleToCopy(e){let t=Dt({...this.getters.getCellTableStyle(e),hideGridLines:!1}),n=this.getters.getCellStyle(e),r=this.getters.getCellTableBorder(e),i=this.getters.getCellBorder(e);return{style:{...t,...Dt(n)},border:{...r,...Dt(i)}}}paste(e,t,n){let r=e.zones,i=e.sheetId;n.isCutOperation?this.pasteFromCut(i,r,t,n):this.pasteFromCopy(i,r,t.tableCells,n)}pasteFromCut(e,t,n,r){for(let e of n.tableCells)for(let t of e)t.table&&this.dispatch(`REMOVE_TABLE`,{sheetId:n.sheetId,target:[this.getters.getRangeFromRangeData(t.table.range).zone]});let i=t[0];this.pasteZone(e,i.left,i.top,n.tableCells,r)}pasteZone(e,t,n,r,i){for(let a=0;a<r.length;a++){let o=r[a];for(let r=0;r<o.length;r++){let s=o[r];if(!s)continue;let c={col:t+r,row:n+a,sheetId:e};this.pasteTableCell(e,s,c,i)}}if(r.length===1)for(let i=0;i<r[0].length;i++)this.dispatch(`AUTOFILL_TABLE_COLUMN`,{col:t+i,row:n,sheetId:e})}pasteTableCell(e,t,n,r){if(t.table&&!r?.pasteOption){let{range:r}=t.table,i=Ln(this.getters.getRangeFromRangeData(r).zone),a={left:n.col,top:n.row,right:n.col+i.numberOfCols-1,bottom:n.row+i.numberOfRows-1};this.dispatch(`CREATE_TABLE`,{sheetId:n.sheetId,ranges:[this.getters.getRangeDataFromZone(e,a)],config:t.table.config,tableType:t.table.type})}this.getters.getCoreTable(n)||r?.pasteOption===`asValue`||(!r?.pasteOption&&!t.isWholeTableCopied||r?.pasteOption===`onlyFormat`)&&(t.style?.style&&this.dispatch(`UPDATE_CELL`,{...n,style:t.style.style}),t.style?.border&&this.dispatch(`SET_BORDER`,{...n,border:t.style.border}))}};zF.figureHandlers.add(`chart`,lW).add(`image`,fW).add(`carousel`,cW),zF.cellHandlers.add(`dataValidation`,dW).add(`cell`,GL).add(`sheet`,hW).add(`merge`,pW).add(`border`,oW).add(`table`,gW).add(`conditionalFormat`,uW).add(`references`,mW);var _W=l({ARRAYTOTEXT:()=>KW,ARRAY_CONSTRAIN:()=>bW,ARRAY_LITERAL:()=>xW,ARRAY_ROW:()=>SW,CHOOSECOLS:()=>CW,CHOOSEROWS:()=>wW,EXPAND:()=>TW,FLATTEN:()=>EW,FREQUENCY:()=>DW,HSTACK:()=>OW,MDETERM:()=>kW,MINVERSE:()=>AW,MMULT:()=>jW,SUMPRODUCT:()=>MW,SUMX2MY2:()=>PW,SUMX2PY2:()=>FW,SUMXMY2:()=>IW,TOCOL:()=>zW,TOROW:()=>BW,TRANSPOSE:()=>VW,VSTACK:()=>HW,WRAPCOLS:()=>UW,WRAPROWS:()=>WW});function vW(e,t){let n=e.map(B),r=n.map(e=>e?.[0]?.length??0),i=Math.max(...r);if(t?.requireSameRowCount){let e=r[0];if(r.some(t=>t!==e))return new N(j(`All ranges in [[FUNCTION_NAME]] must have the same number of columns (got %s).`,r.join(`, `)))}let a=[];for(let e of n)for(let t=0;t<e.length;t++){let n=Array(i).fill({value:null});for(let r=0;r<e[t].length;r++)n[r]=e[t][r];a.push(n)}return a}function yW(e,t){let n=e.map(B),r=n.map(e=>e?.length??0),i=Math.max(...r);if(t?.requireSameColCount){let e=r[0];if(r.some(t=>t!==e))return new N(j(`All ranges in [[FUNCTION_NAME]] must have the same number of columns (got %s).`,r.join(`, `)))}let a=so(i,n.reduce((e,t)=>e+(t?.[0]?.length??0),0),()=>({value:null})),o=0;for(let e of n){for(let t=0;t<e.length;t++)for(let n=0;n<e[t].length;n++)a[t][o+n]=e[t][n];o+=e[0]?.length??0}return a}let bW={description:j(`Returns a result array constrained to a specific width and height.`),args:[k(`input_range (any, range<any>)`,j(`The range to constrain.`)),k(`rows (number)`,j(`The number of rows in the constrained array.`)),k(`columns (number)`,j(`The number of columns in the constrained array.`))],compute:function(e,t,n){let r=B(e),i=Ja(t?.value,this.locale),a=Ja(n?.value,this.locale);if(i<=0)return new N(j(`The rows argument (%s) must be strictly positive.`,i.toString()));if(a<=0)return new N(j(`The columns argument (%s) must be strictly positive.`,a.toString()));let o=Math.min(i,r[0].length);return so(Math.min(a,r.length),o,(e,t)=>r[e][t])},isExported:!1},xW={description:j(`Appends ranges vertically and in sequence to return a larger array. All ranges must have the same number of columns.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return yW(e,{requireSameColCount:!0})},isExported:!1,hidden:!0},SW={description:j(`Appends ranges horizontally and in sequence to return a larger array. All ranges must have the same number of rows.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return vW(e,{requireSameRowCount:!0})},isExported:!1,hidden:!0},CW={description:j(`Creates a new array from the selected columns in the existing range.`),args:[k(`array (any, range<any>)`,j(`The array that contains the columns to be returned.`)),k(`col_num (number, range<number>, repeating)`,j(`The column index of the column to be returned.`))],compute:function(e,...t){let n=B(e),r=wo(t,e=>Ja(e?.value,this.locale)),i=r.filter(e=>e===0||n.length<Math.abs(e));if(i.length!==0)return new N(j(`The columns arguments must be between -%s and %s (got %s), excluding 0.`,n.length.toString(),n.length.toString(),i.join(`,`)));let a=Array(r.length);for(let e=0;e<r.length;e++)r[e]>0?a[e]=n[r[e]-1]:a[e]=n[n.length+r[e]];return a},isExported:!0},wW={description:j(`Creates a new array from the selected rows in the existing range.`),args:[k(`array (any, range<any>)`,j(`The array that contains the rows to be returned.`)),k(`row_num (number, range<number>, repeating)`,j(`The row index of the row to be returned.`))],compute:function(e,...t){let n=B(e),r=wo(t,e=>Ja(e?.value,this.locale)),i=n.length,a=r.filter(e=>e===0||n[0].length<Math.abs(e));return a.length===0?so(i,r.length,(e,t)=>r[t]>0?n[e][r[t]-1]:n[e][n[e].length+r[t]]):new N(j(`The rows arguments must be between -%s and %s (got %s), excluding 0.`,n[0].length.toString(),n[0].length.toString(),a.join(`,`)))},isExported:!0},TW={description:j(`Expands or pads an array to specified row and column dimensions.`),args:[k(`array (any, range<any>)`,j(`The array to expand.`)),k(`rows (number)`,j(`The number of rows in the expanded array. If missing, rows will not be expanded.`)),k(`columns (number, optional)`,j(`The number of columns in the expanded array. If missing, columns will not be expanded.`)),k(`pad_with (any, default=0)`,j(`The value with which to pad.`))],compute:function(e,t,n,r={value:0}){let i=B(e),a=Ja(t?.value,this.locale),o=n===void 0?i.length:Ja(n.value,this.locale);return a<i[0].length?new N(j(`The rows arguments (%s) must be greater or equal than the number of rows of the array.`,a.toString())):o<i.length?new N(j(`The columns arguments (%s) must be greater or equal than the number of columns of the array.`,o.toString())):so(o,a,(e,t)=>e>=i.length||t>=i[e].length?r:i[e][t])},isExported:!0},EW={description:j(`Flattens all the values from one or more ranges into a single column.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to flatten.`))],compute:function(...e){return[wo(e,e=>e===void 0?{value:``}:e)]},isExported:!1},DW={description:j(`Calculates the frequency distribution of a range.`),args:[k(`data (range<number>)`,j(`The array of ranges containing the values to be counted.`)),k(`classes (number, range<number>)`,j(`The range containing the set of classes.`))],compute:function(e,t){let n=wo([e],e=>e.value).filter(e=>typeof e==`number`),r=wo([t],e=>e.value).filter(e=>typeof e==`number`).map((e,t)=>({initialIndex:t,value:e,count:0})).sort((e,t)=>e.value-t.value);r.push({initialIndex:r.length,value:1/0,count:0});let i=n.sort((e,t)=>e-t),a=0;for(let e of i){for(;e>r[a].value&&a<r.length-1;)a++;r[a].count++}return[r.sort((e,t)=>e.initialIndex-t.initialIndex).map(e=>e.count)]},isExported:!0},OW={description:j(`Appends ranges horizontally and in sequence to return a larger array.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return vW(e)},isExported:!0},kW={description:j(`Returns the matrix determinant of a square matrix.`),args:[k(`square_matrix (number, range<number>)`,j(`An range with an equal number of rows and columns representing a matrix whose determinant will be calculated.`))],compute:function(e){let t=Ka(e,`square_matrix`);return mh(t)?_h(t).determinant:new N(j(`The argument square_matrix must have the same number of columns and rows.`))},isExported:!0},AW={description:j(`Returns the multiplicative inverse of a square matrix.`),args:[k(`square_matrix (number, range<number>)`,j(`An range with an equal number of rows and columns representing a matrix whose multiplicative inverse will be calculated.`))],compute:function(e){let t=Ka(e,`square_matrix`);if(!mh(t))return new N(j(`The argument square_matrix must have the same number of columns and rows.`));let{inverted:n}=_h(t);return n||new N(j(`The matrix is not invertible.`))},isExported:!0},jW={description:j(`Calculates the matrix product of two matrices.`),args:[k(`matrix1 (number, range<number>)`,j(`The first matrix in the matrix multiplication operation.`)),k(`matrix2 (number, range<number>)`,j(`The second matrix in the matrix multiplication operation.`))],compute:function(e,t){let n=Ka(e,`matrix1`),r=Ka(t,`matrix2`);return n.length===0||r.length===0?new N(j(`The first and second arguments of [[FUNCTION_NAME]] must be non-empty matrices.`)):n.length===r[0].length?yh(n,r):new N(j(`In [[FUNCTION_NAME]], the number of columns of the first matrix (%s) must be equal to the number of rows of the second matrix (%s).`,n.length.toString(),r[0].length.toString()))},isExported:!0},MW={description:j(`Calculates the sum of the products of corresponding entries in equal-sized ranges.`),args:[k(`range (number, range<number>, repeating)`,j(`The range whose entries will be multiplied with corresponding entries in the other range.`))],compute:function(...e){if(!ph(...e))return new N(j(`All the ranges must have the same dimensions.`));let t=e.map(B),n=0;for(let e=0;e<t[0].length;e++)for(let r=0;r<t[0][e].length;r++){if(!t.every(t=>typeof t[e][r].value==`number`))continue;let i=1;for(let n of t)i*=I(n[e][r],this.locale);n+=i}return n},isExported:!0};function NW(e,t,n){if(!ph(e,t))return new N(j(`The arguments array_x and array_y must have the same dimensions.`));let r=B(e),i=B(t),a=!1,o=0;for(let e in r)for(let t in r[e]){let s=r[e][t].value,c=i[e][t].value;typeof s!=`number`||typeof c!=`number`||(a=!0,o+=n(s,c))}return a?o:new N(j(`The arguments array_x and array_y must contain at least one pair of numbers.`))}let PW={description:j(`Calculates the sum of the difference of the squares of the values in two array.`),args:[k(`array_x (number, range<number>)`,j(`The array or range of values whose squares will be reduced by the squares of corresponding entries in array_y and added together.`)),k(`array_y (number, range<number>)`,j(`The array or range of values whose squares will be subtracted from the squares of corresponding entries in array_x and added together.`))],compute:function(e,t){return NW(e,t,(e,t)=>e**2-t**2)},isExported:!0},FW={description:j(`Calculates the sum of the sum of the squares of the values in two array.`),args:[k(`array_x (number, range<number>)`,j(`The array or range of values whose squares will be added to the squares of corresponding entries in array_y and added together.`)),k(`array_y (number, range<number>)`,j(`The array or range of values whose squares will be added to the squares of corresponding entries in array_x and added together.`))],compute:function(e,t){return NW(e,t,(e,t)=>e**2+t**2)},isExported:!0},IW={description:j(`Calculates the sum of squares of the differences of values in two array.`),args:[k(`array_x (number, range<number>)`,j(`The array or range of values that will be reduced by corresponding entries in array_y, squared, and added together.`)),k(`array_y (number, range<number>)`,j(`The array or range of values that will be subtracted from corresponding entries in array_x, the result squared, and all such results added together.`))],compute:function(e,t){return NW(e,t,(e,t)=>(e-t)**2)},isExported:!0},LW=[k(`array (any, range<any>)`,j(`The array which will be transformed.`)),k(`ignore (number, default=0)`,j(`Whether to ignore certain types of values. By default, no values are ignored.`),[{value:0,label:j(`Keep all values (default)`)},{value:1,label:j(`Ignore blanks`)},{value:2,label:j(`Ignore errors`)},{value:3,label:j(`Ignore blanks and errors`)}]),k(`scan_by_column (number, default=false)`,j(`Scan the array by column. By default, the array is scanned by row.`),[{value:!1,label:j(`Scan by row (default)`)},{value:!0,label:j(`Scan by column`)}])];function RW(e){let t=Math.trunc(e);if(t===0)return()=>!0;if(t===1)return e=>e.value!==null;if(t===2)return e=>!F(e.value);if(t===3)return e=>e.value!==null&&!F(e.value);throw new N(j(`Argument ignore must be between 0 and 3`))}let zW={description:j(`Transforms a range of cells into a single column.`),args:LW,compute:function(e,t={value:0},n={value:!1}){let r=B(e),i=I(t.value,this.locale),a=(R(n.value)?r:uo(r)).flat().filter(RW(i));return a.length===0?new Ri(j(`No results for the given arguments of TOCOL.`)):[a]},isExported:!0},BW={description:j(`Transforms a range of cells into a single row.`),args:LW,compute:function(e,t={value:0},n={value:!1}){let r=B(e),i=I(t.value,this.locale),a=(R(n.value)?r:uo(r)).flat().filter(RW(i)).map(e=>[e]);return a.length===0||a[0].length===0?new Ri(j(`No results for the given arguments of TOROW.`)):a},isExported:!0},VW={description:j(`Transposes the rows and columns of a range.`),args:[k(`range (any, range<any>)`,j(`The range to be transposed.`))],compute:function(e){let t=B(e),n=t[0].length,r=t.length;return so(n,r,(e,n)=>t[n][e])},isExported:!0},HW={description:j(`Appends ranges vertically and in sequence to return a larger array.`),args:[k(`range (any, range<any>, repeating)`,j(`The range to be appended.`))],compute:function(...e){return yW(e)},isExported:!0},UW={description:j(`Wraps the provided row or column of cells by columns after a specified number of elements to form a new array.`),args:[k(`range (any, range<any>)`,j(`The range to wrap.`)),k(`wrap_count (number)`,j(`The maximum number of cells for each column, rounded down to the nearest whole number.`)),k(`pad_with (any, default=0)`,j(`The value with which to fill the extra cells in the range.`))],compute:function(e,t,n={value:0}){let r=B(e),i=Ja(t?.value,this.locale);if(!fh(r))return new N(j(`Argument range must be a single row or column.`));let a=r.flat();return so(Math.ceil(a.length/i),i,(e,t)=>{let r=e*i+t;return r<a.length?a[r]:n})},isExported:!0},WW={description:j(`Wraps the provided row or column of cells by rows after a specified number of elements to form a new array.`),args:[k(`range (any, range<any>)`,j(`The range to wrap.`)),k(`wrap_count (number)`,j(`The maximum number of cells for each row, rounded down to the nearest whole number.`)),k(`pad_with (any, default=0)`,j(`The value with which to fill the extra cells in the range.`))],compute:function(e,t,n={value:0}){let r=B(e),i=Ja(t?.value,this.locale);if(!fh(r))return new N(j(`Argument range must be a single row or column.`));let a=r.flat();return so(i,Math.ceil(a.length/i),(e,t)=>{let r=t*i+e;return r<a.length?a[r]:n})},isExported:!0},GW=[{value:0,label:j(`Concise format\xA0(default)`)},{value:1,label:j(`Strict format`)}],KW={description:j(`returns an array of text values from any specified range. It passes text values unchanged, and converts non-text values to text.`),args:[k(`array (range)`,j(`The array to convert into text`)),k(`format (number, default=0)`,j(`The format of the returned data.`),GW)],compute:function(e,t={value:0}){let n=I(t,this.locale),r=B(e);if(n===1)return rT(r,``,this.locale);if(n===0){let e=this.locale.decimalSeparator===`,`?`/`:`,`;return uo(r).flatMap(e=>e.map(e=>F(e.value)?e.value:L(e))).join(e)}else return new N(j(`Format must be 0 or 1`))},isExported:!0};var qW=l({ABS:()=>YW,ACOS:()=>XW,ACOSH:()=>ZW,ACOT:()=>QW,ACOTH:()=>$W,ASIN:()=>eG,ASINH:()=>tG,ATAN:()=>nG,ATAN2:()=>rG,ATANH:()=>iG,CEILING:()=>aG,CEILING_MATH:()=>sG,CEILING_PRECISE:()=>cG,COS:()=>lG,COSH:()=>uG,COT:()=>dG,COTH:()=>fG,COUNTBLANK:()=>pG,COUNTIF:()=>mG,COUNTIFS:()=>hG,COUNTUNIQUE:()=>gG,COUNTUNIQUEIFS:()=>_G,CSC:()=>vG,CSCH:()=>yG,DECIMAL:()=>bG,DEGREES:()=>xG,EXP:()=>SG,FLOOR:()=>CG,FLOOR_MATH:()=>TG,FLOOR_PRECISE:()=>EG,INT:()=>cK,ISEVEN:()=>DG,ISODD:()=>kG,ISO_CEILING:()=>OG,LN:()=>AG,LOG:()=>jG,MOD:()=>NG,MUNIT:()=>PG,ODD:()=>FG,PI:()=>IG,POWER:()=>LG,PRODUCT:()=>RG,RAND:()=>zG,RANDARRAY:()=>BG,RANDBETWEEN:()=>VG,ROUND:()=>HG,ROUNDDOWN:()=>UG,ROUNDUP:()=>WG,SEC:()=>GG,SECH:()=>KG,SEQUENCE:()=>qG,SIN:()=>JG,SINH:()=>YG,SQRT:()=>XG,SUBTOTAL:()=>eK,SUM:()=>tK,SUMIF:()=>nK,SUMIFS:()=>rK,TAN:()=>iK,TANH:()=>aK,TRUNC:()=>sK});let JW=/^-?[a-z0-9]+$/i,YW={description:j(`Absolute value of a number.`),args:[k(`value (number)`,j(`The number of which to return the absolute value.`))],compute:function(e){return Math.abs(I(e,this.locale))},isExported:!0},XW={description:j(`Inverse cosine of a value, in radians.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse cosine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=I(e,this.locale);return Math.abs(t)>1?new N(j(`The value (%s) must be between -1 and 1 inclusive.`,t)):Math.acos(t)},isExported:!0},ZW={description:j(`Inverse hyperbolic cosine of a number.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse hyperbolic cosine. Must be greater than or equal to 1.`))],compute:function(e){let t=I(e,this.locale);return t<1?new N(j(`The value (%s) must be greater than or equal to 1.`,t)):Math.acosh(t)},isExported:!0},QW={description:j(`Inverse cotangent of a value.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse cotangent.`))],compute:function(e){let t=I(e,this.locale);return(Math.sign(t)||1)*Math.PI/2-Math.atan(t)},isExported:!0},$W={description:j(`Inverse hyperbolic cotangent of a value.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse hyperbolic cotangent. Must not be between -1 and 1, inclusive.`))],compute:function(e){let t=I(e,this.locale);return Math.abs(t)<=1?new N(j(`The value (%s) cannot be between -1 and 1 inclusive.`,t)):Math.log((t+1)/(t-1))/2},isExported:!0},eG={description:j(`Inverse sine of a value, in radians.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse sine. Must be between -1 and 1, inclusive.`))],compute:function(e){let t=I(e,this.locale);return Math.abs(t)>1?new N(j(`The value (%s) must be between -1 and 1 inclusive.`,t)):Math.asin(t)},isExported:!0},tG={description:j(`Inverse hyperbolic sine of a number.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse hyperbolic sine.`))],compute:function(e){return Math.asinh(I(e,this.locale))},isExported:!0},nG={description:j(`Inverse tangent of a value, in radians.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse tangent.`))],compute:function(e){return Math.atan(I(e,this.locale))},isExported:!0},rG={description:j(`Angle from the X axis to a point (x,y), in radians.`),args:[k(`x (number)`,j(`The x coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.`)),k(`y (number)`,j(`The y coordinate of the endpoint of the line segment for which to calculate the angle from the x-axis.`))],compute:function(e,t){let n=I(e,this.locale),r=I(t,this.locale);return n===0&&r===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):Math.atan2(r,n)},isExported:!0},iG={description:j(`Inverse hyperbolic tangent of a number.`),args:[k(`value (number)`,j(`The value for which to calculate the inverse hyperbolic tangent. Must be between -1 and 1, exclusive.`))],compute:function(e){let t=I(e,this.locale);return Math.abs(t)>=1?new N(j(`The value (%s) must be between -1 and 1 exclusive.`,t)):Math.atanh(t)},isExported:!0},aG={description:j(`Rounds number up to nearest multiple of factor.`),args:[k(`value (number)`,j(`The value to round up to the nearest integer multiple of factor.`)),k(`factor (number, default=1)`,j(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=I(e,this.locale),r=I(t,this.locale);return r<0&&n>0?new N(j(`The factor (%s) must be positive when the value (%s) is positive.`,r,n)):{value:r?Math.ceil(n/r)*r:0,format:e?.format}},isExported:!0};function oG(e,t,n=0){return t===0?0:(t=Math.abs(t),e>=0?Math.ceil(e/t)*t:n===0?-Math.floor(Math.abs(e)/t)*t:-Math.ceil(Math.abs(e)/t)*t)}let sG={description:j(`Rounds number up to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round up to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),k(`mode (number, default=0)`,j(`If number is negative, specifies the rounding direction. If 0 or blank, it is rounded towards zero. Otherwise, it is rounded away from zero.`))],compute:function(e,t={value:1},n={value:0}){let r=I(t,this.locale);return{value:oG(I(e,this.locale),r,I(n,this.locale)),format:e?.format}},isExported:!0},cG={description:j(`Rounds number up to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round up to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=I(t,this.locale);return{value:oG(I(e,this.locale),n),format:e?.format}},isExported:!0},lG={description:j(`Cosine of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the cosine of, in radians.`))],compute:function(e){return Math.cos(I(e,this.locale))},isExported:!0},uG={description:j(`Hyperbolic cosine of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic cosine of.`))],compute:function(e){return Math.cosh(I(e,this.locale))},isExported:!0},dG={description:j(`Cotangent of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the cotangent of, in radians.`))],compute:function(e){let t=I(e,this.locale);return t===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tan(t)},isExported:!0},fG={description:j(`Hyperbolic cotangent of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic cotangent of.`))],compute:function(e){let t=I(e,this.locale);return t===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.tanh(t)},isExported:!0},pG={description:j(`Number of empty values.`),args:[k(`value (any, range, repeating)`,j(`Value or range in which to count the number of blanks.`))],compute:function(...e){return io(e,(e,t)=>t===void 0||t.value===null||t.value===``?e+1:e,0)},isExported:!0},mG={description:j(`A conditional count across a range.`),args:[k(`range (range)`,j(`The range that is tested against criterion.`)),k(`criterion (string)`,j(`The pattern or test to apply to range.`))],compute:function(...e){let t=0;return vo(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},hG={description:j(`Count values depending on multiple criteria.`),args:[k(`criteria_range (any, range, repeating)`,j(`Range over which to evaluate criteria.`)),k(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(...e){let t=0;return vo(e,(e,n)=>{t+=1},this.locale),t},isExported:!0},gG={description:j(`Counts number of unique values in a range.`),args:[k(`value (any, range, repeating)`,j(`Value or range to consider for uniqueness.`))],compute:function(...e){return Zh(e)}},_G={description:j(`Counts number of unique values in a range, filtered by a set of criteria.`),args:[k(`range (range)`,j(`The range of cells from which the number of unique values will be counted.`)),k(`criteria_range (any, range, repeating)`,j(`Range over which to evaluate criteria.`)),k(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(e,...t){let n=new Set;return vo(t,(t,r)=>{let i=e[t]?.[r];To(i)&&n.add(i.value)},this.locale),n.size}},vG={description:j(`Cosecant of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the cosecant of, in radians.`))],compute:function(e){let t=I(e,this.locale);return t===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sin(t)},isExported:!0},yG={description:j(`Hyperbolic cosecant of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic cosecant of.`))],compute:function(e){let t=I(e,this.locale);return t===0?new Vi(j(`Function [[FUNCTION_NAME]] caused a divide by zero error.`)):1/Math.sinh(t)},isExported:!0},bG={description:j(`Converts from another base to decimal.`),args:[k(`value (string)`,j(`The number to convert.`)),k(`base (number)`,j(`The base to convert the value from.`))],compute:function(e,t){let n=I(t,this.locale);if(n=Math.floor(n),2>n||n>36)return new N(j(`The base (%s) must be between 2 and 36 inclusive.`,n));let r=L(e);if(r===``)return 0;if(!JW.test(r))return new N(j(`The value (%s) must be a valid base %s representation.`,r,n));let i=parseInt(r,n);return isNaN(i)?new N(j(`The value (%s) must be a valid base %s representation.`,r,n)):i},isExported:!0},xG={description:j(`Converts an angle value in radians to degrees.`),args:[k(`angle (number)`,j(`The angle to convert from radians to degrees.`))],compute:function(e){return I(e,this.locale)*180/Math.PI},isExported:!0},SG={description:j(`Euler's number, e (~2.718) raised to a power.`),args:[k(`value (number)`,j(`The exponent to raise e.`))],compute:function(e){return Math.exp(I(e,this.locale))},isExported:!0},CG={description:j(`Rounds number down to nearest multiple of factor.`),args:[k(`value (number)`,j(`The value to round down to the nearest integer multiple of factor.`)),k(`factor (number, default=1)`,j(`The number to whose multiples value will be rounded.`))],compute:function(e,t={value:1}){let n=I(e,this.locale),r=I(t,this.locale);return r<0&&n>0?new N(j(`The factor (%s) must be positive when the value (%s) is positive.`,r,n)):{value:r?Math.floor(n/r)*r:0,format:e?.format}},isExported:!0};function wG(e,t,n=0){return t===0?0:(t=Math.abs(t),e>=0?Math.floor(e/t)*t:n===0?-Math.ceil(Math.abs(e)/t)*t:-Math.floor(Math.abs(e)/t)*t)}let TG={description:j(`Rounds number down to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round down to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded. The sign of significance will be ignored.`)),k(`mode (number, default=0)`,j(`If number is negative, specifies the rounding direction. If 0 or blank, it is rounded away from zero. Otherwise, it is rounded towards zero.`))],compute:function(e,t={value:1},n={value:0}){let r=I(t,this.locale);return{value:wG(I(e,this.locale),r,I(n,this.locale)),format:e?.format}},isExported:!0},EG={description:j(`Rounds number down to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round down to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){let n=I(t,this.locale);return{value:wG(I(e,this.locale),n),format:e?.format}},isExported:!0},DG={description:j(`Whether the provided value is even.`),args:[k(`value (number)`,j(`The value to be verified as even.`))],compute:function(e){let t=qa(e,this.locale);return!(Math.floor(Math.abs(t))&1)},isExported:!0},OG={description:j(`Rounds number up to nearest multiple of factor.`),args:[k(`number (number)`,j(`The value to round up to the nearest integer multiple of significance.`)),k(`significance (number, default=1)`,j(`The number to whose multiples number will be rounded.`))],compute:function(e,t={value:1}){return{value:oG(I(e,this.locale),I(t,this.locale)),format:e?.format}},isExported:!0},kG={description:j(`Whether the provided value is even.`),args:[k(`value (number)`,j(`The value to be verified as even.`))],compute:function(e){let t=qa(e,this.locale);return!!(Math.floor(Math.abs(t))&1)},isExported:!0},AG={description:j(`The logarithm of a number, base e (euler's number).`),args:[k(`value (number)`,j(`The value for which to calculate the logarithm, base e.`))],compute:function(e){let t=I(e,this.locale);return t<=0?new N(j(`The value (%s) must be strictly positive.`,t)):Math.log(t)},isExported:!0},jG={description:j(`The logarithm of a number, for a given base.`),args:[k(`value (number)`,j(`The value for which to calculate the logarithm.`)),k(`base (number, default=10)`,j(`The base of the logarithm.`))],compute:function(e,t={value:10}){let n=I(e,this.locale),r=I(t,this.locale);return n<=0?new N(j(`The value (%s) must be strictly positive.`,n)):r<=0?new N(j(`The base (%s) must be strictly positive.`,r)):r===1?new N(j(`The base must be different from 1.`)):Math.log10(n)/Math.log10(r)},isExported:!0};function MG(e,t){dh(t,j(`The divisor must be different from 0.`));let n=e%t;return n>0&&t<0||n<0&&t>0?n+t:n}let NG={description:j(`Modulo (remainder) operator.`),args:[k(`dividend (number)`,j(`The number to be divided to find the remainder.`)),k(`divisor (number)`,j(`The number to divide by.`))],compute:function(e,t){let n=I(t,this.locale);return{value:MG(I(e,this.locale),n),format:e?.format}},isExported:!0},PG={description:j(`Returns a n x n unit matrix, where n is the input dimension.`),args:[k(`dimension (number)`,j(`An integer specifying the dimension size of the unit matrix. It must be positive.`))],compute:function(e){let t=Ja(e,this.locale);return t<1?new N(j(`The argument dimension must be positive`)):gh(t)},isExported:!0},FG={description:j(`Rounds a number up to the nearest odd integer.`),args:[k(`value (number)`,j(`The value to round to the next greatest odd number.`))],compute:function(e){let t=I(e,this.locale),n=Math.ceil(Math.abs(t));return n=n&1?n:n+1,{value:t<0?-n:n,format:e?.format}},isExported:!0},IG={description:j(`The number pi.`),args:[],compute:function(){return Math.PI},isExported:!0},LG={description:j(`A number raised to a power.`),args:[k(`base (number)`,j(`The number to raise to the exponent power.`)),k(`exponent (number)`,j(`The exponent to raise base to.`))],compute:function(e,t){let n=I(e,this.locale),r=I(t,this.locale);return n<0&&!Number.isInteger(r)?new N(j(`The exponent (%s) must be an integer when the base is negative.`,r)):{value:n**+r,format:e?.format}},isExported:!0},RG={description:j(`Result of multiplying a series of numbers together.`),args:[k(`factor (number, range<number>, repeating)`,j(`Number or range to calculate for the product.`))],compute:function(...e){let t=0,n=1;for(let r of e)if(Je(r))for(let e of r)for(let r of e){let e=r.value;if(typeof e==`number`&&(n*=e,t+=1),F(e))return r}else r!==void 0&&r.value!==null&&(n*=qa(r,this.locale),t+=1);return{value:t===0?0:n,format:za(e[0])}},isExported:!0},zG={description:j(`A random number between 0 inclusive and 1 exclusive.`),args:[],compute:function(){return Math.random()},isExported:!0},BG={description:j(`Returns a grid of random numbers between 0 inclusive and 1 exclusive.`),args:[k(`rows (number, default=1)`,j(`The number of rows to be returned.`)),k(`columns (number, default=1)`,j(`The number of columns to be returned.`)),k(`min (number, default=0)`,j(`The minimum number you would like returned.`)),k(`max (number, default=1)`,j(`The maximum number you would like returned.`)),k(`whole_number (boolean, default=FALSE)`,j(`Return a whole number or a decimal value.`),[{value:!1,label:j(`Decimal (default)`)},{value:!0,label:j(`Integer`)}])],compute:function(e={value:1},t={value:1},n={value:0},r={value:1},i={value:!1}){let a=Ja(t,this.locale),o=Ja(e,this.locale),s=I(n,this.locale),c=I(r,this.locale),l=R(i);if(a<1)return new N(j(`The number of columns (%s) must be positive.`,a));if(o<1)return new N(j(`The number of rows (%s) must be positive.`,o));if(s>c)return new N(j(`The maximum (%s) must be greater than or equal to the minimum (%s).`,c,s));if(l&&(!Number.isInteger(s)||!Number.isInteger(c)))return new N(j(`The maximum (%s) and minimum (%s) must be integers when whole_number is TRUE.`,c.toString(),s.toString()));let u=Array(a);for(let e=0;e<a;e++){u[e]=Array(o);for(let t=0;t<o;t++)l?u[e][t]=Math.floor(Math.random()*(c-s+1)+s):u[e][t]=s+Math.random()*(c-s)}return u},isExported:!0},VG={description:j(`Random integer between two values, inclusive.`),args:[k(`low (number)`,j(`The low end of the random range.`)),k(`high (number)`,j(`The high end of the random range.`))],compute:function(e,t){let n=I(e,this.locale);Number.isInteger(n)||(n=Math.ceil(n));let r=I(t,this.locale);return Number.isInteger(r)||(r=Math.floor(r)),n>r?new N(j(`The high (%s) must be greater than or equal to the low (%s).`,r,n)):{value:n+Math.ceil((r-n+1)*Math.random())-1,format:e?.format}},isExported:!0},HG={description:j(`Rounds a number according to standard rules.`),args:[k(`value (number)`,j(`The value to round to places number of places.`)),k(`places (number, default=0)`,j(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=I(e,this.locale),r=I(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.round(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.round(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},UG={description:j(`Rounds down a number.`),args:[k(`value (number)`,j(`The value to round to places number of places, always rounding down.`)),k(`places (number, default=0)`,j(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=I(e,this.locale),r=I(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.floor(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.floor(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},WG={description:j(`Rounds up a number.`),args:[k(`value (number)`,j(`The value to round to places number of places, always rounding up.`)),k(`places (number, default=0)`,j(`The number of decimal places to which to round.`))],compute:function(e,t={value:0}){let n=I(e,this.locale),r=I(t,this.locale),i=Math.abs(n),a;return r===0?a=Math.ceil(i):(Number.isInteger(r)||(r=Math.trunc(r)),a=Math.ceil(i*10**r)/10**r),{value:n>=0?a:-a,format:e?.format}},isExported:!0},GG={description:j(`Secant of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the secant of, in radians.`))],compute:function(e){return 1/Math.cos(I(e,this.locale))},isExported:!0},KG={description:j(`Hyperbolic secant of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic secant of.`))],compute:function(e){return 1/Math.cosh(I(e,this.locale))},isExported:!0},qG={description:j(`Returns a sequence of numbers.`),args:[k(`rows (number)`,j(`The number of rows to return`)),k(`columns (number, optional, default=1)`,j(`The number of columns to return`)),k(`start (number, optional, default=1)`,j(`The first number in the sequence`)),k(`step (number, optional, default=1)`,j(`The amount to increment each value in the sequence`))],compute:function(e,t={value:1},n={value:1},r={value:1}){let i=I(n,this.locale),a=I(r,this.locale),o=Ja(e,this.locale),s=Ja(t,this.locale);return s<1?new N(j(`The number of columns (%s) must be positive.`,s)):o<1?new N(j(`The number of rows (%s) must be positive.`,o)):so(s,o,(e,t)=>({value:i+t*s*a+e*a}))},isExported:!0},JG={description:j(`Sine of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the sine of, in radians.`))],compute:function(e){return Math.sin(I(e,this.locale))},isExported:!0},YG={description:j(`Hyperbolic sine of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic sine of.`))],compute:function(e){return Math.sinh(I(e,this.locale))},isExported:!0},XG={description:j(`Positive square root of a positive number.`),args:[k(`value (number)`,j(`The number for which to calculate the positive square root.`))],compute:function(e){let t=I(e,this.locale);return t<0?new N(j(`The value (%s) must be positive or null.`,t)):{value:Math.sqrt(t),format:e?.format}},isExported:!0},ZG={1:`AVERAGE`,2:`COUNT`,3:`COUNTA`,4:`MAX`,5:`MIN`,6:`PRODUCT`,7:`STDEV`,8:`STDEVP`,9:`SUM`,10:`VAR`,11:`VARP`},QG=Object.entries(ZG).map(([e,t])=>({value:parseInt(e),label:j(`%s (include manually-hidden rows)`,t)})),$G=Object.entries(ZG).map(([e,t])=>({value:parseInt(e)+100,label:j(`%s (exclude manually-hidden rows)`,t)})),eK={description:j(`Returns a subtotal for a vertical range of cells using a specified aggregation function.`),args:[k(`function_code (number)`,j(`The function to use in subtotal aggregation.`),[...QG,...$G]),k(`ref (any, range<any>, repeating)`,j(`Range or reference for which you want the subtotal.`))],compute:function(e,...t){let n=Ja(e,this.locale),r=!0;if(n>100&&(n-=100,r=!1),n<1||n>11)return new N(j(`The function code (%s) must be between 1 to 11 or 101 to 111.`,n));let i=[];for(let e of t){let t=B(e),n=t[0][0]?.position;if(n===void 0)return new Li(Ha);let a=n.col+t.length-1,o=n.row+t[0].length-1,s=n.sheetId;for(let e=n.row;e<=o;e++)if(!this.getters.isRowFiltered(s,e)&&!(!r&&this.getters.isRowHiddenByUser(s,e)))for(let t=n.col;t<=a;t++){let n=this.getters.getCorrespondingFormulaCell({sheetId:s,col:t,row:e});(!n||!Yt(n,`SUBTOTAL`))&&i.push(this.getFormulaResult({sheetId:s,col:t,row:e}))}}return this[ZG[n]].apply(this,[[i]])},isExported:!0},tK={description:j(`Sum of a series of numbers and/or cells.`),args:[k(`value (number, range<number>, repeating)`,j(`Number or range to add together.`))],compute:function(...e){let t=e[0];return{value:Xh(e,this.locale),format:za(t)}},isExported:!0},nK={description:j(`A conditional sum across a range.`),args:[k(`criteria_range (range)`,j(`The range which is tested against criterion.`)),k(`criterion (string)`,j(`The pattern or test to apply to range.`)),k(`sum_range (range, default=criteria_range)`,j(`The range to be summed, if different from range.`))],compute:function(e,t,n){n===void 0&&(n=e);let r=0;return vo([e,t],(e,t)=>{let i=n[e]?.[t]?.value;typeof i==`number`&&(r+=i)},this.locale),r},isExported:!0},rK={description:j(`Sums a range depending on multiple criteria.`),args:[k(`sum_range (range)`,j(`The range to sum.`)),k(`criteria_range (any, range, repeating)`,j(`Range to check.`)),k(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(e,...t){let n=0;return vo(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n+=i)},this.locale),n},isExported:!0},iK={description:j(`Tangent of an angle provided in radians.`),args:[k(`angle (number)`,j(`The angle to find the tangent of, in radians.`))],compute:function(e){return Math.tan(I(e,this.locale))},isExported:!0},aK={description:j(`Hyperbolic tangent of any real number.`),args:[k(`value (number)`,j(`Any real value to calculate the hyperbolic tangent of.`))],compute:function(e){return Math.tanh(I(e,this.locale))},isExported:!0};function oK(e,t){return t===0?Math.trunc(e):(Number.isInteger(t)||(t=Math.trunc(t)),Math.trunc(e*10**t)/10**t)}let sK={description:j(`Truncates a number.`),args:[k(`value (number)`,j(`The value to be truncated.`)),k(`places (number, default=0)`,j(`The number of significant digits to the right of the decimal point to retain.`))],compute:function(e,t={value:0}){return{value:oK(I(e,this.locale),I(t,this.locale)),format:e?.format}},isExported:!0},cK={description:j(`Rounds a number down to the nearest integer that is less than or equal to it.`),args:[k(`value (number)`,j(`The number to round down to the nearest integer.`))],compute:function(e){return Math.floor(I(e,this.locale))},isExported:!0};var lK=l({AVEDEV:()=>yK,AVERAGE:()=>bK,AVERAGEA:()=>wK,AVERAGEIF:()=>TK,AVERAGEIFS:()=>EK,AVERAGE_WEIGHTED:()=>CK,CORREL:()=>JK,COUNT:()=>DK,COUNTA:()=>OK,COVAR:()=>kK,COVARIANCE_P:()=>AK,COVARIANCE_S:()=>jK,FORECAST:()=>MK,GROWTH:()=>NK,INTERCEPT:()=>PK,LARGE:()=>FK,LINEST:()=>IK,LOGEST:()=>LK,MATTHEWS:()=>RK,MAX:()=>zK,MAXA:()=>BK,MAXIFS:()=>VK,MEDIAN:()=>HK,MIN:()=>UK,MINA:()=>WK,MINIFS:()=>GK,PEARSON:()=>qK,PERCENTILE:()=>YK,PERCENTILE_EXC:()=>XK,PERCENTILE_INC:()=>ZK,POLYFIT_COEFFS:()=>QK,POLYFIT_FORECAST:()=>$K,QUARTILE:()=>eq,QUARTILE_EXC:()=>tq,QUARTILE_INC:()=>nq,RANK:()=>rq,RSQ:()=>iq,SLOPE:()=>aq,SMALL:()=>oq,SPEARMAN:()=>sq,STDEV:()=>cq,STDEVA:()=>dq,STDEVP:()=>fq,STDEVPA:()=>pq,STDEV_P:()=>lq,STDEV_S:()=>uq,STEYX:()=>mq,TREND:()=>hq,VAR:()=>gq,VARA:()=>yq,VARP:()=>bq,VARPA:()=>xq,VAR_P:()=>_q,VAR_S:()=>vq});let uK=[{value:!0,label:j(`b is calculated normally`)},{value:!1,label:j(`b is forced to 1`)}],dK=[{value:!1,label:j(`do not return additional regression statistics`)},{value:!0,label:j(`return additional regression statistics`)}],fK=[{value:1,label:j(`order 1 (Linear)`)},{value:2,label:j(`order 2 (Quadratic)`)},{value:3,label:j(`order 3 (Cubic)`)},{value:4,label:j(`order 4 (Quartic)`)},{value:5,label:j(`order 5 (Quintic)`)},{value:6,label:j(`order 6 (Sextic)`)}],pK=[{value:!0,label:j(`Compute intercept`)},{value:!1,label:j(`Force intercept to 0`)}],mK=[{value:0,label:j(`Minimum value`)},{value:1,label:j(`First quartile (25th percentile)`)},{value:2,label:j(`Median value (50th percentile)`)},{value:3,label:j(`Third quartile (75th percentile)`)},{value:4,label:j(`Maximum value`)}];function hK(e,t){let n=[],r=[],i=0,a=0;to([e],e=>{n.push(e),i+=1}),to([t],e=>{r.push(e),a+=1}),uh(i===a,j(`[[FUNCTION_NAME]] has mismatched argument count %s vs %s.`,i,a));let o=[],s=[];for(let e=0;e<i;e++){let t=n[e]?.value,i=r[e]?.value;typeof t==`number`&&typeof i==`number`&&(s.push(t),o.push(i))}return{flatDataX:o,flatDataY:s}}function gK(e,t,n){let{flatDataX:r,flatDataY:i}=hK(e,t),a=i.length;dh(a),n&&dh(a-1);let o=0,s=0;for(let e=0;e<a;e++)o+=i[e],s+=r[e];let c=o/a,l=s/a,u=0;for(let e=0;e<a;e++)u+=(i[e]-c)*(r[e]-l);return u/(a-+!!n)}function _K(e,t,n,r){let i=0,a=n?oo:ao,o=a(e,(e,t)=>(i+=1,e+t),0,r);dh(i),t&&dh(i-1);let s=o/i;return a(e,(e,t)=>e+(t-s)**2,0,r)/(i-+!!t)}function vK(e,t,n,r){let i=I(t,r);uh(n?0<=i&&i<=1:0<i&&i<1,j(`Function [[FUNCTION_NAME]] parameter 2 value is out of range.`));let a=[],o,s=0;return to(e,e=>{let t=e?.value;typeof t==`number`&&(o=yo(a,e,`nextSmaller`,`asc`,a.length,(e,t)=>e[t]),a.splice(o+1,0,t),s++)}),uh(s!==0,Eo),n||uh(1/(s+1)<=i&&i<=s/(s+1),j(`Function [[FUNCTION_NAME]] parameter 2 value is out of range.`)),La(a,i,n)}let yK={description:j(`Average magnitude of deviations from mean.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){let t=0,n=ao(e,(e,n)=>(t+=1,e+n),0,this.locale);if(t===0)return new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`));let r=n/t;return ao(e,(e,t)=>e+Math.abs(r-t),0,this.locale)/t},isExported:!0},bK={description:j(`Numerical average value in a dataset, ignoring text.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the average value.`))],compute:function(...e){return{value:wh(e,this.locale),format:za(e[0])}},isExported:!0},xK=j(`[[FUNCTION_NAME]] has mismatched range sizes.`),SK=j(`[[FUNCTION_NAME]] expects the weight to be positive or equal to 0.`),CK={description:j(`Weighted average.`),args:[k(`values (number, range<number>, repeating)`,j(`Value to average.`)),k(`weights (number, range<number>, repeating)`,j(`Weight for each corresponding value.`))],compute:function(...e){let t=0,n=0;for(let r=0;r<e.length-1;r+=2){let i=e[r],a=e[r+1];if(!ph(i,a))return new N(xK);if(Je(i))for(let e=0;e<i.length;e++)for(let r=0;r<i[0].length;r++){let o=i[e][r].value,s=Je(a)?a?.[e][r].value:I(a,this.locale),c=typeof o==`number`,l=typeof s==`number`;if(c&&l){if(s<0)return new N(SK);t+=o*s,n+=s;continue}if(c!==l)return new N(j(`[[FUNCTION_NAME]] expects number values.`))}else{let e=I(i,this.locale),r=Je(a)?a?.[0][0].value:I(a,this.locale);if(typeof r==`number`){if(r<0)return new N(SK);t+=e*r,n+=r}}}return n===0?new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:t/n,format:za(e[0])}}},wK={description:j(`Numerical average value in a dataset.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the average value.`))],compute:function(...e){let t=0,n=oo(e,(e,n)=>(t+=1,e+n),0,this.locale);return t===0?new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):{value:n/t,format:za(e[0])}},isExported:!0},TK={description:j(`Average of values depending on criteria.`),args:[k(`criteria_range (number, range<number>)`,j(`The range to check against criterion.`)),k(`criterion (string)`,j(`The pattern or test to apply to criteria_range.`)),k(`average_range (number, range<number>, default=criteria_range)`,j(`The range to average. If not included, criteria_range is used for the average instead.`))],compute:function(e,t,n){let r=B(n===void 0?e:n),i=0,a=0;return vo([e,t],(e,t)=>{let n=r[e]?.[t]?.value;typeof n==`number`&&(i+=1,a+=n)},this.locale),i===0?new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):a/i},isExported:!0},EK={description:j(`Average of values depending on multiple criteria.`),args:[k(`average_range (range)`,j(`The range to average.`)),k(`criteria_range (any, range, repeating)`,j(`Range to check.`)),k(`criterion (string, repeating)`,j(`Criterion to check.`))],compute:function(e,...t){let n=B(e),r=0,i=0;return vo(t,(e,t)=>{let a=n[e]?.[t]?.value;typeof a==`number`&&(r+=1,i+=a)},this.locale),r===0?new Vi(j(`Evaluation of function [[FUNCTION_NAME]] caused a divide by zero error.`)):i/r},isExported:!0},DK={description:j(`The number of numeric values in dataset.`),args:[k(`value (number, any, range<number>, repeating)`,j(`Value or range to consider when counting.`))],compute:function(...e){return Eh(e,this.locale)},isExported:!0},OK={description:j(`The number of values in a dataset.`),args:[k(`value (any, range, repeating)`,j(`Value or range to consider when counting.`))],compute:function(...e){return Dh(e)},isExported:!0},kK={description:j(`The covariance of a dataset.`),args:[k(`data_y (any, range)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (any, range)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return gK(e,t,!1)},isExported:!0},AK={description:j(`The covariance of a dataset.`),args:[k(`data_y (any, range)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (any, range)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return gK(e,t,!1)},isExported:!0},jK={description:j(`The sample covariance of a dataset.`),args:[k(`data_y (any, range)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (any, range)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return gK(e,t,!0)},isExported:!0},MK={description:j(`Calculates the expected y-value for a specified x based on a linear regression of a dataset.`),args:[k(`x (number, range<number>)`,j(`The value(s) on the x-axis to forecast.`)),k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t,n){let{flatDataX:r,flatDataY:i}=hK(t,n);return r.length===0||i.length===0?new Ri(Eo):Lh([i],[r],co(B(e),e=>I(e,this.locale)),!0)},isExported:!0},NK={description:j(`Fits points to exponential growth trend.`),args:[k(`known_data_y (range<number>)`,j(`The array or range containing dependent (y) values that are already known, used to curve fit an ideal exponential growth curve.`)),k(`known_data_x (range<number>, default={1;2;3;...})`,j(`The values of the independent variable(s) corresponding with known_data_y.`)),k(`new_data_x (any, range, default=known_data_x)`,j(`The data points to return the y values for on the ideal curve fit.`)),k(`b (boolean, default=TRUE)`,j(`Given a general exponential form of y = b*m^x for a curve fit, calculates b if TRUE or forces b to be 1 and only calculates the m values if FALSE.`),uK)],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new N(Do(`known_data_y`)):Fh(Lh(Ih(Ka(e,`known_data_y`)),Ka(t,`known_data_x`),Ka(n,`new_data_y`),R(r)))}},PK={description:j(`Compute the intercept of the linear regression.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=hK(e,t);if(n.length===0||r.length===0)return new Ri(Eo);let[[],[i]]=jh([n],[r]);return i},isExported:!0},FK={description:j(`Nth largest element from a data set.`),args:[k(`data (any, range)`,j(`Array or range containing the dataset to consider.`)),k(`n (number)`,j(`The rank from largest to smallest of the element to return.`))],compute:function(e,t){let n=Math.trunc(I(t?.value,this.locale)),r=[],i,a=0;to([e],e=>{typeof e?.value==`number`&&(i=yo(r,e,`nextSmaller`,`asc`,r.length,(e,t)=>e[t].value),r.splice(i+1,0,e),a++,a>n&&(r.shift(),a--))});let o=r.shift();return o===void 0?new N(Eo):a<n?new N(j(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},IK={description:j(`Given partial data about a linear trend, calculates various parameters about the ideal linear trend using the least-squares method.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>, default={1;2;3;...})`,j(`The range representing the array or matrix of independent data.`)),k(`calculate_b (boolean, default=TRUE)`,j(`A flag specifying whether to compute the slope or not`),uK),k(`verbose (boolean, default=FALSE)`,j(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`),dK)],compute:function(e,t=[[]],n={value:!0},r={value:!1}){return e.length===0||e[0].length===0?new N(Do(`data_y`)):jh(Ka(t,`data_x`),Ka(e,`data_y`),R(n),R(r))},isExported:!0},LK={description:j(`Given partial data about an exponential growth curve, calculates various parameters about the best fit ideal exponential growth curve.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>, optional, default={1;2;3;...})`,j(`The range representing the array or matrix of independent data.`)),k(`calculate_b (boolean, default=TRUE)`,j(`A flag specifying whether to compute the slope or not`),uK),k(`verbose (boolean, default=FALSE)`,j(`A flag specifying whether to return additional regression statistics or only the linear coefficients and the y-intercept`),dK)],compute:function(e,t=[[]],n={value:!0},r={value:!1}){if(e.length===0||e[0].length===0)return new N(Do(`data_y`));let i=jh(Ka(t,`data_x`),Ih(Ka(e,`data_y`)),R(n),R(r));for(let e=0;e<i.length;e++)i[e][0]=Math.exp(i[e][0]);return i},isExported:!0},RK={description:j(`Compute the Matthews correlation coefficient of a dataset.`),args:[k(`data_x (range)`,j(`The range representing the array or matrix of observed data.`)),k(`data_y (range)`,j(`The range representing the array or matrix of predicted data.`))],compute:function(e,t){let n=e.flat(),r=t.flat();if(Ch(n,r),n.length===0||r.length===0)return new Ri(Eo);let i=n.length,a=0,o=0,s=0,c=0;for(let e=0;e<i;++e){let t=R(n[e]);t===R(r[e])?t?o++:a++:t?c++:s++}return(o*a-s*c)/Math.sqrt((o+s)*(o+c)*(a+s)*(a+c))},isExported:!1},zK={description:j(`Maximum value in a numeric dataset.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the maximum value.`))],compute:function(...e){return Oh(e,this.locale)},isExported:!0},BK={description:j(`Maximum numeric value in a dataset.`),args:[k(`value (any, range, repeating)`,j(`Value or range to consider when calculating the maximum value.`))],compute:function(...e){let t=oo(e,(e,t)=>Math.max(t,e),-1/0,this.locale);return{value:t===-1/0?0:t,format:za(e[0])}},isExported:!0},VK={description:j(`Returns the maximum value in a range of cells, filtered by a set of criteria.`),args:[k(`range (range)`,j(`The range of cells from which the maximum will be determined.`)),k(`criteria_range (any, range, repeating)`,j(`Range to evaluate criteria.`)),k(`criterion (string, repeating)`,j(`Criteria to check.`))],compute:function(e,...t){let n=-1/0;return vo(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n=n<i?i:n)},this.locale),n===-1/0?0:n},isExported:!0},HK={description:j(`Median value in a numeric dataset.`),args:[k(`value (any, range, repeating)`,j(`Value or range to consider when calculating the median value.`))],compute:function(...e){let t=[];return no(e,e=>{t.push(e)},this.locale),{value:vK(t,{value:.5},!0,this.locale),format:za(t[0])}},isExported:!0},UK={description:j(`Minimum value in a numeric dataset.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the minimum value.`))],compute:function(...e){return kh(e,this.locale)},isExported:!0},WK={description:j(`Minimum numeric value in a dataset.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to consider when calculating the minimum value.`))],compute:function(...e){let t=oo(e,(e,t)=>Math.min(t,e),1/0,this.locale);return{value:t===1/0?0:t,format:za(e[0])}},isExported:!0},GK={description:j(`Returns the minimum value in a range of cells, filtered by a set of criteria.`),args:[k(`range (range)`,j(`The range of cells from which the minimum will be determined.`)),k(`criteria_range (any, range, repeating)`,j(`Range to evaluate criteria.`)),k(`criterion (string, repeating)`,j(`Criterion to check.`))],compute:function(e,...t){let n=1/0;return vo(t,(t,r)=>{let i=e[t]?.[r]?.value;typeof i==`number`&&(n=n>i?i:n)},this.locale),n===1/0?0:n},isExported:!0};function KK(e,t){let{flatDataX:n,flatDataY:r}=hK(e,t);if(n.length===0||r.length===0)return new Ri(Eo);let i=n.length,a=0,o=0,s=0,c=0,l=0;for(let e=0;e<i;e++){let t=n[e],i=r[e];a+=t,o+=i,s+=t*i,c+=t*t,l+=i*i}return(i*s-a*o)/Math.sqrt((i*c-a*a)*(i*l-o*o))}let qK={description:j(`Compute the Pearson product-moment correlation coefficient of a dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){return KK(e,t)},isExported:!0},JK=qK,YK={description:j(`Value at a given percentile of a dataset.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`percentile (number)`,j(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return ZK.compute.bind(this)(e,t)},isExported:!0},XK={description:j(`Value at a given percentile of a dataset exclusive of 0 and 1.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`percentile (number)`,j(`The percentile, exclusive of 0 and 1, whose value within 'data' will be calculated and returned.`))],compute:function(e,t){return{value:vK([e],t,!1,this.locale),format:za(e)}},isExported:!0},ZK={description:j(`Value at a given percentile of a dataset.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`percentile (number)`,j(`The percentile whose value within data will be calculated and returned.`))],compute:function(e,t){return{value:vK([e],t,!0,this.locale),format:za(e)}},isExported:!0},QK={description:j(`Compute the coefficients of polynomial regression of the dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`)),k(`order (number)`,j(`The order of the polynomial to fit the data, between 1 and 6.`),fK),k(`intercept (boolean, default=TRUE)`,j(`A flag specifying whether to compute the intercept or not.`),pK)],compute:function(e,t,n,r={value:!0}){let{flatDataX:i,flatDataY:a}=hK(e,t);return i.length===0||a.length===0?new Ri(Eo):Mh(a,i,I(n,this.locale),R(r))},isExported:!1},$K={description:j(`Predict value by computing a polynomial regression of the dataset.`),args:[k(`x (number, range<number>)`,j(`The value(s) on the x-axis to forecast.`)),k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`)),k(`order (number)`,j(`The order of the polynomial to fit the data, between 1 and 6.`),fK),k(`intercept (boolean, default=TRUE)`,j(`A flag specifying whether to compute the intercept or not.`),pK)],compute:function(e,t,n,r,i={value:!0}){let a=I(r,this.locale),{flatDataX:o,flatDataY:s}=hK(t,n);if(o.length===0||s.length===0)return new Ri(Eo);let c=Mh(s,o,a,R(i)).flat();return co(B(e),e=>Ph(c,I(e,this.locale),a))},isExported:!1},eq={description:j(`Value nearest to a specific quartile of a dataset.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`quartile_number (number)`,j(`Which quartile value to return.`),mK)],compute:function(e,t){return nq.compute.bind(this)(e,t)},isExported:!0},tq={description:j(`Value nearest to a specific quartile of a dataset exclusive of 0 and 4.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`quartile_number (number)`,j(`Which quartile value, exclusive of 0 and 4, to return.`),[{value:1,label:j(`First quartile (25th percentile)`)},{value:2,label:j(`Median value (50th percentile)`)},{value:3,label:j(`Third quartile (75th percentile)`)}])],compute:function(e,t){let n={value:.25*Math.trunc(I(t,this.locale))};return{value:vK([e],n,!1,this.locale),format:za(e)}},isExported:!0},nq={description:j(`Value nearest to a specific quartile of a dataset.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`quartile_number (number)`,j(`Which quartile value to return.`),mK)],compute:function(e,t){let n={value:.25*Math.trunc(I(t,this.locale))};return{value:vK([e],n,!0,this.locale),format:za(e)}},isExported:!0},rq={description:j(`Returns the rank of a specified value in a dataset.`),args:[k(`value (number)`,j(`The value whose rank will be determined.`)),k(`data (range)`,j(`The range containing the dataset to consider.`)),k(`is_ascending (boolean, default=FALSE)`,j(`Whether to consider the values in data in descending or ascending order.`),[{value:!1,label:j(`Descending`)},{value:!0,label:j(`Ascending`)}])],compute:function(e,t,n={value:!1}){let r=R(n),i=I(e,this.locale),a=1,o=!1;for(let e of t)for(let t of e){if(typeof t.value!=`number`)continue;let e=I(t,this.locale);e===i?o=!0:e>i!==r&&a++}return o?a:new Ri(j(`Value not found in the given data.`))},isExported:!0},iq={description:j(`Compute the square of r, the Pearson product-moment correlation coefficient of a dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let n=KK(e,t);if(n instanceof Error)throw n;return n**2},isExported:!0},aq={description:j(`Compute the slope of the linear regression.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=hK(e,t);if(n.length===0||r.length===0)return new Ri(Eo);let[[i]]=jh([n],[r]);return i},isExported:!0},oq={description:j(`Nth smallest element in a data set.`),args:[k(`data (any, range)`,j(`The array or range containing the dataset to consider.`)),k(`n (number)`,j(`The rank from smallest to largest of the element to return.`))],compute:function(e,t){let n=Math.trunc(I(t?.value,this.locale)),r=[],i,a=0;to([e],e=>{typeof e?.value==`number`&&(i=yo(r,e,`nextSmaller`,`asc`,r.length,(e,t)=>e[t].value),r.splice(i+1,0,e),a++,a>n&&(r.pop(),a--))});let o=r.pop();return o===void 0?new N(Eo):a<n?new N(j(`Function [[FUNCTION_NAME]] parameter 2 value (%s) is out of range.`,n)):o},isExported:!0},sq={description:j(`Compute the Spearman rank correlation coefficient of a dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=hK(t,e);if(n.length===0||r.length===0)return new Ri(Eo);let i=n.length,a=n.map((e,t)=>[e,r[t]]);a.sort((e,t)=>e[0]-t[0]);for(let e=0;e<i;++e)a[e][0]=e;a.sort((e,t)=>e[1]-t[1]);let o=0;for(let e=0;e<i;++e)o+=(a[e][0]-e)**2;return 1-6*o/(i**3-i)},isExported:!1},cq={description:j(`Standard deviation.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(gq.compute.bind(this)(...e))},isExported:!0},lq={description:j(`Standard deviation of entire population.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(_q.compute.bind(this)(...e))},isExported:!0},uq={description:j(`Standard deviation.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(vq.compute.bind(this)(...e))},isExported:!0},dq={description:j(`Standard deviation of sample (text as 0).`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return Math.sqrt(yq.compute.bind(this)(...e))},isExported:!0},fq={description:j(`Standard deviation of entire population.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(bq.compute.bind(this)(...e))},isExported:!0},pq={description:j(`Standard deviation of entire population (text as 0).`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return Math.sqrt(xq.compute.bind(this)(...e))},isExported:!0},mq={description:j(`Calculates the standard error of the predicted y-value for each x in the regression of a dataset.`),args:[k(`data_y (range<number>)`,j(`The range representing the array or matrix of dependent data.`)),k(`data_x (range<number>)`,j(`The range representing the array or matrix of independent data.`))],compute:function(e,t){let{flatDataX:n,flatDataY:r}=hK(e,t);return n.length===0||r.length===0?new Ri(Eo):jh([n],[r],!0,!0)[1][2]},isExported:!0},hq={description:j(`Fits points to linear trend derived via least-squares.`),args:[k(`known_data_y (number, range<number>)`,j(`The array or range containing dependent (y) values that are already known, used to curve fit an ideal linear trend.`)),k(`known_data_x (number, range<number>, optional, default={1;2;3;...})`,j(`The values of the independent variable(s) corresponding with known_data_y.`)),k(`new_data_x (number, range<number>, optional, default=known_data_x)`,j(`The data points to return the y values for on the ideal curve fit.`)),k(`b (boolean, optional, default=TRUE)`,j(`Given a general linear form of y = m*x+b for a curve fit, calculates b if TRUE or forces b to be 0 and only calculates the m values if FALSE, i.e. forces the curve fit to pass through the origin.`),uK)],compute:function(e,t=[[]],n=[[]],r={value:!0}){return e.length===0||e[0].length===0?new N(Do(`known_data_y`)):Lh(Ka(e,`known_data_y`),Ka(t,`known_data_x`),Ka(n,`new_data_y`),R(r))}},gq={description:j(`Variance.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return _K(e,!0,!1,this.locale)},isExported:!0},_q={description:j(`Variance of entire population.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return _K(e,!1,!1,this.locale)},isExported:!0},vq={description:j(`Variance.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return _K(e,!0,!1,this.locale)},isExported:!0},yq={description:j(`Variance of sample (text as 0).`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the sample.`))],compute:function(...e){return _K(e,!0,!0,this.locale)},isExported:!0},bq={description:j(`Variance of entire population.`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return _K(e,!1,!1,this.locale)},isExported:!0},xq={description:j(`Variance of entire population (text as 0).`),args:[k(`value (number, range<number>, repeating)`,j(`Value or range to include in the population.`))],compute:function(...e){return _K(e,!1,!0,this.locale)},isExported:!0};var Sq=l({DAVERAGE:()=>Tq,DCOUNT:()=>Eq,DCOUNTA:()=>Dq,DGET:()=>Oq,DMAX:()=>kq,DMIN:()=>Aq,DPRODUCT:()=>jq,DSTDEV:()=>Mq,DSTDEVP:()=>Nq,DSUM:()=>Pq,DVAR:()=>Fq,DVARP:()=>Iq});function Cq(e,t,n,r){let i=new Map,a=e.length;for(let t=a-1;t>=0;t--)i.set(L(e[t][0]).toUpperCase(),t);let o=t?.value;if(typeof o!=`number`&&typeof o!=`string`)throw new N(j(`The field must be a number or a string`));let s;if(typeof o==`number`){if(s=Math.trunc(o)-1,s<0||a-1<s)throw new N(j(`The field (%(fieldValue)s) must be one of %(dimRowDB)s or must be a number between 1 and %s inclusive.`,{fieldValue:o.toString(),dimRowDB:a.toString()}))}else{let e=L(t).toUpperCase();if(s=i.get(e)??-1,s===-1)throw new N(j(`The field (%s) must be one of %s.`,L(t),[...i.keys()].toString()))}let c=n[0].length;if(c<2)throw new N(j(`The criteria range contains %s row, it must be at least 2 rows.`,c.toString()));let l=new Set,u=e[0].length;for(let t=1;t<c;t++){let a=[],o=!0;for(let r=0;r<n.length;r++){let s=L(n[r][0]).toUpperCase(),c=i.get(s),l=n[r][t];if(l.value!==null)if(c!==void 0)a.push([e[c].slice(1,u)]),a.push(l);else{o=!1;break}}if(o)if(a.length>0)vo(a,(e,t)=>{l.add(t)},r,!0);else{l=new Set(Array(u-1).keys());break}}let d=e[s];return[...l].map(e=>d[e+1])}let wq=[k(`database (range)`,j(`The array or range containing the data to consider, structured in such a way that the first row contains the labels for each column's values.`)),k(`field (number, string)`,j(`Indicates which column in database contains the values to be extracted and operated on.`)),k(`criteria (range)`,j(`An array or range containing zero or more criteria to filter the database values by before operating.`))],Tq={description:j(`Average of a set of values from a table-like range.`),args:wq,compute:function(e,t,n){let r=Cq(e,t,n,this.locale);return bK.compute.bind(this)([r])},isExported:!0},Eq={description:j(`Counts values from a table-like range.`),args:wq,compute:function(e,t,n){let r=Cq(e,t,n,this.locale);return DK.compute.bind(this)([r])},isExported:!0},Dq={description:j(`Counts values and text from a table-like range.`),args:wq,compute:function(e,t,n){let r=Cq(e,t,n,this.locale);return OK.compute.bind(this)([r])},isExported:!0},Oq={description:j(`Single value from a table-like range.`),args:wq,compute:function(e,t,n){let r=Cq(e,t,n,this.locale);return r.length===1?r[0]:new N(j(`More than one match found in DGET evaluation.`))},isExported:!0},kq={description:j(`Maximum of values from a table-like range.`),args:wq,compute:function(e,t,n){let r=Cq(e,t,n,this.locale);return zK.compute.bind(this)([r])},isExported:!0},Aq={description:j(`Minimum of values from a table-like range.`),args:wq,compute:function(e,t,n){let r=Cq(e,t,n,this.locale);return UK.compute.bind(this)([r])},isExported:!0},jq={description:j(`Product of values from a table-like range.`),args:wq,compute:function(e,t,n){let r=Cq(e,t,n,this.locale);return RG.compute.bind(this)([r])},isExported:!0},Mq={description:j(`Standard deviation of population sample from table.`),args:wq,compute:function(e,t,n){let r=Cq(e,t,n,this.locale);return cq.compute.bind(this)([r])},isExported:!0},Nq={description:j(`Standard deviation of entire population from table.`),args:wq,compute:function(e,t,n){let r=Cq(e,t,n,this.locale);return fq.compute.bind(this)([r])},isExported:!0},Pq={description:j(`Sum of values from a table-like range.`),args:wq,compute:function(e,t,n){let r=Cq(e,t,n,this.locale);return tK.compute.bind(this)([r])},isExported:!0},Fq={description:j(`Variance of population sample from table-like range.`),args:wq,compute:function(e,t,n){let r=Cq(e,t,n,this.locale);return gq.compute.bind(this)([r])},isExported:!0},Iq={description:j(`Variance of a population from a table-like range.`),args:wq,compute:function(e,t,n){let r=Cq(e,t,n,this.locale);return bq.compute.bind(this)([r])},isExported:!0},Lq=j(`The cashflow_amounts and cashflow_dates ranges must have the same dimensions.`),Rq=j(`There must be both positive and negative values in cashflow_amounts.`),zq=e=>j(`The cost (%s) must be positive or null.`,e),Bq=e=>j(`The cost (%s) must be strictly positive.`,e),Vq=e=>j(`The frequency (%s) must be one of %s`,e,[1,2,4].toString()),Hq=e=>j(`The day_count_convention (%s) must be between 0 and 4 inclusive.`,e),Uq=e=>j(`The depreciation factor (%s) must be strictly positive.`,e),Wq=e=>j(`The discount (%s) must be different from -1.`,e),Gq=e=>j(`The discount (%s) must be strictly positive.`,e),Kq=e=>j(`The discount (%s) must be smaller than 1.`,e),qq=e=>j(`The effective_rate (%s) must be strictly positive.`,e),Jq=e=>j(`The end_period (%s) must be positive or null.`,e),Yq=(e,t)=>j(`The end_period (%(end)s) must be smaller or equal to the life (%(life)s).`,{end:e,life:t}),Xq=e=>j(`All the dates should be greater or equal to the first date in cashflow_dates (%s).`,e),Zq=(e,t)=>j(`The first_period (%(first)s) must be smaller or equal to the last_period (%(last)s).`,{first:e,last:t}),Qq=e=>j(`The first_period (%s) must be strictly positive.`,e),$q=e=>j(`The future_value (%s) must be strictly positive.`,e),eJ=e=>j(`The investment (%s) must be strictly positive.`,e),tJ=e=>j(`The issue (%s) must be positive or null.`,e),nJ=(e,t)=>j(`The last_period (%(last)s) must be smaller or equal to the number_of_periods (%(nPeriods)s).`,{last:e,nPeriods:t}),rJ=e=>j(`The last_period (%s) must be strictly positive.`,e),iJ=e=>j(`The life (%s) must be strictly positive.`,e),aJ=(e,t)=>j(`The maturity (%(maturity)s) must be strictly greater than the settlement (%(settlement)s).`,{maturity:t,settlement:e}),oJ=e=>j(`The month (%s) must be between 1 and 12 inclusive.`,e),sJ=e=>j(`The nominal_rate (%s) must be strictly positive.`,e),cJ=e=>j(`The number_of_periods (%s) must be different from zero.`,e),lJ=e=>j(`The number_of_periods (%s) must be strictly positive.`,e),uJ=e=>j(`The period must be between 1 and number_of_periods (%s)`,e),dJ=(e,t)=>j(`The period (%(period)s) must be less than or equal to %(lifeLimit)s.`,{period:e,lifeLimit:t}),fJ=e=>j(`The period (%s) must be positive or null.`,e),pJ=e=>j(`The periods_by_year (%s) must be strictly positive.`,e),mJ=(e,t)=>j(`The period (%(period)s) must be less than or equal life (%(life)s).`,{period:e,life:t}),hJ=e=>j(`The period (%s) must be strictly positive.`,e),gJ=e=>j(`The present_value (%s) must be strictly positive.`,e),_J=e=>j(`The price (%s) must be strictly positive.`,e),vJ=(e,t)=>j(`The purchase_date (%(purchaseDate)s) must be before the first_period_end (%(firstPeriodEnd)s).`,{purchaseDate:e,firstPeriodEnd:t}),yJ=e=>j(`The purchase_date (%s) must be positive or null.`,e),bJ=e=>j(`The rate_guess (%s) must be strictly greater than -1.`,e),xJ=e=>j(`The rate (%s) must be positive or null.`,e),SJ=e=>j(`The rate (%s) must be strictly positive.`,e),CJ=e=>j(`The redemption (%s) must be strictly positive.`,e),wJ=e=>j(`The salvage (%s) must be positive or null.`,e),TJ=(e,t)=>j(`The salvage (%(salvage)s) must be smaller or equal than the cost (%(cost)s).`,{salvage:e,cost:t}),EJ=(e,t)=>j(`The settlement date (%(settlement)s) must be greater or equal to the issue date (%(issue)s).`,{settlement:e,issue:t}),DJ=(e,t)=>j(`The settlement date (%(settlement)s) must at most one year after the maturity date (%(maturity)s).`,{settlement:e,maturity:t}),OJ=(e,t)=>j(`The settlement date (%(settlement)s) must be strictly greater than the issue date (%(issue)s).`,{settlement:e,issue:t}),kJ=e=>j(`The start_period (%s) must be positive or null.`,e),AJ=(e,t)=>j(`The start_period (%(start)s) must be smaller or equal to the end_period (%(end)s).`,{start:e,end:t}),jJ=e=>j(`The unit (%s) must be strictly positive.`,e),MJ=e=>j(`The yield (%s) must be positive or null.`,e);function NJ(e){return e.some(e=>e>0)&&e.some(e=>e<0)}function PJ(e){return![0,1,2,3,4].includes(e)}function FJ(e){return![1,2,4].includes(e)}function IJ(e,t,n){let r=z(e,n),i=z(t,n),a=z(e,n);return a.setFullYear(r.getFullYear()+1),i.getTime()<=a.getTime()}let LJ=[{value:0,label:j(`US (NASD) 30/360`)},{value:1,label:j(`Actual/Actual`)},{value:2,label:j(`Actual/360`)},{value:3,label:j(`Actual/365`)},{value:4,label:j(`European 30/360`)}];var RJ=l({DATE:()=>BJ,DATEDIF:()=>VJ,DATEVALUE:()=>HJ,DAY:()=>UJ,DAYS:()=>WJ,DAYS360:()=>GJ,EDATE:()=>KJ,EOMONTH:()=>qJ,HOUR:()=>JJ,ISOWEEKNUM:()=>YJ,MINUTE:()=>XJ,MONTH:()=>ZJ,MONTH_END:()=>mY,MONTH_START:()=>pY,NETWORKDAYS:()=>QJ,NETWORKDAYS_INTL:()=>tY,NOW:()=>nY,QUARTER:()=>hY,QUARTER_END:()=>_Y,QUARTER_START:()=>gY,SECOND:()=>rY,TIME:()=>iY,TIMEVALUE:()=>aY,TODAY:()=>oY,WEEKDAY:()=>sY,WEEKNUM:()=>cY,WORKDAY:()=>lY,WORKDAY_INTL:()=>uY,YEAR:()=>dY,YEARFRAC:()=>fY,YEAR_END:()=>yY,YEAR_START:()=>vY}),zJ=function(e){return e.WHOLE_YEARS=`Y`,e.WHOLE_MONTHS=`M`,e.WHOLE_DAYS=`D`,e.DAYS_WITHOUT_WHOLE_MONTHS=`MD`,e.MONTH_WITHOUT_WHOLE_YEARS=`YM`,e.DAYS_BETWEEN_NO_MORE_THAN_ONE_YEAR=`YD`,e}(zJ||{});let BJ={description:j(`Converts year/month/day into a date.`),args:[k(`year (number)`,j(`The year component of the date.`)),k(`month (number)`,j(`The month component of the date.`)),k(`day (number)`,j(`The day component of the date.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=Math.trunc(I(n,this.locale));if(r<0||r>9999)return new N(j(`The year (%s) must be between 0 and 9999 inclusive.`,r.toString()));r<1900&&(r+=1900);let o=ha(new P(r,i-1,a));return o<0?new N(j(`The function [[FUNCTION_NAME]] result must be greater than or equal 01/01/1900.`)):{value:o,format:this.locale.dateFormat}},isExported:!0},VJ={description:j(`Calculates the number of days, months, or years between two dates.`),args:[k(`start_date (date)`,j(`The start date to consider in the calculation. Must be a reference to a cell containing a DATE, a function returning a DATE type, or a number.`)),k(`end_date (date)`,j(`The end date to consider in the calculation. Must be a reference to a cell containing a DATE, a function returning a DATE type, or a number.`)),k(`unit (string)`,j(`A text abbreviation for unit of time.`),[{value:`Y`,label:j(`The number of whole years between start_date and end_date`)},{value:`M`,label:j(`The number of whole months between start_date and end_date`)},{value:`D`,label:j(`The number of days between start_date and end_date`)},{value:`MD`,label:j(`The number of days between start_date and end_date after subtracting whole months`)},{value:`YM`,label:j(`The number of whole months between start_date and end_date after subtracting whole years`)},{value:`YD`,label:j(`The number of days between start_date and end_date, assuming start_date and end_date were no more than one year apart`)}])],compute:function(e,t,n){let r=L(n).toUpperCase();if(!Object.values(zJ).includes(r))return new N(Wa(Object.values(zJ),L(n)));let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=ma(i),s=ma(a);if(a<i)return new N(j(`start_date (%s) should be on or before end_date (%s).`,o.toLocaleDateString(),s.toLocaleDateString()));switch(r){case`Y`:return wa(o,s);case`M`:return Sa(o,s);case`D`:return Ca(o,s);case`YM`:return Sa(o,s)-wa(o,s)*12;case`MD`:let e=s.getDate()-o.getDate();return e<0&&(e=_a(new P(s.getFullYear(),s.getMonth()-1,1))-Math.abs(e)),e;case`YD`:{if(Ta(i,a))return Ca(o,s);let e=new P(o.getFullYear(),s.getMonth(),s.getDate()),t=Ca(o,e);return t<0&&(e.setFullYear(o.getFullYear()+1),t=Ca(o,e)),t}}},isExported:!0},HJ={description:j(`Converts a date string to a date value.`),args:[k(`date_string (string)`,j(`The string representing the date.`))],compute:function(e){let t=L(e),n=ia(t,this.locale);return n===null?new N(j(`The date_string (%s) cannot be parsed to date/time.`,t.toString())):Math.trunc(n.value)},isExported:!0},UJ={description:j(`Day of the month that a specific date falls on.`),args:[k(`date (string)`,j(`The date from which to extract the day.`))],compute:function(e){return z(e,this.locale).getDate()},isExported:!0},WJ={description:j(`Number of days between two dates.`),args:[k(`end_date (date)`,j(`The end of the date range.`)),k(`start_date (date)`,j(`The start of the date range.`))],compute:function(e,t){let n=z(e,this.locale),r=z(t,this.locale),i=n.getTime()-r.getTime();return Math.round(i/Wi)},isExported:!0},GJ={description:j(`Number of days between two dates on a 360-day year (months of 30 days).`),args:[k(`start_date (date)`,j(`The start date to consider in the calculation.`)),k(`end_date (date)`,j(`The end date to consider in the calculation.`)),k(`method (boolean, default=false)`,j(`An indicator of what day count method to use.`),[{value:!1,label:j(`U.S. NASD method (default)`)},{value:!0,label:j(`European method`)}])],compute:function(e,t,n={value:!1}){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=xa(r,i,R(n)?4:0);return Math.sign(i-r)*Math.round(a*360)},isExported:!0},KJ={description:j(`Date a number of months before/after another date.`),args:[k(`start_date (date)`,j(`The date from which to calculate the result.`)),k(`months (number)`,j(`The number of months before (negative) or after (positive) 'start_date' to calculate.`))],compute:function(e,t){return{value:ha(ya(z(e,this.locale),Math.trunc(I(t,this.locale)),!1)),format:this.locale.dateFormat}},isExported:!0},qJ={description:j(`Last day of a month before or after a date.`),args:[k(`start_date (date)`,j(`The date from which to calculate the result.`)),k(`months (number)`,j(`The number of months before (negative) or after (positive) 'start_date' to consider.`))],compute:function(e,t){let n=z(e,this.locale),r=Math.trunc(I(t,this.locale));return{value:ha(new P(n.getFullYear(),n.getMonth()+r+1,0)),format:this.locale.dateFormat}},isExported:!0},JJ={description:j(`Hour component of a specific time.`),args:[k(`time (date)`,j(`The time from which to calculate the hour component.`))],compute:function(e){return z(e,this.locale).getHours()},isExported:!0},YJ={description:j(`ISO week number of the year.`),args:[k(`date (date)`,j(`The date for which to determine the ISO week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.`))],compute:function(e){let t=z(e,this.locale),n=t.getFullYear(),r=1;for(;new P(n,0,r).getDay()!==4;)r+=1;let i=new P(n,0,r-3),a=31;for(;new P(n,11,a).getDay()!==4;)--a;let o=new P(n,11,a+3),s;s=i.getTime()<=t.getTime()?t.getTime()<=o.getTime()?0:1:-1;let c;switch(s){case 0:c=i;break;case 1:c=new P(n,11,a+3+1);break;case-1:let e=1;for(;new P(n-1,0,e).getDay()!==4;)e+=1;c=new P(n-1,0,e-3);break}let l=(t.getTime()-c.getTime())/Wi;return Math.floor(l/7)+1},isExported:!0},XJ={description:j(`Minute component of a specific time.`),args:[k(`time (date)`,j(`The time from which to calculate the minute component.`))],compute:function(e){return z(e,this.locale).getMinutes()},isExported:!0},ZJ={description:j(`Month of the year a specific date falls in`),args:[k(`date (date)`,j(`The date from which to extract the month.`))],compute:function(e){return z(e,this.locale).getMonth()+1},isExported:!0},QJ={description:j(`Net working days between two provided days.`),args:[k(`start_date (date)`,j(`The start date of the period from which to calculate the number of net working days.`)),k(`end_date (date)`,j(`The end date of the period from which to calculate the number of net working days.`)),k(`holidays (date, range<date>, optional)`,j(`A range or array constant containing the date serial numbers to consider holidays.`))],compute:function(e,t,n){return tY.compute.bind(this)(e,t,{value:1},n)},isExported:!0};function $J(e){let t=e?.value;if(typeof t==`string`){uh(t.length===7&&[...t].every(e=>e===`0`||e===`1`),j(`When weekend is a string (%s) it must be composed of "0" or "1".`,t));let e=[];for(let n=0;n<7;n++)t[n]===`1`&&e.push((n+1)%7);return e}if(typeof t==`number`)return uh(1<=t&&t<=7||11<=t&&t<=17,j(`The weekend (%s) must be a string or a number in the range 1-7 or 11-17.`,t.toString())),t<=7?[t-2==-1?6:t-2,t-1]:[t-11];throw new N(j(`The weekend must be a number or a string.`))}let eY=[{value:1,label:j(`Saturday/Sunday are weekends`)},{value:2,label:j(`Sunday/Monday are weekends`)},{value:3,label:j(`Monday/Tuesday are weekends`)},{value:4,label:j(`Tuesday/Wednesday are weekends`)},{value:5,label:j(`Wednesday/Thursday are weekends`)},{value:6,label:j(`Thursday/Friday are weekends`)},{value:7,label:j(`Friday/Saturday are weekends`)},{value:11,label:j(`Sunday is the only weekend`)},{value:12,label:j(`Monday is the only weekend`)},{value:13,label:j(`Tuesday is the only weekend`)},{value:14,label:j(`Wednesday is the only weekend`)},{value:15,label:j(`Thursday is the only weekend`)},{value:16,label:j(`Friday is the only weekend`)},{value:17,label:j(`Saturday is the only weekend`)}],tY={description:j(`Net working days between two dates (specifying weekends).`),args:[k(`start_date (date)`,j(`The start date of the period from which to calculate the number of net working days.`)),k(`end_date (date)`,j(`The end date of the period from which to calculate the number of net working days.`)),k(`weekend (any, default=1)`,j(`A number or string representing which days of the week are considered weekends.`),eY),k(`holidays (date, range<date>, optional)`,j(`A range or array constant containing the dates to consider as holidays.`))],compute:function(e,t,n={value:1},r){let i=z(e,this.locale),a=z(t,this.locale),o=$J(n),s=new Set;r!==void 0&&to([r],e=>{let t=z(e,this.locale);s.add(t.getTime())});let c=i.getTime()>a.getTime(),l=P.fromTimestamp((c?i:a).getTime()),u=P.fromTimestamp((c?a:i).getTime()),d=l.getTime(),f=u.getTime(),p=0;for(;f<=d;)!o.includes(u.getDay())&&!s.has(f)&&(p+=1),u.setDate(u.getDate()+1),f=u.getTime();return c?-p:p},isExported:!0},nY={description:j(`Current date and time as a date value.`),args:[],compute:function(){let e=P.now(),t=e.getTime()-Ui.getTime(),n=e.getHours()/24+e.getMinutes()/1440+e.getSeconds()/86400;return{value:Math.floor(t/Wi)+n,format:sb(this.locale)}},isExported:!0},rY={description:j(`Minute component of a specific time.`),args:[k(`time (date)`,j(`The time from which to calculate the second component.`))],compute:function(e){return z(e,this.locale).getSeconds()},isExported:!0},iY={description:j(`Converts hour/minute/second into a time.`),args:[k(`hour (number)`,j(`The hour component of the time.`)),k(`minute (number)`,j(`The minute component of the time.`)),k(`second (number)`,j(`The second component of the time.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=Math.trunc(I(n,this.locale));return i+=Math.floor(a/60),a=a%60+(a<0?60:0),r+=Math.floor(i/60),i=i%60+(i<0?60:0),r%=24,r<0?new N(j(`The function [[FUNCTION_NAME]] result cannot be negative`)):{value:r/24+i/1440+a/(1440*60),format:this.locale.timeFormat}},isExported:!0},aY={description:j(`Converts a time string into its serial number representation.`),args:[k(`time_string (string)`,j(`The string that holds the time representation.`))],compute:function(e){let t=L(e),n=ia(t,this.locale);if(n===null)return new N(j(`The time_string (%s) cannot be parsed to date/time.`,t));let r=n.value-Math.trunc(n.value);return r<0?1+r:r},isExported:!0},oY={description:j(`Current date as a date value.`),args:[],compute:function(){let e=P.now();return{value:ha(new P(e.getFullYear(),e.getMonth(),e.getDate())),format:this.locale.dateFormat}},isExported:!0},sY={description:j(`Day of the week of the date provided (as number).`),args:[k(`date (date)`,j(`The date for which to determine the day of the week. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),k(`type (number, default=1)`,j(`A number indicating which numbering system to use to represent weekdays. By default, counts starting with Sunday = 1.`),[{value:1,label:j(`Numbers 1 (Sunday) trough 7 (Saturday)`)},{value:2,label:j(`Numbers 1 (Monday) trough 7 (Sunday)`)},{value:3,label:j(`Numbers 0 (Monday) trough 6 (Sunday)`)},{value:11,label:j(`Numbers 1 (Monday) trough 7 (Sunday)`)},{value:12,label:j(`Numbers 1 (Tuesday) trough 7 (Monday)`)},{value:13,label:j(`Numbers 1 (Wednesday) trough 7 (Tuesday)`)},{value:14,label:j(`Numbers 1 (Thursday) trough 7 (Wednesday)`)},{value:15,label:j(`Numbers 1 (Friday) trough 7 (Thursday)`)},{value:16,label:j(`Numbers 1 (Saturday) trough 7 (Friday)`)},{value:17,label:j(`Numbers 1 (Sunday) trough 7 (Saturday)`)}])],compute:function(e,t={value:1}){let n=z(e,this.locale),r=Math.round(I(t,this.locale)),i=n.getDay();if(!(1<=r&&r<=3)&&!(11<=r&&r<=17))return new N(j(`The type (%s) must be between 1 and 3 or between 11 and 17.`,r));switch(r){case 1:return i+1;case 2:return i===0?7:i;case 3:return i===0?6:i-1}let a=r-10,o=(i+1-a+7)%7;return o===0?7:o},isExported:!0},cY={description:j(`Week number of the year.`),args:[k(`date (date)`,j(`The date for which to determine the week number. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),k(`type (number, default=1)`,j(`A number representing the day that a week starts on. Sunday = 1.`),[{value:1,label:j(`Sunday`)},{value:2,label:j(`Monday`)},{value:11,label:j(`Monday`)},{value:12,label:j(`Tuesday`)},{value:13,label:j(`Wednesday`)},{value:14,label:j(`Thursday`)},{value:15,label:j(`Friday`)},{value:16,label:j(`Saturday`)},{value:17,label:j(`Sunday`)},{value:21,label:j(`ISO week number (Monday as first day of the week)`)}])],compute:function(e,t={value:1}){let n=z(e,this.locale),r=Math.round(I(t,this.locale));if(![1,2,11,12,13,14,15,16,17,21].includes(r))return new N(j(`The type (%s) is out of range.`,r.toString()));if(r===21)return YJ.compute.bind(this)(e);let i;i=r===1||r===2?r-1:r-10==7?0:r-10;let a=n.getFullYear(),o=1,s=new P(a,0,o);for(;s.getDay()!==i;)o+=1,s=new P(a,0,o);let c=(n.getTime()-s.getTime())/Wi;return c<0?1:Math.floor(c/7)+(o===1?1:2)},isExported:!0},lY={description:j(`Date after a number of workdays.`),args:[k(`start_date (date)`,j(`The date from which to begin counting.`)),k(`num_days (number)`,j(`The number of working days to advance from start_date. If negative, counts backwards.`)),k(`holidays (date, range<date>, optional)`,j(`A range or array constant containing the dates to consider holidays.`))],compute:function(e,t,n={value:null}){return uY.compute.bind(this)(e,t,{value:1},n)},isExported:!0},uY={description:j(`Date after a number of workdays (specifying weekends).`),args:[k(`start_date (date)`,j(`The date from which to begin counting.`)),k(`num_days (number)`,j(`The number of working days to advance from start_date. If negative, counts backwards.`)),k(`weekend (any, default=1)`,j(`A number or string representing which days of the week are considered weekends.`),eY),k(`holidays (date, range<date>, optional)`,j(`A range or array constant containing the dates to consider holidays.`))],compute:function(e,t,n={value:1},r){let i=z(e,this.locale),a=Math.trunc(I(t,this.locale));if(n.value===`1111111`)return new N(j(`The weekend must be different from '1111111'.`));let o=$J(n),s=new Set;r!==void 0&&to([r],e=>{let t=z(e,this.locale);s.add(t.getTime())});let c=P.fromTimestamp(i.getTime()),l=c.getTime(),u=Math.sign(a),d=Math.abs(a);for(;d>0;)c.setDate(c.getDate()+u),l=c.getTime(),!o.includes(c.getDay())&&!s.has(l)&&--d;let f=l-Ui.getTime();return{value:Math.round(f/Wi),format:this.locale.dateFormat}},isExported:!0},dY={description:j(`Year specified by a given date.`),args:[k(`date (date)`,j(`The date from which to extract the year.`))],compute:function(e){return z(e,this.locale).getFullYear()},isExported:!0},fY={description:j(`Exact number of years between two dates.`),args:[k(`start_date (date)`,j(`The start date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),k(`end_date (date)`,j(`The end date to consider in the calculation. Must be a reference to a cell containing a date, a function returning a date type, or a number.`)),k(`day_count_convention (number, default=0)`,j(`An indicator of what day count method to use.`),LJ)],compute:function(e,t,n={value:0}){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=Math.trunc(I(n,this.locale));return r<0?new N(j(`The start_date (%s) must be positive or null.`,r)):i<0?new N(j(`The end_date (%s) must be positive or null.`,i)):0>a||a>4?new N(j(`The day_count_convention (%s) must be between 0 and 4 inclusive.`,a)):xa(r,i,a)}},pY={description:j(`First day of the month preceding a date.`),args:[k(`date (date)`,j(`The date from which to calculate the result.`))],compute:function(e){let t=z(e,this.locale);return{value:ha(new P(t.getFullYear(),t.getMonth(),1)),format:this.locale.dateFormat}}},mY={description:j(`Last day of the month following a date.`),args:[k(`date (date)`,j(`The date from which to calculate the result.`))],compute:function(e){return qJ.compute.bind(this)(e,{value:0})}},hY={description:j(`Quarter of the year a specific date falls in`),args:[k(`date (date)`,j(`The date from which to extract the quarter.`))],compute:function(e){return Math.ceil((z(e,this.locale).getMonth()+1)/3)}},gY={description:j(`First day of the quarter of the year a specific date falls in.`),args:[k(`date (date)`,j(`The date from which to calculate the start of quarter.`))],compute:function(e){let t=hY.compute.bind(this)(e);return{value:ha(new P(dY.compute.bind(this)(e),(t-1)*3,1)),format:this.locale.dateFormat}}},_Y={description:j(`Last day of the quarter of the year a specific date falls in.`),args:[k(`date (date)`,j(`The date from which to calculate the end of quarter.`))],compute:function(e){let t=hY.compute.bind(this)(e);return{value:ha(new P(dY.compute.bind(this)(e),t*3,0)),format:this.locale.dateFormat}}},vY={description:j(`First day of the year a specific date falls in.`),args:[k(`date (date)`,j(`The date from which to calculate the start of the year.`))],compute:function(e){return{value:ha(new P(dY.compute.bind(this)(e),0,1)),format:this.locale.dateFormat}}},yY={description:j(`Last day of the year a specific date falls in.`),args:[k(`date (date)`,j(`The date from which to calculate the end of the year.`))],compute:function(e){return{value:ha(new P(dY.compute.bind(this)(e)+1,0,0)),format:this.locale.dateFormat}}};var bY=l({DELTA:()=>xY});let xY={description:j(`Compare two numeric values, returning 1 if they're equal.`),args:[k(`number1 (number)`,j(`The first number to compare.`)),k(`number2 (number, default=0)`,j(`The second number to compare.`))],compute:function(e,t={value:0}){return+(I(e,this.locale)===I(t,this.locale))},isExported:!0};var SY=l({FILTER:()=>wY,SORT:()=>TY,SORTN:()=>EY,UNIQUE:()=>DY});function CY(e,t,...n){for(let e=0;e<n.length;e++){let t=e%2==0?`sort_column`:`is_ascending`;uh(n[e]!==void 0,j(`Value for parameter %s is missing in [[FUNCTION_NAME]].`,t))}let r=[],i=[],a=e.length;for(let o=0;o<n.length;o+=2){r.push(R(bh(n[o+1])?.value)?`asc`:`desc`);let s=n[o];if(Je(s)&&(s.length>1||s[0].length>1))uh(s.length===1&&s[0].length===a,j(`Wrong size for %s. Expected a range of size 1x%s. Got %sx%s.`,`sort_column${o+1}`,a,s.length,s[0].length)),i.push(s.flat().map(e=>e.value));else{let n=I(bh(s)?.value,t);if(n<1||n>e[0].length)return e;i.push(e.map(e=>e[n-1].value))}}if(i.length===0)for(let t=0;t<e[0].length;t++)i.push(e.map(e=>e[t].value)),r.push(`asc`);let o={desc:bz(`desc`),asc:bz(`asc`)},s=C(0,e.length);return s.sort((e,t)=>{for(let[n,a]of i.entries()){let i=a[e],s=a[t],c={value:i,type:i===null?`empty`:typeof i==`string`?`text`:typeof i},l={value:s,type:s===null?`empty`:typeof s==`string`?`text`:typeof s},u=o[r[n]](c,l);if(u!==0)return u}return 0}),s.map(t=>e[t])}let wY={description:j(`Returns a filtered version of the source range, returning only rows or columns that meet the specified conditions.`),args:[k(`range (any, range<any>)`,j(`The data to be filtered.`)),k(`condition (boolean, range<boolean>, repeating)`,j(`Column or row containing true or false values corresponding to the range.`))],compute:function(e,...t){let n=B(e),r=t.map(e=>co(B(e),e=>e.value));for(let e of r)if(!fh(e))return new N(j(`The arguments condition must be a single column or row.`));if(!ph(...t))return new N(j(`The arguments conditions must have the same dimensions.`));let i=r.map(e=>e.flat()),a=r[0].length===1?`row`:`col`;if(n=a===`row`?uo(n):n,i.some(e=>e.length!==n.length))return new N(j(`FILTER has mismatched sizes on the range and conditions.`));let o=[];for(let e=0;e<n.length;e++){let t=n[e];i.every(t=>(typeof t[e]==`boolean`||typeof t[e]==`number`)&&t[e])&&o.push(t)}return o.length?a===`row`?uo(o):o:new Ri(j(`No match found in FILTER evaluation`))},isExported:!1},TY={description:j(`Sorts the rows of a given array or range by the values in one or more columns.`),args:[k(`range (range)`,j(`The data to be sorted.`)),k(`sort_column (any, range<number>, repeating, optional)`,j(`The index of the column in range or a range outside of range containing the value by which to sort.`)),k(`is_ascending (boolean, repeating, optional)`,j(`TRUE or FALSE indicating whether to sort sort_column in ascending order. FALSE sorts in descending order.`),[{value:!0,label:j(`Ascending`)},{value:!1,label:j(`Descending`)}])],compute:function(e,...t){return uo(CY(uo(e),this.locale,...t))},isExported:!0},EY={description:j(`Returns the first n items in a data set after performing a sort.`),args:[k(`range (range)`,j(`The data to be sorted.`)),k(`n (number)`,j(`The number of items to return.`)),k(`display_ties_mode (number, default=0)`,j(`A number representing the way to display ties.`)),k(`sort_column (number, range<number>, repeating, optional)`,j(`The index of the column in range or a range outside of range containing the value by which to sort.`)),k(`is_ascending (boolean, repeating, optional)`,j(`TRUE or FALSE indicating whether to sort sort_column in ascending order. FALSE sorts in descending order.`),[{value:!0,label:j(`Ascending`)},{value:!1,label:j(`Descending`)}])],compute:function(e,t,...n){let r=I(t?.value??1,this.locale),i=n.length%2==0?0:I(n[0]?.value,this.locale),a=n.length%2==0?n:n.slice(1);if(r<0)return new N(j(`Wrong value of 'n'. Expected a positive number. Got %s.`,r));if(i<0||i>3)return new N(j(`Wrong value of 'display_ties_mode'. Expected a positive number between 0 and 3. Got %s.`,i));let o=CY(uo(e),this.locale,...a),s=(e,t)=>JSON.stringify(o[e].map(e=>e.value))===JSON.stringify(o[t].map(e=>e.value));switch(i){case 0:return uo(o.slice(0,r));case 1:for(let e=r;e<o.length;e++)if(!s(e,r-1))return uo(o.slice(0,e));return uo(o);case 2:{let e=[o[0]];for(let t=1;t<o.length;t++)for(let n=0;n<t&&!s(t,n);n++)n===t-1&&e.push(o[t]);return uo(e.slice(0,r))}case 3:{let e=[o[0]],t=1;for(let n=1;n<o.length&&(s(n,n-1)||t++,!(t>r));n++)e.push(o[n]);return uo(e)}}},isExported:!1},DY={description:j(`Unique rows in the provided source range.`),args:[k(`range (any, range<any>)`,j(`The data to filter by unique entries.`)),k(`by_column (boolean, default=FALSE)`,j(`Whether to filter the data by columns or by rows.`),[{value:!0,label:j(`Return unique columns`)},{value:!1,label:j(`Return unique rows`)}]),k(`exactly_once (boolean, default=FALSE)`,j(`Whether to return only entries with no duplicates.`),[{value:!0,label:j(`Return items that appear exactly once`)},{value:!1,label:j(`Return every distinct item`)}])],compute:function(e={value:``},t,n){if(!Je(e))return[[e]];let r=R(t?.value)||!1,i=R(n?.value)||!1;r||(e=uo(e));let a=new Map;for(let t of e){let e=JSON.stringify(t.map(e=>e.value)),n=a.get(e);n?n.count++:a.set(e,{data:t,count:1})}let o=[];for(let e of a.values())i&&e.count>1||o.push(e.data);return o.length?r?o:uo(o):new N(j(`No unique values found`))},isExported:!0};var OY=l({ACCRINTM:()=>NY,AMORLINC:()=>PY,COUPDAYBS:()=>IY,COUPDAYS:()=>FY,COUPDAYSNC:()=>LY,COUPNCD:()=>RY,COUPNUM:()=>zY,COUPPCD:()=>BY,CUMIPMT:()=>VY,CUMPRINC:()=>HY,DB:()=>UY,DDB:()=>GY,DISC:()=>KY,DOLLARDE:()=>qY,DOLLARFR:()=>JY,DURATION:()=>YY,EFFECT:()=>XY,FV:()=>QY,FVSCHEDULE:()=>$Y,INTRATE:()=>eX,IPMT:()=>nX,IRR:()=>iX,ISPMT:()=>aX,MDURATION:()=>oX,MIRR:()=>sX,NOMINAL:()=>cX,NPER:()=>lX,NPV:()=>dX,PDURATION:()=>fX,PMT:()=>mX,PPMT:()=>gX,PRICE:()=>vX,PRICEDISC:()=>yX,PRICEMAT:()=>bX,PV:()=>_X,RATE:()=>SX,RECEIVED:()=>CX,RRI:()=>wX,SLN:()=>TX,SYD:()=>EX,TBILLEQ:()=>kX,TBILLPRICE:()=>OX,TBILLYIELD:()=>AX,VDB:()=>jX,XIRR:()=>MX,XNPV:()=>NX,YIELD:()=>PX,YIELDDISC:()=>FX,YIELDMAT:()=>IX});let kY=[{value:1,label:j(`Annual`)},{value:2,label:j(`Semi-annual`)},{value:4,label:j(`Quarterly`)}],AY=[{value:0,label:j(`End of period (default)`)},{value:1,label:j(`Beginning of period`)}],jY=[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),kY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),LJ)];function MY(e,t,n,r,i=1e-10,a){let o=n,s,c,l,u=!1,d=0,f;do{if(l=e(o),isNaN(l)){uh(d<r&&a!==void 0,j(`Function [[FUNCTION_NAME]] didn't find any result.`)),d++,o=a(f),f=o;continue}s=o-l/t(o),c=Math.abs(s-o),o=s,u=c<i||Math.abs(l)<i,uh(d<r,j(`Function [[FUNCTION_NAME]] didn't find any result.`)),d++}while(!u);return o}let NY={description:j(`Accrued interest of security paying at maturity.`),args:[k(`issue (date)`,j(`The date the security was initially issued.`)),k(`maturity (date)`,j(`The maturity date of the security.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),LJ)],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(r,this.locale),c=I(n,this.locale),l=Math.trunc(I(i,this.locale));if(a<0)return new N(tJ(a));if(a>=o)return new N(aJ(a,o));if(PJ(l))return new N(Hq(l));if(s<=0)return new N(CJ(s));if(c<=0)return new N(SJ(c));let u=xa(a,o,l);return s*c*u},isExported:!0},PY={description:j(`Depreciation for an accounting period.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`purchase_date (date)`,j(`The date the asset was purchased.`)),k(`first_period_end (date)`,j(`The date the first period ended.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`period (number)`,j(`The single period within life for which to calculate depreciation.`)),k(`rate (number)`,j(`The deprecation rate.`)),k(`day_count_convention (number, optional)`,j(`An indicator of what day count method to use.`),LJ)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=I(e,this.locale),c=Math.trunc(I(t,this.locale)),l=Math.trunc(I(n,this.locale)),u=I(r,this.locale),d=I(i,this.locale),f=I(a,this.locale),p=Math.trunc(I(o,this.locale));if(s<=0)return new N(Bq(s));if(c<0)return new N(yJ(c));if(u<0)return new N(wJ(u));if(u>s)return new N(TJ(u,s));if(d<0)return new N(fJ(d));if(f<=0)return new N(SJ(f));if(PJ(p))return new N(Hq(p));if(c>l)return new N(vJ(c,l));let m=d<1&&d>0?1:Math.trunc(d),h=s*f,g=xa(c,l,p),_=c===l?h:h*g,v=s-_-h*m;return v>=u?m===0?_:h:u-v<h?h-(u-v):0},isExported:!0},FY={description:j(`Days in coupon period containing settlement date.`),args:jY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(aJ(i,a));if(FJ(o))return new N(Vq(o));if(PJ(s))return new N(Hq(s));if(s===1){let i=BY.compute.bind(this)(e,t,n,r).value,a=RY.compute.bind(this)(e,t,n,r).value;return I(a,this.locale)-I(i,this.locale)}return(s===3?365:360)/o},isExported:!0},IY={description:j(`Days from settlement until next coupon.`),args:jY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(aJ(i,a));if(FJ(o))return new N(Vq(o));if(PJ(s))return new N(Hq(s));let c=BY.compute.bind(this)(e,t,n,r).value,l=I(c,this.locale);if([1,2,3].includes(s))return i-l;if(s===4){let e=xa(l,i,s);return Math.round(e*360)}let u=z(i,this.locale),d=z(l,this.locale),f=d.getFullYear(),p=u.getFullYear(),m=d.getMonth()+1,h=u.getMonth()+1,g=d.getDate(),_=u.getDate();return m===2&&h===2&&va(d)&&va(u)&&(_=30),_===31&&(g===30||g===31)&&(_=30),m===2&&va(d)&&(g=30),g===31&&(g=30),(p-f)*360+(h-m)*30+(_-g)},isExported:!0},LY={description:j(`Days from settlement until next coupon.`),args:jY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(aJ(i,a));if(FJ(o))return new N(Vq(o));if(PJ(s))return new N(Hq(s));let c=RY.compute.bind(this)(e,t,n,r).value,l=I(c,this.locale);if([1,2,3].includes(s))return l-i;if(s===4){let e=xa(i,l,s);return Math.round(e*360)}let u=IY.compute.bind(this)(e,t,n,r);return I(FY.compute.bind(this)(e,t,n,r),this.locale)-I(u,this.locale)},isExported:!0},RY={description:j(`Next coupon date after the settlement date.`),args:jY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(aJ(i,a));if(FJ(o))return new N(Vq(o));if(PJ(s))return new N(Hq(s));let c=12/o,l=zY.compute.bind(this)(e,t,n,r);return{value:ha(ya(z(a,this.locale),-(I(l,this.locale)-1)*c,!0)),format:this.locale.dateFormat}},isExported:!0},zY={description:j(`Number of coupons between settlement and maturity.`),args:jY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(aJ(i,a));if(FJ(o))return new N(Vq(o));if(PJ(s))return new N(Hq(s));let c=1,l=a,u=12/o;for(;l>i;)l=ha(ya(z(l,this.locale),-u,!1)),c++;return c-1},isExported:!0},BY={description:j(`Last coupon date prior to or on the settlement date.`),args:jY,compute:function(e,t,n,r={value:0}){r||=0;let i=Math.trunc(I(e,this.locale)),a=Math.trunc(I(t,this.locale)),o=Math.trunc(I(n,this.locale)),s=Math.trunc(I(r,this.locale));if(i>=a)return new N(aJ(i,a));if(FJ(o))return new N(Vq(o));if(PJ(s))return new N(Hq(s));let c=12/o,l=zY.compute.bind(this)(e,t,n,r);return{value:ha(ya(z(a,this.locale),-l*c,!0)),format:this.locale.dateFormat}},isExported:!0},VY={description:j(`Cumulative interest paid over a set of periods.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`first_period (number)`,j(`The number of the payment period to begin the cumulative calculation.`)),k(`last_period (number)`,j(`The number of the payment period to end the cumulative calculation.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),AY)],compute:function(e,t,n,r,i,a={value:0}){let o=I(r,this.locale),s=I(i,this.locale),c=I(e,this.locale),l=I(n,this.locale),u=I(t,this.locale),d=+!!R(a);if(u<=0)return new N(lJ(u));if(o<=0)return new N(Qq(o));if(s<=0)return new N(rJ(s));if(o>s)return new N(Zq(o,s));if(s>u)return new N(nJ(s,u));if(c<=0)return new N(SJ(c));if(l<=0)return new N(gJ(l));let f=0;for(let e=o;e<=s;e++)f+=tX(c,e,u,l,0,d);return f},isExported:!0},HY={description:j(`Cumulative principal paid over a set of periods.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`first_period (number)`,j(`The number of the payment period to begin the cumulative calculation.`)),k(`last_period (number)`,j(`The number of the payment period to end the cumulative calculation.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),AY)],compute:function(e,t,n,r,i,a={value:0}){let o=I(r,this.locale),s=I(i,this.locale),c=I(e,this.locale),l=I(n,this.locale),u=I(t,this.locale),d=+!!R(a);if(u<=0)return new N(lJ(u));if(o<=0)return new N(Qq(o));if(s<=0)return new N(rJ(s));if(o>s)return new N(Zq(o,s));if(s>u)return new N(nJ(s,u));if(c<=0)return new N(SJ(c));if(l<=0)return new N(gJ(l));let f=0;for(let e=o;e<=s;e++)f+=hX(c,e,u,l,0,d);return f},isExported:!0},UY={description:j(`Depreciation via declining balance method.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),k(`period (number)`,j(`The single period within life for which to calculate depreciation.`)),k(`month (number, optional)`,j(`The number of months in the first year of depreciation.`))],compute:function(e,t,n,r,...i){let a=I(e,this.locale),o=I(t,this.locale),s=I(n,this.locale),c=Math.trunc(I(r,this.locale)),l=i.length?Math.trunc(I(i[0],this.locale)):12,u=s+(l===12?0:1);if(a<0)return new N(zq(a));if(o<0)return new N(wJ(o));if(c<=0)return new N(hJ(c));if(s<=0)return new N(iJ(s));if(1>l||l>12)return new N(oJ(l));if(c>u)return new N(dJ(c,u));let d=l/12,f=1-(o/a)**(1/s);f=Math.round(f*1e3)/1e3;let p=a,m=a*(1-f*d);for(let e=1;e<c;e++)p=m,m=p*(1-f),e===s&&(m=p*(1-f*(1-d)));return{value:p-m,format:`#,##0.00`}},isExported:!0},WY=`#,##0.00`,GY={description:j(`Depreciation via double-declining balance method.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),k(`period (number)`,j(`The single period within life for which to calculate depreciation.`)),k(`factor (number, default=2)`,j(`The factor by which depreciation decreases.`))],compute:function(e,t,n,r,i={value:2}){let a=I(e,this.locale),o=I(t,this.locale),s=I(n,this.locale),c=I(r,this.locale),l=I(i,this.locale);if(a<0)return new N(zq(a));if(o<0)return new N(wJ(o));if(c<=0)return new N(hJ(c));if(s<=0)return new N(iJ(s));if(c>s)return new N(mJ(c,s));if(l<=0)return new N(Uq(l));if(a===0||o>=a)return{value:0,format:WY};let u=l/s;if(u>1)return{value:c===1?a-o:0,format:WY};if(c<=1)return{value:a*u,format:WY};let d=a*(1-u)**(c-1),f=a*(1-u)**c,p=f<o?d-o:d-f;return{value:Math.max(p,0),format:WY}},isExported:!0},KY={description:j(`Discount rate of a security based on price.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`price (number)`,j(`The price at which the security is bought per 100 face value.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),LJ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(n,this.locale),c=I(r,this.locale),l=Math.trunc(I(i,this.locale));if(a>=o)return new N(aJ(a,o));if(PJ(l))return new N(Hq(l));if(s<=0)return new N(_J(s));if(c<=0)return new N(CJ(c));let u=xa(a,o,l);return(c-s)/c/u},isExported:!0},qY={description:j(`Convert a decimal fraction to decimal value.`),args:[k(`fractional_price (number)`,j(`The price quotation given using fractional decimal conventions.`)),k(`unit (number)`,j(`The units of the fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.`))],compute:function(e,t){let n=I(e,this.locale),r=Math.trunc(I(t,this.locale));if(r<=0)return new N(jJ(r));let i=Math.trunc(n);return i+(n-i)*(10**Math.ceil(Math.log10(r))/r)},isExported:!0},JY={description:j(`Convert a decimal value to decimal fraction.`),args:[k(`decimal_price (number)`,j(`The price quotation given as a decimal value.`)),k(`unit (number)`,j(`The units of the desired fraction, e.g. 8 for 1/8ths or 32 for 1/32nds.`))],compute:function(e,t){let n=I(e,this.locale),r=Math.trunc(I(t,this.locale));if(r<=0)return new N(jJ(r));let i=Math.trunc(n);return i+(n-i)*(r/10**Math.ceil(Math.log10(r)))},isExported:!0},YY={description:j(`Number of periods for an investment to reach a value.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`yield (number)`,j(`The expected annual yield of the security.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),kY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),LJ)],compute:function(e,t,n,r,i,a={value:0}){let o=Math.trunc(I(e,this.locale)),s=Math.trunc(I(t,this.locale)),c=I(n,this.locale),l=I(r,this.locale),u=Math.trunc(I(i,this.locale)),d=Math.trunc(I(a,this.locale));if(o>=s)return new N(aJ(o,s));if(FJ(u))return new N(Vq(u));if(PJ(d))return new N(Hq(d));if(c<0)return new N(xJ(c));if(l<0)return new N(MJ(l));let f=xa(o,s,d),p=f-Math.trunc(f)||1/u,m=Math.ceil(f*u),h=c/u,g=l/u,_=0,v=0;for(let e=1;e<=m;e++){let t=(h+ +(e===m))/(1+g)**e;v+=(p+(e-1)/u)*t,_+=t}return _===0?0:v/_},isExported:!0},XY={description:j(`Annual effective interest rate.`),args:[k(`nominal_rate (number)`,j(`The nominal interest rate per year.`)),k(`periods_per_year (number)`,j(`The number of compounding periods per year.`))],compute:function(e,t){let n=I(e,this.locale),r=Math.trunc(I(t,this.locale));return n<=0?new N(sJ(n)):r<=0?new N(pJ(r)):(1+n/r)**+r-1},isExported:!0};function ZY(e,t,n,r,i){return e===0?-(r+n*t):-r*(1+e)**t-n*(1+e*i)*((1+e)**t-1)/e}let QY={description:j(`Future value of an annuity investment.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`payment_amount (number)`,j(`The amount per period to be paid.`)),k(`present_value (number, default=0)`,j(`The current value of the annuity.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),AY)],compute:function(e,t,n,r={value:0},i={value:0}){return r||=0,i||=0,{value:ZY(I(e,this.locale),I(t,this.locale),I(n,this.locale),I(r,this.locale),+!!R(i)),format:`#,##0.00`}},isExported:!0},$Y={description:j(`Future value of principal from series of rates.`),args:[k(`principal (number)`,j(`The amount of initial capital or value to compound against.`)),k(`rate_schedule (number, range<number>)`,j(`A series of interest rates to compound against the principal.`))],compute:function(e,t){let n=I(e,this.locale);return io([t],(e,t)=>e*(1+I(t,this.locale)),n)},isExported:!0},eX={description:j(`Calculates effective interest rate.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`investment (number)`,j(`The amount invested in the security.`)),k(`redemption (number)`,j(`The amount to be received at maturity.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),LJ)],compute:function(e,t,n,r,i={value:0}){let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(r,this.locale),c=I(n,this.locale),l=Math.trunc(I(i,this.locale));if(a>=o)return new N(aJ(a,o));if(c<=0)return new N(eJ(c));if(s<=0)return new N(CJ(s));if(PJ(l))return new N(Hq(l));let u=xa(a,o,l);return(s-c)/c/u},isExported:!0};function tX(e,t,n,r,i,a){return pX(e,n,r,i,a)-hX(e,t,n,r,i,a)}let nX={description:j(`Payment on the principal of an investment.`),args:[k(`rate (number)`,j(`The annualized rate of interest.`)),k(`period (number)`,j(`The amortization period, in terms of number of periods.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),AY)],compute:function(e,t,n,r,i={value:0},a={value:0}){return{value:tX(I(e,this.locale),I(t,this.locale),I(n,this.locale),I(r,this.locale),I(i,this.locale),+!!R(a)),format:`#,##0.00`}},isExported:!0},rX=.1,iX={description:j(`Internal rate of return given periodic cashflows.`),args:[k(`cashflow_amounts (number, range<number>)`,j(`An array or range containing the income or payments associated with the investment.`)),k(`rate_guess (number, default=${rX})`,j(`An estimate for what the internal rate of return will be.`))],compute:function(e,t={value:rX}){let n=I(t,this.locale);if(n<=-1)return new N(bJ(n));let r=!1,i=!1,a=[];if(no([e],({value:e})=>{e>0&&(r=!0),e<0&&(i=!0),a.push(e)},this.locale),!r||!i)return new N(Rq);let o=a.shift();function s(e,t,n){let r=n.length,i=0;return n.reduce((t,n)=>(i++,t+n*e**(r-i)),t*e**r)}function c(e,t,n){let r=n.length,i=0;return n.reduce((t,n)=>(i++,t+n*(r-i)*e**(r-i-1)),t*r*e**(r-1))}function l(e){return s(e,o,a)}function u(e){return c(e,o,a)}return{value:MY(l,u,n+1,20,1e-5)-1,format:`0%`}},isExported:!0},aX={description:j(`Returns the interest paid at a particular period of an investment.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`period (number)`,j(`The period for which you want to view the interest payment.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`))],compute:function(e,t,n,r){let i=I(e,this.locale),a=I(t,this.locale),o=I(n,this.locale),s=I(r,this.locale);return o===0?new N(cJ(o)):-1*(s-a/o*s)*i},isExported:!0},oX={description:j(`Modified Macaulay duration.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`yield (number)`,j(`The expected annual yield of the security.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),kY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`))],compute:function(e,t,n,r,i,a={value:0}){let o=YY.compute.bind(this)(e,t,n,r,i,a),s=I(r,this.locale),c=Math.trunc(I(i,this.locale));return I(o,this.locale)/(1+s/c)},isExported:!0},sX={description:j(`Modified internal rate of return.`),args:[k(`cashflow_amounts (range<number>)`,j(`A range containing the income or payments associated with the investment. The array should contain bot payments and incomes.`)),k(`financing_rate (number)`,j(`The interest rate paid on funds invested.`)),k(`reinvestment_return_rate (number)`,j(`The return (as a percentage) earned on reinvestment of income received from the investment.`))],compute:function(e,t,n){let r=I(t,this.locale),i=I(n,this.locale),a=uo(e).flat().filter(e=>e.value!==null).map(e=>I(e,this.locale)),o=a.length,s=0,c=0;for(let e of C(0,o)){let t=a[e];t>=0?s+=t*(i+1)**(o-e-1):c+=t/(r+1)**e}if(c===0||s===0)return new N(Rq);let l=1/(o-1);return(-s/c)**l-1},isExported:!0},cX={description:j(`Annual nominal interest rate.`),args:[k(`effective_rate (number)`,j(`The effective interest rate per year.`)),k(`periods_per_year (number)`,j(`The number of compounding periods per year.`))],compute:function(e,t){let n=I(e,this.locale),r=Math.trunc(I(t,this.locale));return n<=0?new N(qq(n)):r<=0?new N(pJ(r)):((n+1)**(1/r)-1)*r},isExported:!0},lX={description:j(`Number of payment periods for an investment.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`payment_amount (number)`,j(`The amount of each payment made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),AY)],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=I(e,this.locale),o=I(t,this.locale),s=I(n,this.locale),c=I(r,this.locale),l=+!!R(i);if(a===0)return-(c+s)/o;let u=o*(1+a*l)/a;return Math.log((u-c)/(s+u))/Math.log(1+a)},isExported:!0};function uX(e,t,n,r){let i=0;return ao(n,(t,n)=>(i++,t+n/(1+e)**i),t,r)}let dX={description:j(`The net present value of an investment based on a series of periodic cash flows and a discount rate.`),args:[k(`discount (number)`,j(`The discount rate of the investment over one period.`)),k(`cashflow (number, range<number>, repeating)`,j(`The future cash flows.`))],compute:function(e,...t){let n=I(e,this.locale);return n===-1?new N(Wq(n)):{value:uX(n,0,t,this.locale),format:`#,##0.00`}},isExported:!0},fX={description:j(`Computes the number of periods needed for an investment to reach a value.`),args:[k(`rate (number)`,j(`The rate at which the investment grows each period.`)),k(`present_value (number)`,j(`The investment's current value.`)),k(`future_value (number)`,j(`The investment's desired future value.`))],compute:function(e,t,n){let r=I(e,this.locale),i=I(t,this.locale),a=I(n,this.locale);return r<=0?new N(SJ(r)):i<=0?new N(gJ(i)):a<=0?new N($q(a)):(Math.log(a)-Math.log(i))/Math.log(1+r)},isExported:!0};function pX(e,t,n,r,i){if(t<=0)throw new N(lJ(t));if(e===0)return-(r+n)/t;let a=-(n*(1+e)**t+r);return a=a*e/((1+e*i)*((1+e)**t-1)),a}let mX={description:j(`Periodic payment for an annuity investment.`),args:[k(`rate (number)`,j(`The annualized rate of interest.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),AY)],compute:function(e,t,n,r={value:0},i={value:0}){let a=I(t,this.locale),o=I(e,this.locale),s=+!!R(i),c=I(r,this.locale);return{value:pX(o,a,I(n,this.locale),c,s),format:`#,##0.00`}},isExported:!0};function hX(e,t,n,r,i,a){if(n<=0)throw new N(lJ(n));if(t<=0||t>n)throw new N(uJ(n));let o=pX(e,n,r,i,a);return a===1&&t===1?o:o+-ZY(e,a===0?t-1:t-2,o,r+o*a,0)*e}let gX={description:j(`Payment on the principal of an investment.`),args:[k(`rate (number)`,j(`The annualized rate of interest.`)),k(`period (number)`,j(`The amortization period, in terms of number of periods.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),AY)],compute:function(e,t,n,r,i={value:0},a={value:0}){let o=I(n,this.locale),s=I(e,this.locale),c=I(t,this.locale),l=+!!R(a),u=I(i,this.locale);return{value:hX(s,c,o,I(r,this.locale),u,l),format:`#,##0.00`}},isExported:!0},_X={description:j(`Present value of an annuity investment.`),args:[k(`rate (number)`,j(`The interest rate.`)),k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`payment_amount (number)`,j(`The amount per period to be paid.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),AY)],compute:function(e,t,n,r={value:0},i={value:0}){r||=0,i||=0;let a=I(e,this.locale),o=I(t,this.locale),s=I(n,this.locale),c=I(r,this.locale),l=+!!R(i);return{value:a?-(s*(1+a*l)*((1+a)**o-1)/a+c)/(1+a)**o:-(c+s*o),format:`#,##0.00`}},isExported:!0},vX={description:j(`Price of a security paying periodic interest.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`yield (number)`,j(`The expected annual yield of the security.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),kY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),LJ)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(I(e,this.locale)),c=Math.trunc(I(t,this.locale)),l=I(n,this.locale),u=I(r,this.locale),d=I(i,this.locale),f=Math.trunc(I(a,this.locale)),p=Math.trunc(I(o,this.locale));if(s>=c)return new N(aJ(s,c));if(FJ(f))return new N(Vq(f));if(PJ(p))return new N(Hq(p));if(l<0)return new N(xJ(l));if(u<0)return new N(MJ(u));if(d<=0)return new N(CJ(d));let m=xa(s,c,p)*f,h=Math.ceil(m),g=m-Math.floor(m)||1,_=1+u/f,v=100*l/f;if(h===1)return(v+d)/(g*u/f+1)-v*(1-g);let y=0;for(let e=1;e<=h;e++)y+=v/_**(e-1+g);return d/_**(h-1+g)+y-v*(1-g)},isExported:!0},yX={description:j(`Price of a discount security.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`discount (number)`,j(`The discount rate of the security at time of purchase.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),LJ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(n,this.locale),c=I(r,this.locale),l=Math.trunc(I(i,this.locale));if(a>=o)return new N(aJ(a,o));if(PJ(l))return new N(Hq(l));if(s<=0)return new N(Gq(s));if(c<=0)return new N(CJ(c));let u=xa(a,o,l);return c-s*c*u},isExported:!0},bX={description:j(`Calculates the price of a security paying interest at maturity, based on expected yield.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`issue (date)`,j(`The date the security was initially issued.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`yield (number)`,j(`The expected annual yield of the security.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),LJ)],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(I(e,this.locale)),s=Math.trunc(I(t,this.locale)),c=Math.trunc(I(n,this.locale)),l=I(r,this.locale),u=I(i,this.locale),d=Math.trunc(I(a,this.locale));if(o<=c)return new N(OJ(o,c));if(o>=s)return new N(aJ(o,s));if(PJ(d))return new N(Hq(d));if(l<0)return new N(xJ(l));if(u<0)return new N(MJ(u));let f=xa(o,s,d),p=xa(o,c,d),m=100+xa(c,s,d)*l*100,h=1+f*u,g=p*l*100;return m/h-g},isExported:!0},xX=.1,SX={description:j(`Interest rate of an annuity investment.`),args:[k(`number_of_periods (number)`,j(`The number of payments to be made.`)),k(`payment_per_period (number)`,j(`The amount per period to be paid.`)),k(`present_value (number)`,j(`The current value of the annuity.`)),k(`future_value (number, default=0)`,j(`The future value remaining after the final payment has been made.`)),k(`end_or_beginning (number, default=0)`,j(`The timing of the payment payments are due for each period.`),AY),k(`rate_guess (number, default=${xX})`,j(`An estimate for what the interest rate will be.`))],compute:function(e,t,n,r={value:0},i={value:0},a={value:xX}){let o=I(e,this.locale),s=I(t,this.locale),c=+!!R(i),l=I(a,this.locale)||xX,u=I(r,this.locale),d=I(n,this.locale);return o<=0?new N(lJ(o)):NJ([s,d,u])?l<=-1?new N(bJ(l)):(u-=s*c,d+=s*c,{value:MY(e=>{let t=(1+e)**+o,n=(t-1)/e;return u+d*t+s*n},e=>{let t=(1+e)**(o-1),n=((1+e)**+o-1)/e,r=o*t/e-n/e;return d*o*t+s*r},l,40,1e-5),format:`0%`}):new N(j(`There must be both positive and negative values in [payment_amount, present_value, future_value].`))},isExported:!0},CX={description:j(`Amount received at maturity for a security.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`investment (number)`,j(`The amount invested (irrespective of face value of each security).`)),k(`discount (number)`,j(`The discount rate of the security invested in.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),LJ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(n,this.locale),c=I(r,this.locale),l=Math.trunc(I(i,this.locale));return a>=o?new N(aJ(a,o)):PJ(l)?new N(Hq(l)):s<=0?new N(eJ(s)):c<=0?new N(Gq(c)):s/(1-c*xa(a,o,l))},isExported:!0},wX={description:j(`Computes the rate needed for an investment to reach a specific value within a specific number of periods.`),args:[k(`number_of_periods (number)`,j(`The number of periods.`)),k(`present_value (number)`,j(`The present value of the investment.`)),k(`future_value (number)`,j(`The future value of the investment.`))],compute:function(e,t,n){let r=I(e,this.locale),i=I(t,this.locale),a=I(n,this.locale);return r<=0?new N(lJ(r)):(a/i)**(1/r)-1},isExported:!0},TX={description:j(`Depreciation of an asset using the straight-line method.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`))],compute:function(e,t,n){let r=I(e,this.locale),i=I(t,this.locale),a=I(n,this.locale);return{value:(r-i)/a,format:`#,##0.00`}},isExported:!0},EX={description:j(`Depreciation via sum of years digit method.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),k(`period (number)`,j(`The single period within life for which to calculate depreciation.`))],compute:function(e,t,n,r){let i=I(e,this.locale),a=I(t,this.locale),o=I(n,this.locale),s=I(r,this.locale);if(s<=0)return new N(hJ(s));if(o<=0)return new N(iJ(o));if(s>o)return new N(mJ(s,o));let c=o*(o+1)/2,l=o-s+1;return{value:(i-a)*(l/c),format:`#,##0.00`}},isExported:!0};function DX(e,t,n){return 100*(1-n*xa(e,t,2))}let OX={description:j(`Price of a US Treasury bill.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`discount (number)`,j(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=I(n,this.locale);return r>=i?new N(aJ(r,i)):IJ(r,i,this.locale)?a<=0?new N(Gq(a)):a>=1?new N(Kq(a)):DX(r,i,a):new N(DJ(r,i))},isExported:!0},kX={description:j(`Equivalent rate of return for a US Treasury bill.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`discount (number)`,j(`The discount rate of the bill at time of purchase.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=I(n,this.locale);if(r>=i)return new N(aJ(r,i));if(!IJ(r,i,this.locale))return new N(DJ(r,i));if(a<=0)return new N(Gq(a));if(a>=1)return new N(Kq(a));let o=WJ.compute.bind(this)({value:i},{value:r});if(o<=182)return 365*a/(360-a*o);let s=DX(r,i,a)/100,c=o/(o===366?366:365);return(-2*c+2*Math.sqrt(c**2-(2*c-1)*(1-1/s)))/(2*c-1)},isExported:!0},AX={description:j(`The yield of a US Treasury bill based on price.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`price (number)`,j(`The price at which the security is bought per 100 face value.`))],compute:function(e,t,n){let r=Math.trunc(I(e,this.locale)),i=Math.trunc(I(t,this.locale)),a=I(n,this.locale);if(r>=i)return new N(aJ(r,i));if(!IJ(r,i,this.locale))return new N(DJ(r,i));if(a<=0)return new N(_J(a));let o=xa(r,i,2);return(100-a)/a*(1/o)},isExported:!0},jX={description:j(`Variable declining balance. WARNING : does not handle decimal periods.`),args:[k(`cost (number)`,j(`The initial cost of the asset.`)),k(`salvage (number)`,j(`The value of the asset at the end of depreciation.`)),k(`life (number)`,j(`The number of periods over which the asset is depreciated.`)),k(`start (number)`,j(`Starting period to calculate depreciation.`)),k(`end (number)`,j(`Ending period to calculate depreciation.`)),k(`factor (number, default=2)`,j(`The number of months in the first year of depreciation.`)),k(`no_switch (number, default=false)`,j(`Whether to switch to straight-line depreciation when the depreciation is greater than the declining balance calculation.`),[{value:!1,label:j(`Switch to straight-line depreciation`)},{value:!0,label:j(`Do not switch to straight-line depreciation`)}])],compute:function(e,t,n,r,i,a={value:2},o={value:!1}){a||=0;let s=I(e,this.locale),c=I(t,this.locale),l=I(n,this.locale),u=Math.trunc(I(r,this.locale)),d=Math.trunc(I(i,this.locale)),f=I(a,this.locale),p=R(o);if(s<0)return new N(zq(s));if(c<0)return new N(wJ(c));if(l<=0)return new N(iJ(l));if(u<0)return new N(kJ(u));if(d<0)return new N(Jq(d));if(u>d)return new N(AJ(u,d));if(d>l)return new N(Yq(d,l));if(f<=0)return new N(Uq(f));if(s===0)return 0;if(c>=s)return u<1?s-c:0;let m=f/l;if(m>=1)return u<1?s-c:0;let h=s,g=0,_=0,v=!1;for(let e=0;e<d;e++){if(!v||p){let t=h*m,n=l-e,r=(h-c)/n;!p&&r>t?(v=!0,g=r):g=t}let t=Math.max(h-g,c);e>=u&&(_+=h-t),h=t}return _},isExported:!0},MX={description:j(`Internal rate of return given non-periodic cash flows.`),args:[k(`cashflow_amounts (range<number>)`,j(`An range containing the income or payments associated with the investment.`)),k(`cashflow_dates (range<number>)`,j(`An range with dates corresponding to the cash flows in cashflow_amounts.`)),k(`rate_guess (number, default=${xX})`,j(`An estimate for what the internal rate of return will be.`))],compute:function(e,t,n={value:xX}){let r=I(n,this.locale);if(!ph(e,t))return new N(Lq);let i=e.flat().map(e=>I(e,this.locale)),a=t.flat().map(e=>I(e,this.locale));if(!NJ(i))return new N(Rq);if(a.some(e=>e<a[0]))return new N(Xq(a[0]));if(r<=-1)return new N(bJ(r));let o=new Map;for(let e of C(0,a.length)){let t=a[e];o.has(t)?o.set(t,o.get(t)+i[e]):o.set(t,i[e])}let s=Array.from(o.keys()),c=s.map(e=>o.get(e));return MY(e=>{let t=c[0];for(let n of C(1,c.length)){let r=(s[0]-s[n])/365;t+=c[n]*(1+e)**r}return t},e=>{let t=0;for(let n of C(1,c.length)){let r=(s[0]-s[n])/365;t+=r*c[n]*(1+e)**(r-1)}return t},r,40,1e-5,e=>e?e/10-.9:-.9)},isExported:!0},NX={description:j(`Net present value given to non-periodic cash flows..`),args:[k(`discount (number)`,j(`The discount rate of the investment over one period.`)),k(`cashflow_amounts (number, range<number>)`,j(`An range containing the income or payments associated with the investment.`)),k(`cashflow_dates (number, range<number>)`,j(`An range with dates corresponding to the cash flows in cashflow_amounts.`))],compute:function(e,t,n){let r=I(e,this.locale);if(!ph(t,n))return new N(Lq);let i=B(t).flat().map(e=>qa(e,this.locale)),a=B(n).flat().map(e=>qa(e,this.locale));if(a.some(e=>e<a[0]))return new N(Xq(a[0]));if(r<=0)return new N(SJ(r));if(i.length===1)return i[0];let o=new Map;for(let e of C(0,a.length)){let t=a[e];o.has(t)?o.set(t,o.get(t)+i[e]):o.set(t,i[e])}let s=Array.from(o.keys()),c=s.map(e=>o.get(e)),l=c[0];for(let e of C(1,c.length)){let t=(s[0]-s[e])/365;l+=c[e]*(1+r)**t}return l},isExported:!0},PX={description:j(`Annual yield of a security paying periodic interest.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`price (number)`,j(`The price at which the security is bought per 100 face value.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`frequency (number)`,j(`The number of interest or coupon payments per year (1, 2, or 4).`),kY),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),LJ)],compute:function(e,t,n,r,i,a,o={value:0}){o||=0;let s=Math.trunc(I(e,this.locale)),c=Math.trunc(I(t,this.locale)),l=I(n,this.locale),u=I(r,this.locale),d=I(i,this.locale),f=Math.trunc(I(a,this.locale)),p=Math.trunc(I(o,this.locale));if(s>=c)return new N(aJ(s,c));if(FJ(f))return new N(Vq(f));if(PJ(p))return new N(Hq(p));if(l<0)return new N(xJ(l));if(u<=0)return new N(_J(u));if(d<=0)return new N(CJ(d));let m=xa(s,c,p)*f,h=Math.ceil(m),g=m-Math.floor(m)||1,_=100*l/f;if(h===1){let e=u+_*(1-g);return(d+_-e)*f*(1/g)/e}function v(e,t,n,r,i,a){let o=a-(e+i*(1-t))*r**(n-1+t);for(let e=1;e<=n;e++)o+=i*r**(e-1);return o}function y(e,t,n,r,i){let a=-(e+i*(1-t))*(n-1+t)*r**(n-2+t);for(let e=1;e<=n;e++)a+=i*(e-1)*r**(e-2);return a}function b(e){return v(u,g,h,e,_,d)}function ee(e){return y(u,g,h,e,_)}return(MY(b,ee,1+(l+1)/f,100,1e-5)-1)*f},isExported:!0},FX={description:j(`Annual yield of a discount security.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`price (number)`,j(`The price at which the security is bought per 100 face value.`)),k(`redemption (number)`,j(`The redemption amount per 100 face value, or par.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),LJ)],compute:function(e,t,n,r,i={value:0}){i||=0;let a=Math.trunc(I(e,this.locale)),o=Math.trunc(I(t,this.locale)),s=I(n,this.locale),c=I(r,this.locale),l=Math.trunc(I(i,this.locale));if(a>=o)return new N(aJ(a,o));if(PJ(l))return new N(Hq(l));if(s<=0)return new N(_J(s));if(c<=0)return new N(CJ(c));let u=xa(a,o,l);return(c/s-1)/u},isExported:!0},IX={description:j(`Annual yield of a security paying interest at maturity.`),args:[k(`settlement (date)`,j(`The settlement date of the security, the date after issuance when the security is delivered to the buyer.`)),k(`maturity (date)`,j(`The maturity or end date of the security, when it can be redeemed at face, or par value.`)),k(`issue (date)`,j(`The date the security was initially issued.`)),k(`rate (number)`,j(`The annualized rate of interest.`)),k(`price (number)`,j(`The price at which the security is bought.`)),k(`day_count_convention (number, default=0 )`,j(`An indicator of what day count method to use.`),LJ)],compute:function(e,t,n,r,i,a={value:0}){a||=0;let o=Math.trunc(I(e,this.locale)),s=Math.trunc(I(t,this.locale)),c=Math.trunc(I(n,this.locale)),l=I(r,this.locale),u=I(i,this.locale),d=Math.trunc(I(a,this.locale));if(o>=s)return new N(aJ(o,s));if(PJ(d))return new N(Hq(d));if(o<c)return new N(EJ(o,c));if(l<0)return new N(xJ(l));if(u<=0)return new N(_J(u));let f=xa(c,s,d),p=xa(c,o,d),m=xa(o,s,d);return(100*(1+l*f)/(u+100*l*p)-1)/m},isExported:!0};var LX=l({CELL:()=>zX,ISBLANK:()=>qX,ISERR:()=>BX,ISERROR:()=>VX,ISFORMULA:()=>YX,ISLOGICAL:()=>HX,ISNA:()=>UX,ISNONTEXT:()=>WX,ISNUMBER:()=>GX,ISTEXT:()=>KX,NA:()=>JX});let RX=[{value:`address`,label:j(`Returns an absolute reference as plain text of the top left cell in reference.`)},{value:`col`,label:j(`Returns the column number of the cell in reference.`)},{value:`contents`,label:j(`Returns the value contained in the top left cell in reference.`)},{value:`format`,label:j(`Returns the format of the top left cell in reference.`)},{value:`row`,label:j(`Returns the row number of the top left cell in reference.`)},{value:`type`,label:j(`Returns the type of data in the cell in reference. The following values are returned: "b" for a blank cell, "l" (for label) if the cell contains plain text, and "v" (for value) if the cell contains any other type of data.`)}],zX={description:j(`Gets information about a cell.`),args:[k(`info_type (string)`,j(`The type of information requested.`),RX),k(`reference (any, range<any>)`,j(`The reference to the cell.`))],compute:function(e,t){let n=L(e).toLowerCase();if(!RX.map(e=>e.value).includes(n))return new N(j(`The info_type should be one of %s.`,RX.join(`, `)));let r=B(t)[0][0],i=r.position;if(i===void 0)return new N(j(`The reference is invalid.`));switch(n){case`address`:return(this.__originSheetId===i.sheetId?``:this.getters.getSheetName(i.sheetId)+`!`)+E(i.col,i.row,{colFixed:!0,rowFixed:!0});case`col`:return i.col+1;case`contents`:return r.value;case`format`:return r.format||``;case`row`:return i.row+1;case`type`:return r.value===null?`b`:iu(r.format)?`l`:typeof r.value==`number`||typeof r.value==`boolean`?`v`:`l`}return``},isExported:!0},BX={description:j(`Whether a value is an error other than #N/A.`),args:[k(`value (any)`,j(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return F(t)&&t!==M.NotAvailable},isExported:!0},VX={description:j(`Whether a value is an error.`),args:[k(`value (any)`,j(`The value to be verified as an error type.`))],compute:function(e){let t=e?.value;return F(t)},isExported:!0},HX={description:j("Whether a value is `true` or `false`."),args:[k(`value (any)`,j(`The value to be verified as a logical TRUE or FALSE.`))],compute:function(e){return typeof e?.value==`boolean`},isExported:!0},UX={description:j(`Whether a value is the error #N/A.`),args:[k(`value (any)`,j(`The value to be verified as an error type.`))],compute:function(e){return e?.value===M.NotAvailable},isExported:!0},WX={description:j(`Whether a value is non-textual.`),args:[k(`value (any)`,j(`The value to be checked.`))],compute:function(e){return!KX.compute.bind(this)(e)},isExported:!0},GX={description:j(`Whether a value is a number.`),args:[k(`value (any)`,j(`The value to be verified as a number.`))],compute:function(e){return typeof e?.value==`number`},isExported:!0},KX={description:j(`Whether a value is text.`),args:[k(`value (any)`,j(`The value to be verified as text.`))],compute:function(e){return typeof e?.value==`string`&&F(e?.value)===!1},isExported:!0},qX={description:j(`Whether the referenced cell is empty`),args:[k(`value (any)`,j(`Reference to the cell that will be checked for emptiness.`))],compute:function(e){return e?.value===null},isExported:!0},JX={description:j(`Returns the error value #N/A.`),args:[],compute:function(){return{value:M.NotAvailable}},isExported:!0},YX={description:j(`Checks whether there is a reference to a cell that contains a formula, and returns TRUE or FALSE.`),args:[k(`cell_reference (any)`,j(`A reference to a cell.`))],compute:function(e){return e?.position===void 0?new Li(Ha):this.getters.getCell(e.position)?.isFormula??!1},isExported:!0};var XX=l({AND:()=>ZX,FALSE:()=>QX,IF:()=>$X,IFERROR:()=>eZ,IFNA:()=>tZ,IFS:()=>nZ,NOT:()=>rZ,OR:()=>iZ,SWITCH:()=>aZ,TRUE:()=>oZ,XOR:()=>sZ});let ZX={description:j("Logical `and` operator."),args:[k(`logical_expression (boolean, range<boolean>, repeating)`,j(`Expression or reference to a cell containing a logical value (TRUE/FALSE) or an expression that can be coerced to a logical value.`))],compute:function(...e){let{result:t,foundBoolean:n}=Jh(e);return n?t:new N(Eo)},isExported:!0},QX={description:j("Logical value `false`."),args:[],compute:function(){return!1},isExported:!0},$X={description:j(`Returns value depending on logical expression.`),args:[k(`logical_expression (boolean, range<boolean>)`,j(`An expression or reference to a cell containing an expression that represents some logical value, i.e. TRUE or FALSE.`)),k(`value_if_true (any, range)`,j(`The value the function returns if logical_expression is TRUE.`)),k(`value_if_false (any, range, default=FALSE)`,j(`The value the function returns if logical_expression is FALSE.`))],compute:function(e,t,n){return Sh(e)?fo($X.compute,[e,t,n]):(R(bh(e))?t:n)??{value:0}},isExported:!0},eZ={description:j(`Value if it is not an error, otherwise 2nd argument.`),args:[k(`value (any, range)`,j(`The value to return if value itself is not an error.`)),k(`value_if_error (any, range, default="empty")`,j(`The value the function returns if value is an error.`))],compute:function(e,t){return Sh(e)?fo(eZ.compute,[e,t]):(F(bh(e)?.value)?t:e)??{value:0}},isExported:!0},tZ={description:j(`Value if it is not an #N/A error, otherwise 2nd argument.`),args:[k(`value (any, range)`,j(`The value to return if value itself is not #N/A an error.`)),k(`value_if_error (any, range, default="empty")`,j(`The value the function returns if value is an #N/A error.`))],compute:function(e,t){return Sh(e)?fo(tZ.compute,[e,t]):(bh(e)?.value===M.NotAvailable?t:e)??{value:0}},isExported:!0},nZ={description:j(`Returns a value depending on multiple logical expressions.`),args:[k(`condition (any, range, repeating)`,j(`The condition to be evaluated. It can be a boolean, a number, an array, or a reference to any of those.`)),k(`value (any, range, repeating)`,j(`The value to be returned if its corresponding condition is TRUE.`))],compute:function(...e){if(e.length%2!=0)return new N(j(`Wrong number of arguments. Expected an even number of arguments.`));for(;e.length>0;){if(Sh(e[0]))return fo(nZ.compute,e);let t=R(bh(e.shift())),n=e.shift();if(t)return n??{value:0}}return new N(j(`No match.`))},isExported:!0},rZ={description:j(`Returns opposite of provided logical value.`),args:[k(`logical_expression (boolean)`,j(`An expression or reference to a cell holding an expression that represents some logical value.`))],compute:function(e){return!R(e)},isExported:!0},iZ={description:j("Logical `or` operator."),args:[k(`logical_expression (boolean, range<boolean>, repeating)`,j(`Expression or reference to a cell containing a logical value (TRUE/FALSE) or an expression that can be coerced to a logical value.`))],compute:function(...e){let{result:t,foundBoolean:n}=Yh(e);return n?t:new N(Eo)},isExported:!0},aZ={description:j(`Returns a value by comparing cases to an expression.`),args:[k(`expression (number, boolean, string)`,j(`The value to be checked.`)),k(`case (any, repeating)`,j(`Case to be checked against expression.`)),k(`value (any, repeating)`,j(`Value to be returned if its corresponding case matches expression.`)),k(`default (any, default="empty")`,j(`An optional default value to be returned if none of the cases match expression.`))],compute:function(e,...t){let n=t.length%2==0?Ba(e):t.pop();for(let n=0;n<t.length;n+=2){let r=t[n];if(r&&F(r.value))return r;if(e?.value===r?.value)return t[n+1]||{value:0}}return n||{value:0}},isExported:!0},oZ={description:j("Logical value `true`."),args:[],compute:function(){return!0},isExported:!0},sZ={description:j("Logical `xor` operator."),args:[k(`logical_expression (boolean, range<boolean>, repeating)`,j(`Expression or reference to a cell containing a logical value (TRUE/FALSE) or an expression that can be coerced to a logical value.`))],compute:function(...e){let t=!1,n=!1;return mo(e,e=>(t=!0,n=n?!e:e,!0)),t?n:new N(Eo)},isExported:!0};function cZ(e,t){let n=t.getPivotId(e);if(!n)throw new N(j(`There is no pivot with id "%s"`,e));return n}function lZ(e,t,n){let{measures:r}=n.getPivotCoreDefinition(e);if(!r.find(e=>e.id===t))throw new N(j(`The argument %s is not a valid measure. Here are the measures: %s`,t,`(${r.map(e=>e.id).join(`, `)})`))}function uZ(e){if(e.length%2!=0)throw new N(j(`Function PIVOT takes an even number of arguments.`))}function dZ(e,t,n){let r=[],i=e.getters.getPivotCoreDefinition(t);if(i.type===`SPREADSHEET`&&i.dataSet){let{sheetId:t,zone:n}=i.dataSet,a=wn(n),o=e.getters.getRangeFromSheetXC(t,a);if(o===void 0||o.invalidXc||o.invalidSheetName)throw new Li;if(e.__originCellPosition&&o.sheetId===e.__originSheetId&&In(D(e.__originCellPosition),n))throw new Ii;r.push(o)}for(let i of n)i.computedBy&&r.push(...e.getters.getMeasureFullDependencies(t,i));let a=e.__originCellPosition;a&&r.length&&(e.updateDependencies?.(a),e.addDependencies?.(a,r))}var fZ=l({ADDRESS:()=>hZ,CHOOSE:()=>MZ,COLUMN:()=>gZ,COLUMNS:()=>_Z,DROP:()=>NZ,FORMULATEXT:()=>FZ,HLOOKUP:()=>vZ,INDEX:()=>yZ,INDIRECT:()=>bZ,LOOKUP:()=>xZ,MATCH:()=>SZ,OFFSET:()=>jZ,PIVOT:()=>AZ,PIVOT_HEADER:()=>kZ,PIVOT_VALUE:()=>OZ,ROW:()=>CZ,ROWS:()=>wZ,TAKE:()=>PZ,VLOOKUP:()=>TZ,XLOOKUP:()=>DZ});let pZ=[{value:!0,label:j(`A1 style (default)`)},{value:!1,label:j(`R1C1 style`)}],mZ=[{value:!0,label:j(`Approximate match (default)`)},{value:!1,label:j(`Exact match`)}],hZ={description:j(`Returns a cell reference as a string. `),args:[k(`row (number)`,j(`The row number of the cell reference. `)),k(`column (number)`,j(`The column number (not name) of the cell reference. A is column number 1. `)),k(`absolute_relative_mode (number, default=1)`,j(`An indicator of whether the reference is row/column absolute.`),[{value:1,label:j(`Absolute row and column (e.g. $A$1)`)},{value:2,label:j(`Absolute row, relative column (e.g. A$1)`)},{value:3,label:j(`Relative row, absolute column (e.g. $A1)`)},{value:4,label:j(`Relative row and column (e.g. A1)`)}]),k(`use_a1_notation (boolean, default=TRUE)`,j(`A boolean indicating whether to use A1 style notation or R1C1 style notation.`),pZ),k(`sheet (string, optional)`,j(`A string indicating the name of the sheet into which the address points.`))],compute:function(e,t,n={value:1},r={value:!0},i){let a=Ya(e,this.locale),o=Ya(t,this.locale);if(a<1)return new N(hh(a));if(o<1)return new N(hh(o));let s=Ya(n,this.locale);if(![1,2,3,4].includes(s))return new N(Ua(1,4,s));let c=R(r),l;if(c){let e={rowFixed:[1,2].includes(s),colFixed:[1,3].includes(s)};l=E(o-1,a-1,e)}else l=([1,2].includes(s)?`R${a}`:`R[${a}]`)+([1,3].includes(s)?`C${o}`:`C[${o}]`);return i===void 0?l:Xo(L(i),l)},isExported:!0},gZ={description:j(`Column number of a specified cell.`),args:[k(`cell_reference (any, range<any>, default='this cell')`,j(`The cell whose column number will be returned. Column A corresponds to 1. By default, the function use the cell in which the formula is entered.`))],compute:function(e){if(e===void 0)return this.__originCellPosition===void 0?new N(j(`In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.`)):this.__originCellPosition.col+1;let t=B(e),n=t[0][0];if(n===void 0)return new N(j(`The range is out of bounds.`));if(n.position===void 0)return new Li(Ha);let r=n.position.col;return t.length===1?r+1:so(t.length,1,e=>({value:r+e+1}))},isExported:!0},_Z={description:j(`Number of columns in a specified array or range.`),args:[k(`range (any, range<any>)`,j(`The range whose column count will be returned.`))],compute:function(e){let t=B(e);return t[0][0]===void 0?new N(j(`The range is out of bounds.`)):t[0][0].value===M.InvalidReference?t[0][0]:t.length},isExported:!0},vZ={description:j(`Horizontal lookup`),args:[k(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),k(`range (any, range)`,j(`The range to consider for the search. The first row in the range is searched for the key specified in search_key.`)),k(`index (number)`,j(`The row index of the value to be returned, where the first row in range is numbered 1.`)),k(`is_sorted (boolean, default=true)`,j(`Indicates whether the row to be searched (the first row of the specified range) is sorted, in which case the closest match for search_key will be returned.`),mZ)],compute:function(e,t,n,r={value:!0}){let i=Math.trunc(I(n?.value,this.locale)),a=B(t);if(1>i||i>a[0].length)return new N(j(`[[FUNCTION_NAME]] evaluates to an out of bounds range.`));let o=(e,t)=>e[t][0].value,s=a[R(r.value)?yo(a,e,`nextSmaller`,`asc`,a.length,o):bo(a,e,`wildcard`,a.length,o,this.lookupCaches)];return s===void 0?Ba(e):s[i-1]},isExported:!0},yZ={description:j(`Returns the content of a cell, specified by row and column offset.`),args:[k(`reference (any, range)`,j(`The range of cells from which the values are returned.`)),k(`row (number, default=0)`,j(`The index of the row to be returned from within the reference range of cells.`)),k(`column (number, default=0)`,j(`The index of the column to be returned from within the reference range of cells.`))],compute:function(e,t={value:0},n={value:0}){let r=B(e),i=I(t.value,this.locale),a=I(n.value,this.locale);return a<0||a-1>=r.length||i<0||i-1>=r[0].length?new N(j(`Index out of range.`)):i===0&&a===0?r:i===0?[r[a-1]]:a===0?r.map(e=>[e[i-1]]):r[a-1][i-1]},isExported:!0},bZ={description:j(`Returns the content of a cell, specified by a string.`),args:[k(`reference (string)`,j(`The range of cells from which the values are returned.`)),k(`use_a1_notation (boolean, default=TRUE)`,j(`A boolean indicating whether to use A1 style notation (TRUE) or R1C1 style notation (FALSE).`),pZ)],compute:function(e,t={value:!0}){let n=e?.value?.toString();if(!n)return new Li(j(`Reference should be defined.`));if(!R(t))return new N(j(`R1C1 notation is not supported.`));let r=this.__originSheetId,i=this.__originCellPosition;i&&this.updateDependencies?.(i);let a=this.getters.getNamedRange(n),o=a?a.range:this.getters.getRangeFromSheetXC(r,n);if(o===void 0||o.invalidXc||o.invalidSheetName)return new Li;i&&this.addDependencies?.(i,[o]);let s=[];for(let e=o.zone.left;e<=o.zone.right;e++){let t=[];for(let n=o.zone.top;n<=o.zone.bottom;n++){let r={sheetId:o.sheetId,col:e,row:n};t.push(this.getFormulaResult(r))}s.push(t)}return s.length===1&&s[0].length===1?s[0][0]:s},isExported:!0},xZ={description:j(`Look up a value.`),args:[k(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),k(`search_array (any, range)`,j(`One method of using this function is to provide a single sorted row or column search_array to look through for the search_key with a second argument result_range. The other way is to combine these two arguments into one search_array where the first row or column is searched and a value is returned from the last row or column in the array. If search_key is not found, a non-exact match may be returned.`)),k(`result_range (any, range, optional)`,j(`The range from which to return a result. The value returned corresponds to the location where search_key is found in search_range. This range must be only a single row or column and should not be used if using the search_result_array method.`))],compute:function(e,t,n){let r=B(t),i=B(n),a=r.length,o=r[0].length,s=o>=a,c=yo(r,e,`nextSmaller`,`asc`,s?o:a,s?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value);return c===-1||s&&r[0][c]===void 0||!s&&r[c][o-1]===void 0?Ba(e):i[0].length===0?s?r[a-1][c]:r[c][o-1]:(a=i.length,o=i[0].length,a!==1&&o!==1?new N(j(`The result_range must be a single row or a single column.`)):a>1?c>a-1?new N(j(`[[FUNCTION_NAME]] evaluates to an out of range row value %s.`,c+1)):i[c][0]:c>o-1?new N(j(`[[FUNCTION_NAME]] evaluates to an out of range column value %s.`,c+1)):i[0][c])},isExported:!0},SZ={description:j(`Position of item in range that matches value.`),args:[k(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),k(`range (any, range)`,j(`The one-dimensional array to be searched.`)),k(`search_type (number, default=1)`,j(`The search method is a number 1, 0 or -1 indicating which value to return. 1 finds the largest value less than or equal to search_key when range is sorted in ascending order. 0 finds the exact value when range is unsorted. -1 finds the smallest value greater than or equal to search_key when range is sorted in descending order.`),[{value:1,label:j(`Ascending order (default)`)},{value:0,label:j(`Exact match`)},{value:-1,label:j(`Descending order`)}])],compute:function(e,t,n={value:1}){let r=I(n,this.locale),i=B(t),a=i.length,o=i[0].length;if(a!==1&&o!==1)return new N(j(`The range must be a single row or a single column.`));let s=-1,c=a===1?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,l=a===1?i[0].length:i.length;switch(r=Math.sign(r),r){case 1:s=yo(i,e,`nextSmaller`,`asc`,l,c);break;case 0:s=bo(i,e,`wildcard`,l,c,this.lookupCaches);break;case-1:s=yo(i,e,`nextGreater`,`desc`,l,c);break}return a===1&&i[0][s]===void 0||a!==1&&i[s]===void 0?Ba(e):s+1},isExported:!0},CZ={description:j(`Row number of a specified cell.`),args:[k(`cell_reference (any, range<any>, default='this cell')`,j(`The cell whose row number will be returned. By default, this function uses the cell in which the formula is entered.`))],compute:function(e){if(e===void 0)return this.__originCellPosition?.row===void 0?new N(j(`In this context, the function [[FUNCTION_NAME]] needs to have a cell or range in parameter.`)):this.__originCellPosition.row+1;let t=B(e),n=t[0][0];if(n===void 0)return new N(j(`The range is out of bounds.`));if(n.position===void 0)return new Li(Ha);let r=n.position.row;return t[0].length===1?r+1:so(1,t[0].length,(e,t)=>({value:r+t+1}))},isExported:!0},wZ={description:j(`Number of rows in a specified array or range.`),args:[k(`range (any, range<any>)`,j(`The range whose row count will be returned.`))],compute:function(e){let t=B(e);return t[0][0]===void 0?new N(j(`The range is out of bounds.`)):t[0][0].value===M.InvalidReference?t[0][0]:t[0].length},isExported:!0},TZ={description:j(`Vertical lookup.`),args:[k(`search_key (string, number, boolean)`,j(`The value to search for. For example, 42, 'Cats', or I24.`)),k(`range (any, range)`,j(`The range to consider for the search. The first column in the range is searched for the key specified in search_key.`)),k(`index (number)`,j(`The column index of the value to be returned, where the first column in range is numbered 1.`)),k(`is_sorted (boolean, default=true)`,j(`Indicates whether the column to be searched (the first column of the specified range) is sorted, in which case the closest match for search_key will be returned.`),mZ)],compute:function(e,t,n,r={value:!0}){let i=Math.trunc(I(n?.value,this.locale)),a=B(t);if(1>i||i>a.length)return new N(j(`[[FUNCTION_NAME]] evaluates to an out of bounds range.`));let o=(e,t)=>e[0][t].value,s=R(r.value)?yo(a,e,`nextSmaller`,`asc`,a[0].length,o):bo(a,e,`wildcard`,a[0].length,o,this.lookupCaches),c=a[i-1][s];return c===void 0?Ba(e):c},isExported:!0},EZ={0:`strict`,1:`nextGreater`,"-1":`nextSmaller`,2:`wildcard`},DZ={description:j(`Search a range for a match and return the corresponding item from a second range.`),args:[k(`search_key (string,number,boolean)`,j(`The value to search for.`)),k(`lookup_range (any, range)`,j(`The range to consider for the search. Should be a single column or a single row.`)),k(`return_range (any, range)`,j(`The range containing the return value. Should have the same dimensions as lookup_range.`)),k(`if_not_found (any, optional)`,j(`If a valid match is not found, return this value.`)),k(`match_mode (any, default=0)`,j(`Specifies how to match search_key with the items in lookup_range. `),[{value:0,label:j(`Exact match (default)`)},{value:-1,label:j(`Exact match or next smaller item`)},{value:1,label:j(`Exact match or next larger item`)},{value:2,label:j(`Wildcard character match`)}]),k(`search_mode (any, default=1)`,j(`Specifies the search mode to use. By default, a first to last search will be used.`),[{value:1,label:j(`Search first to last (default)`)},{value:-1,label:j(`Search last to first`)},{value:2,label:j(`Binary search (sorted ascending order)`)},{value:-2,label:j(`Binary search (sorted descending order)`)}])],compute:function(e,t,n,r,i={value:0},a={value:1}){let o=Math.trunc(I(i.value,this.locale)),s=Math.trunc(I(a.value,this.locale)),c=B(t),l=B(n);if(c.length!==1&&c[0].length!==1)return new N(j(`lookup_range should be either a single row or single column.`));if(![1,-1,2,-2].includes(s))return new N(j(`search_mode should be a value in [-1, 1, -2, 2].`));if(![-1,0,1,2].includes(o))return new N(j(`match_mode should be a value in [-1, 0, 1, 2].`));let u=c.length===1?`col`:`row`;if(o===2&&[-2,2].includes(s))return new N(j(`The search and match mode combination is not supported for XLOOKUP evaluation.`));if(u===`col`?l[0].length!==c[0].length:l.length!==c.length)return new N(j(`return_range should have the same dimensions as lookup_range.`));let d=u===`col`?(e,t)=>e[0][t].value:(e,t)=>e[t][0].value,f=u===`col`?c[0].length:c.length,p=EZ[o],m=s===-1,h=s===2||s===-2?yo(c,e,p,s===2?`asc`:`desc`,f,d):bo(c,e,p,f,d,this.lookupCaches,m);return h===-1?r===void 0?Ba(e):[[r]]:u===`col`?l.map(e=>[e[h]]):[l[h]]},isExported:!0},OZ={description:j(`Get the value from a pivot.`),args:[k(`pivot_id (number,string)`,j(`ID of the pivot.`)),k(`measure_name (string)`,j(`Name of the measure.`)),k(`domain_field_name (string,repeating,optional)`,j(`Field name.`)),k(`domain_value (number,string,boolean,repeating,optional)`,j(`Value.`))],compute:function(e,t,...n){let r=L(e),i=L(t),a=cZ(r,this.getters);lZ(a,i,this.getters),uZ(n);let o=this.getters.getPivot(a),s=this.getters.getPivotCoreDefinition(a);dZ(this,a,s.measures.filter(e=>e.id===i)),o.init({reload:o.needsReevaluation});let c=o.assertIsValid({throwOnError:!1});if(c)return c;if(!o.areDomainArgsFieldsValid(n)){let e=j(`Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.`,`=PIVOT(${r})`);return{value:M.GenericError,message:j(`Dimensions don't match the pivot definition`)+`. `+e}}let l=o.parseArgsToPivotDomain(n);return this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(a)?.trackValue(i,l),o.getPivotCellValueAndFormat(i,l)}},kZ={description:j(`Get the header of a pivot.`),args:[k(`pivot_id (number,string)`,j(`ID of the pivot.`)),k(`domain_field_name (string,repeating,optional)`,j(`Field name.`)),k(`domain_value (number,string,value,repeating,optional)`,j(`Value.`))],compute:function(e,...t){let n=L(e),r=cZ(n,this.getters);uZ(t);let i=this.getters.getPivot(r);dZ(this,r,[]),i.init({reload:i.needsReevaluation});let a=i.assertIsValid({throwOnError:!1});if(a)return a;if(!i.areDomainArgsFieldsValid(t)){let e=j(`Consider using a dynamic pivot formula: %s. Or re-insert the static pivot from the Data menu.`,`=PIVOT(${n})`);return{value:M.GenericError,message:j(`Dimensions don't match the pivot definition`)+`. `+e}}let o=i.parseArgsToPivotDomain(t);this.getters.getActiveSheetId()===this.__originSheetId&&this.getters.getPivotPresenceTracker(r)?.trackHeader(o);let s=o.at(-1);if(s?.field===`measure`)return i.getPivotMeasureValue(L(s.value),o);let{value:c,format:l}=i.getPivotHeaderValueAndFormat(o);return{value:c,format:!s||s.field===`measure`||s.value===`false`?void 0:l}}},AZ={description:j(`Get a pivot table.`),args:[k(`pivot_id (string)`,j(`ID of the pivot.`)),k(`row_count (number, optional)`,j(`number of rows`)),k(`include_total (boolean, default=TRUE)`,j(`Whether to include total/sub-totals or not.`)),k(`include_column_titles (boolean, default=TRUE)`,j(`Whether to include the column titles or not.`)),k(`column_count (number, optional)`,j(`number of columns`)),k(`include_measure_titles (boolean, default=TRUE)`,j(`Whether to include the measure titles row or not.`))],compute:function(e,t,n,r,i,a){let o=cZ(L(e),this.getters),s=this.getters.getPivot(o),c=this.getters.getPivotCoreDefinition(o),l=Ug(c,t,n,r,i,a,this.locale);if(l.numberOfRows<0)return new N(j(`The number of rows must be positive.`));if(l.numberOfColumns<0)return new N(j(`The number of columns must be positive.`));dZ(this,o,c.measures),s.init({reload:s.needsReevaluation});let u=s.assertIsValid({throwOnError:!1});if(u)return u;let d=s.getCollapsedTableStructure();if(d.numberOfCells>5e5)return new N(Uy(d.numberOfCells,this.locale));let f=d.getPivotCells(l),p=this.getters.getPivotName(o),{numberOfCols:m,numberOfRows:h}=d.getPivotTableDimensions(l);if(h===0)return[[{value:p}]];let g=[];for(let e of C(0,m)){g[e]=[];for(let t of C(0,h)){let n=f[e][t];switch(n.type){case`EMPTY`:g[e].push({value:``});break;case`HEADER`:let t=s.getPivotHeaderValueAndFormat(n.domain);g[e].push(Pg(n.domain,t));break;case`MEASURE_HEADER`:g[e].push(s.getPivotMeasureValue(n.measure,n.domain));break;case`VALUE`:g[e].push(s.getPivotCellValueAndFormat(n.measure,n.domain));break;case`ROW_GROUP_NAME`:let r=s.definition.rows.find(e=>e.nameWithGranularity===n.rowField)?.displayName;g[e].push({value:r||``});break}}}return(l.displayColumnHeaders||l.displayMeasuresRow)&&f[0][0].type===`EMPTY`&&(g[0][0]={value:p}),g}},jZ={description:j(`Returns a range reference shifted by a specified number of rows and columns from a starting cell reference.`),args:[k(`cell_reference (any, range<any>)`,j(`The starting point from which to count the offset rows and columns.`)),k(`offset_rows (number)`,j(`The number of rows to offset by.`)),k(`offset_columns (number)`,j(`The number of columns to offset by.`)),k(`height (number, default='height of cell_reference')`,j(`The number of rows of the range to return starting at the offset target.`)),k(`width (number, default='width of cell_reference')`,j(`The number of columns of the range to return starting at the offset target.`))],compute:function(e,t,n,r,i){if(e===void 0)return new Li(Ha);let a=B(e),o=a[0][0];if(o===void 0)return new N(j(`The range is out of bounds.`));if(o.position===void 0)return new Li(Ha);let s=a[0].length,c=a.length;if(r){let e=I(r,this.locale);if(e<1)return new N(j(`Height value is %(_height)s. It should be greater than or equal to 1.`,{_height:e}));s=e}if(i){let e=I(i,this.locale);if(e<1)return new N(j(`Width value is %(_width)s. It should be greater than or equal to 1.`,{_width:e}));c=e}let l=I(t,this.locale),u=I(n,this.locale),d=this.__originCellPosition;d&&this.updateDependencies?.(d);let f=o.position.col+u,p=o.position.row+l;if(f<0||p<0)return new Li(j(`OFFSET evaluates to an out of bounds range.`));let m={left:f,top:p,right:f+c-1,bottom:p+s-1},h=o.position.sheetId,g=this.getters.getRangeFromZone(h,m);return g.invalidXc||g.invalidSheetName?new Li:(d&&this.addDependencies?.(d,[g]),so(c,s,(e,t)=>this.getFormulaResult({sheetId:h,col:f+e,row:p+t})))}},MZ={description:j(`Returns an element from a list of choices based on index.`),args:[k(`index (number)`,j(`Which choice to return.`)),k(`choice (any, range<any>, repeating)`,j(`A potential value to return. May be a reference to a cell or an individual value.`))],compute:function(e,...t){let n=Math.floor(I(e,this.locale))-1;return n<0||n>=t.length?new N(j(`Index for CHOOSE is invalid. Valid values are between 1 and %(choices)s inclusive.`,{choices:t.length})):t[n]??new N(j(`Choice is undefined.`))},isExported:!0},NZ={description:j(`Excludes a specified number of rows or columns from the start or end of an array.`),args:[k(`array (range)`,j(`The array from which to drop rows or columns`)),k(`rows (number)`,j(`The number of rows to drop. A negative value drops from the end of the array.`)),k(`columns (number, optional)`,j(`The number of columns to exclude. A negative value drops from the end of the array.`))],compute:function(e,t,n){let r=I(t,this.locale),i=I(n,this.locale),a=e;if(Math.abs(i)>=e.length||Math.abs(r)>=e[0].length)return new N(j(`The number of rows or column to exclude must be smaller than the number of elements in the array.`));a=i>=0?a.slice(i):a.slice(0,a.length+i);for(let e=0;e<a.length;e++)r>=0?a[e]=a[e].slice(r):a[e]=a[e].slice(0,a[e].length+r);return a},isExported:!0},PZ={description:j(`Returns a specified number of contiguous rows or columns from the start or end of an array.`),args:[k(`array (range)`,j(`The array from which to take rows or columns.`)),k(`rows (number)`,j(`The number of rows to take. A negative value takes from the end of the array.`)),k(`columns (number, optional)`,j(`The number of columns to take. A negative value takes from the end of the array.`))],compute:function(e,t,n){let r=t?I(t,this.locale):e[0].length,i=I(n,this.locale),a=e;if((Math.abs(i)>=e.length||i===0)&&(i=e.length),Math.abs(r)>=e[0].length&&(r=e[0].length),a=i>=0?a.slice(0,i):a.slice(a.length+i,a.length),r===0)return new N(j(`The number of rows can not be zero.`));for(let e=0;e<a.length;e++)r>0?a[e]=a[e].slice(0,r):a[e]=a[e].slice(a[e].length+r,a[e].length);return a},isExported:!0},FZ={description:j(`Returns a formula as a string.`),args:[k(`cell_reference (any)`,j(`A reference to a cell.`))],compute:function(e){if(e?.position===void 0)return new Li(Ha);let t=this.getters.getCell(e.position);return t?.isFormula?t.compiledFormula.toFormulaString(this.getters):new Ri(j(`The cell does not contain a formula.`))},isExported:!0};var IZ=l({ADD:()=>LZ,CONCAT:()=>RZ,DIVIDE:()=>zZ,EQ:()=>UZ,GT:()=>GZ,GTE:()=>KZ,LT:()=>qZ,LTE:()=>JZ,MINUS:()=>YZ,MULTIPLY:()=>XZ,NE:()=>ZZ,POW:()=>QZ,SPILLED_RANGE:()=>$Z,UMINUS:()=>eQ,UNARY_PERCENT:()=>tQ,UPLUS:()=>nQ});let LZ={description:j(`Sum of two numbers.`),args:[k(`value1 (number)`,j(`The first addend.`)),k(`value2 (number)`,j(`The second addend.`))],compute:function(e,t){return{value:I(e,this.locale)+I(t,this.locale),format:e?.format||t?.format}}},RZ={description:j(`Concatenation of two values.`),args:[k(`value1 (string)`,j(`The value to which value2 will be appended.`)),k(`value2 (string)`,j(`The value to append to value1.`))],compute:function(e,t){return L(e)+L(t)},isExported:!0},zZ={description:j(`One number divided by another.`),args:[k(`dividend (number)`,j(`The number to be divided.`)),k(`divisor (number)`,j(`The number to divide by.`))],compute:function(e,t){let n=I(t,this.locale);return n===0?new Vi(j(`The divisor must be different from zero.`)):{value:I(e,this.locale)/n,format:e?.format||t?.format}}};function BZ(e){return e===void 0||e.value===null}let VZ={number:0,string:``,boolean:!1};function HZ(e,t,n=2e-16){return Math.abs(e-t)<n}let UZ={description:j(`Equal.`),args:[k(`value1 (string, number, boolean)`,j(`The first value.`)),k(`value2 (string, number, boolean)`,j(`The value to test against value1 for equality.`))],compute:function(e,t){if(F(e?.value))return e;if(F(t?.value))return t;let n=BZ(e)?VZ[typeof t?.value]:e?.value,r=BZ(t)?VZ[typeof e?.value]:t?.value;return typeof n==`string`&&(n=n.toUpperCase()),typeof r==`string`&&(r=r.toUpperCase()),typeof n==`number`&&typeof r==`number`?{value:HZ(n,r)}:{value:n===r}}};function WZ(e,t,n){if(F(e?.value))return e;if(F(t?.value))return t;let r=BZ(e)?VZ[typeof t?.value]:e?.value,i=BZ(t)?VZ[typeof e?.value]:t?.value;typeof r!=`number`&&(r=L(r).toUpperCase()),typeof i!=`number`&&(i=L(i).toUpperCase());let a=typeof r,o=typeof i;return a===`string`&&o===`number`?{value:!0}:o===`string`&&a===`number`?{value:!1}:{value:n(r,i)}}let GZ={description:j(`Strictly greater than.`),args:[k(`value1 (number, string, boolean)`,j(`The value to test as being greater than value2.`)),k(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){return WZ(e,t,(e,t)=>typeof e==`number`&&typeof t==`number`?!HZ(e,t)&&e>t:e>t)}},KZ={description:j(`Greater than or equal to.`),args:[k(`value1 (number, string, boolean)`,j(`The value to test as being greater than or equal to value2.`)),k(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){return WZ(e,t,(e,t)=>typeof e==`number`&&typeof t==`number`?HZ(e,t)||e>t:e>=t)}},qZ={description:j(`Less than.`),args:[k(`value1 (number, string, boolean)`,j(`The value to test as being less than value2.`)),k(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){let n=KZ.compute.bind(this)(e,t);return F(n.value)?n:{value:!n.value}}},JZ={description:j(`Less than or equal to.`),args:[k(`value1 (number, string, boolean)`,j(`The value to test as being less than or equal to value2.`)),k(`value2 (number, string, boolean)`,j(`The second value.`))],compute:function(e,t){let n=GZ.compute.bind(this)(e,t);return F(n.value)?n:{value:!n.value}}},YZ={description:j(`Difference of two numbers.`),args:[k(`value1 (number)`,j(`The minuend, or number to be subtracted from.`)),k(`value2 (number)`,j(`The subtrahend, or number to subtract from value1.`))],compute:function(e,t){return{value:I(e,this.locale)-I(t,this.locale),format:e?.format||t?.format}}},XZ={description:j(`Product of two numbers`),args:[k(`factor1 (number)`,j(`The first multiplicand.`)),k(`factor2 (number)`,j(`The second multiplicand.`))],compute:function(e,t){return{value:I(e,this.locale)*I(t,this.locale),format:e?.format||t?.format}}},ZZ={description:j(`Not equal.`),args:[k(`value1 (string, number, boolean)`,j(`The first value.`)),k(`value2 (string, number, boolean)`,j(`The value to test against value1 for inequality.`))],compute:function(e,t){let n=UZ.compute.bind(this)(e,t);return F(n.value)?n:{value:!n.value}}},QZ={description:j(`A number raised to a power.`),args:[k(`base (number)`,j(`The number to raise to the exponent power.`)),k(`exponent (number)`,j(`The exponent to raise base to.`))],compute:function(e,t){return LG.compute.bind(this)(e,t)}},$Z={description:j(`Gets the spilled range of an array formula.`),args:[k(`ref (any, range<any>)`,j(`The reference to get the spilled range from.`))],compute:function(e){if(e===void 0)return new Li(Ha);let t=B(e);if(t.length!==1||t[0].length!==1)return new N(j(`Only single-cell references are allowed to get the spilled range.`));let n=t[0][0];if(F(n.value))return n;if(n.position===void 0)return new Li(Ha);let r=this.__originCellPosition;r&&this.updateDependencies?.(r);let i=this.getters.getSpreadZone(n.position);if(i===void 0)return new Li;let a=this.getters.getRangeFromZone(this.__originSheetId,i);return r&&this.addDependencies?.(r,[a]),so(i.right-i.left+1,i.bottom-i.top+1,(e,t)=>this.getFormulaResult({sheetId:a.sheetId,col:i.left+e,row:i.top+t}))},hidden:!0},eQ={description:j(`A number with the sign reversed.`),args:[k(`value (number)`,j(`The number to have its sign reversed. Equivalently, the number to multiply by -1.`))],compute:function(e){return{value:-I(e,this.locale),format:e?.format}}},tQ={description:j(`Value interpreted as a percentage.`),args:[k(`percentage (number)`,j(`The value to interpret as a percentage.`))],compute:function(e){return I(e,this.locale)/100}},nQ={description:j(`A specified number, unchanged.`),args:[k(`value (any)`,j(`The number to return.`))],compute:function(e={value:null}){return e}},$=e=>({transform:t=>t*e,inverseTransform:t=>t/e}),rQ={transform:e=>e,inverseTransform:e=>e},iQ=1e-10,aQ=.0254,oQ=aQ/72,sQ=.3048,cQ=.9144,lQ=1609.34,uQ=1852,dQ=946073047258e4,fQ={g:{...rQ,category:`weight`},u:{...$(166053e-29),category:`weight`},grain:{...$(.0647989),category:`weight`},ozm:{...$(28.3495),category:`weight`},lbm:{...$(453.592),category:`weight`},stone:{...$(6350.29),category:`weight`},sg:{...$(14593.90294),category:`weight`},cwt:{...$(45359.237),category:`weight`},uk_cwt:{...$(50802.3),category:`weight`},ton:{...$(907184.74),category:`weight`},uk_ton:{...$(1016046.9),category:`weight`},m:{...rQ,category:`distance`},km:{...$(1e3),category:`distance`},ang:{...$(iQ),category:`distance`},Picapt:{...$(oQ),category:`distance`},pica:{...$(aQ/6),category:`distance`},in:{...$(aQ),category:`distance`},ft:{...$(sQ),category:`distance`},yd:{...$(cQ),category:`distance`},ell:{...$(1.143),category:`distance`},mi:{...$(lQ),category:`distance`},survey_mi:{...$(1609.34),category:`distance`},Nmi:{...$(uQ),category:`distance`},ly:{...$(dQ),category:`distance`},parsec:{...$(0x6da012f95c9fd0),category:`distance`},sec:{...rQ,category:`time`},min:{...$(60),category:`time`},hr:{...$(3600),category:`time`},day:{...$(86400),category:`time`},yr:{...$(31556952),category:`time`},Pa:{...rQ,category:`pressure`},bar:{...$(1e5),category:`pressure`},mmHg:{...$(133.322),category:`pressure`},Torr:{...$(133.322),category:`pressure`},psi:{...$(6894.76),category:`pressure`},atm:{...$(101325),category:`pressure`},N:{...rQ,category:`force`},dyn:{...$(1e-5),category:`force`},pond:{...$(.00980665),category:`force`},lbf:{...$(4.44822),category:`force`},J:{...rQ,category:`energy`},eV:{...$(160218e-24),category:`energy`},e:{...$(1e-7),category:`energy`},flb:{...$(1.3558179483),category:`energy`},c:{...$(4.184),category:`energy`},cal:{...$(4.1868),category:`energy`},BTU:{...$(1055.06),category:`energy`},Wh:{...$(3600),category:`energy`},HPh:{...$(2684520),category:`energy`},W:{...rQ,category:`power`},PS:{...$(735.499),category:`power`},HP:{...$(745.7),category:`power`},T:{...rQ,category:`magnetism`},ga:{...$(1e-4),category:`magnetism`},K:{...rQ,category:`temperature`},C:{transform:e=>e+273.15,inverseTransform:e=>e-273.15,category:`temperature`},F:{transform:e=>(e-32)*5/9+273.15,inverseTransform:e=>(e-273.15)*9/5+32,category:`temperature`},Rank:{...$(5/9),category:`temperature`},Reau:{transform:e=>e*1.25+273.15,inverseTransform:e=>(e-273.15)/1.25,category:`temperature`},"m^3":{...rQ,category:`volume`,order:3},"ang^3":{...$(iQ**3),category:`volume`,order:3},"Picapt^3":{...$(oQ**3),category:`volume`,order:3},tsp:{...$(492892e-11),category:`volume`},tspm:{...$(5e-6),category:`volume`},tbs:{...$(14786764825785619e-21),category:`volume`},"in^3":{...$(aQ**3),category:`volume`,order:3},oz:{...$(295735295625e-16),category:`volume`},cup:{...$(237e-6),category:`volume`},pt:{...$(.0004731765),category:`volume`},uk_pt:{...$(568261e-9),category:`volume`},qt:{...$(.0009463529),category:`volume`},l:{...$(.001),category:`volume`},uk_qt:{...$(.0011365225),category:`volume`},gal:{...$(.0037854118),category:`volume`},uk_gal:{...$(.00454609),category:`volume`},"ft^3":{...$(sQ**3),category:`volume`,order:3},bushel:{...$(.0352390704),category:`volume`},barrel:{...$(.158987295),category:`volume`},"yd^3":{...$(cQ**3),category:`volume`,order:3},MTON:{...$(1.13267386368),category:`volume`},GRT:{...$(2.83168),category:`volume`},"mi^3":{...$(lQ**3),category:`volume`,order:3},"Nmi^3":{...$(uQ**3),category:`volume`,order:3},"ly^3":{...$(dQ**3),category:`volume`,order:3},"m^2":{...rQ,category:`area`,order:2},"ang^2":{...$(iQ**2),category:`area`,order:2},"Picapt^2":{...$(oQ**2),category:`area`,order:2},"in^2":{...$(aQ**2),category:`area`,order:2},"ft^2":{...$(sQ**2),category:`area`,order:2},"yd^2":{...$(cQ**2),category:`area`,order:2},ar:{...$(100),category:`area`},Morgen:{...$(2500),category:`area`},uk_acre:{...$(4046.8564224),category:`area`},us_acre:{...$(4046.8726098743),category:`area`},ha:{...$(1e4),category:`area`},"mi^2":{...$(lQ**2),category:`area`,order:2},"Nmi^2":{...$(uQ**2),category:`area`,order:2},"ly^2":{...$(dQ**2),category:`area`,order:2},bit:{...rQ,category:`information`},byte:{...$(8),category:`information`},"m/s":{...rQ,category:`speed`},"m/hr":{...$(1/3600),category:`speed`},"km/hr":{...$(1/3.6),category:`speed`},mph:{...$(.44704),category:`speed`},kn:{...$(.5144444444),category:`speed`},admkn:{...$(.5147733333),category:`speed`}},pQ={shweight:`cwt`,lcwt:`uk_cwt`,hweight:`uk_cwt`,LTON:`uk_ton`,brton:`uk_ton`,pc:`parsec`,Pica:`Picapt`,d:`day`,mn:`min`,s:`sec`,p:`Pa`,at:`atm`,dy:`dyn`,ev:`eV`,hh:`HPh`,wh:`Wh`,btu:`BTU`,h:`HP`,cel:`C`,fah:`F`,kel:`K`,us_pt:`pt`,L:`l`,lt:`l`,ang3:`ang^3`,ft3:`ft^3`,in3:`in^3`,ly3:`ly^3`,m3:`m^3`,mi3:`mi^3`,yd3:`yd^3`,Nmi3:`Nmi^3`,Picapt3:`Picapt^3`,"Pica^3":`Picapt^3`,Pica3:`Picapt^3`,regton:`GRT`,ang2:`ang^2`,ft2:`ft^2`,in2:`in^2`,ly2:`ly^2`,m2:`m^2`,mi2:`mi^2`,Nmi2:`Nmi^2`,Picapt2:`Picapt^2`,"Pica^2":`Picapt^2`,Pica2:`Picapt^2`,yd2:`yd^2`,"m/h":`m/hr`,"m/sec":`m/s`},mQ={"":1,Y:1e24,Z:1e21,E:0xde0b6b3a7640000,P:0x38d7ea4c68000,T:0xe8d4a51000,G:1e9,M:1e6,k:1e3,h:100,da:10,e:10,d:.1,c:.01,m:.001,u:1e-6,n:1e-9,p:1e-12,f:1e-15,a:1e-18,z:1e-21,y:1e-21,Yi:2**80,Zi:2**70,Ei:2**60,Pi:2**50,Ti:2**40,Gi:2**30,Mi:2**20,ki:2**10},hQ={weight:j(`Weight`),distance:j(`Distance`),time:j(`Time`),pressure:j(`Pressure`),force:j(`Force`),energy:j(`Energy`),power:j(`Power`),magnetism:j(`Magnetism`),temperature:j(`Temperature`),volume:j(`Volume`),area:j(`Area`),information:j(`Information`),speed:j(`Speed`)},gQ=Object.entries(fQ).map(([e,t])=>({value:e,label:_Q(t.category)}));function _Q(e){return hQ[e]??``}function vQ(e){for(let[t,n]of Object.entries(mQ)){if(t&&!e.startsWith(t))continue;let r=e.slice(t.length),i=fQ[r];if(!i&&pQ[r]&&(i=fQ[pQ[r]]),i)return{...i,factor:i.order?n**+i.order:n}}}var yQ=l({CONVERT:()=>bQ});let bQ={description:j(`Converts a numeric value to a different unit of measure.`),args:[k(`value (number)`,j(`the numeric value in start_unit to convert to end_unit`)),k(`start_unit (string)`,j(`The starting unit, the unit currently assigned to value`),gQ),k(`end_unit (string)`,j(`The unit of measure into which to convert value`),gQ)],compute:function(e,t,n){let r=I(e,this.locale),i=L(t),a=L(n),o=vQ(i),s=vQ(a);return o?s?o.category===s.category?{value:s.inverseTransform(o.factor*o.transform(r))/s.factor,format:e?.format}:{value:M.GenericError,message:j(`Incompatible units of measure ('%s' vs '%s')`,_Q(o.category),_Q(s.category))}:{value:M.GenericError,message:j(`Invalid units of measure ('%s')`,a)}:{value:M.GenericError,message:j(`Invalid units of measure ('%s')`,i)}},isExported:!0};var xQ=l({CHAR:()=>TQ,CLEAN:()=>EQ,CONCATENATE:()=>DQ,EXACT:()=>OQ,FIND:()=>kQ,FORMAT_LARGE_NUMBER:()=>AQ,JOIN:()=>jQ,LEFT:()=>MQ,LEN:()=>NQ,LOWER:()=>PQ,MID:()=>FQ,PROPER:()=>IQ,REGEXEXTRACT:()=>RQ,REGEXREPLACE:()=>zQ,REGEXTEST:()=>LQ,REPLACE:()=>BQ,RIGHT:()=>VQ,SEARCH:()=>HQ,SPLIT:()=>UQ,SUBSTITUTE:()=>WQ,TEXT:()=>YQ,TEXTAFTER:()=>ZQ,TEXTBEFORE:()=>QQ,TEXTJOIN:()=>GQ,TEXTSPLIT:()=>KQ,TRIM:()=>qQ,UPPER:()=>JQ,VALUE:()=>XQ});let SQ=/[A-Za-zÀ-ÖØ-öø-ÿ]+/g,CQ=[{value:0,label:j(`Case-sensitive (default)`)},{value:1,label:j(`Case-insensitive`)}],wQ=[{value:0,label:j(`Don't match to end (default)`)},{value:1,label:j(`Match to end`)}],TQ={description:j(`Gets character associated with number.`),args:[k(`table_number (number)`,j(`The number of the character to look up from the current Unicode table in decimal format.`))],compute:function(e){let t=Math.trunc(I(e,this.locale));return t<1?new N(j(`The table_number (%s) is out of range.`,t)):String.fromCharCode(t)},isExported:!0},EQ={description:j(`Remove non-printable characters from a piece of text.`),args:[k(`text (string)`,j(`The text whose non-printable characters are to be removed.`))],compute:function(e){let t=L(e),n=``;for(let e of t)e&&e.charCodeAt(0)>31&&(n+=e);return n},isExported:!0},DQ={description:j(`Appends strings to one another.`),args:[k(`string (string, range<string>, repeating)`,j(`String to append in sequence.`))],compute:function(...e){return io(e,(e,t)=>e+L(t),``)},isExported:!0},OQ={description:j(`Tests whether two strings are identical.`),args:[k(`string1 (string)`,j(`The first string to compare.`)),k(`string2 (string)`,j(`The second string to compare.`))],compute:function(e,t){return L(e)===L(t)},isExported:!0},kQ={description:j(`First position of string found in text, case-sensitive.`),args:[k(`search_for (string)`,j(`The string to look for within text_to_search.`)),k(`text_to_search (string)`,j(`The text to search for the first occurrence of search_for.`)),k(`starting_at (number, default=1)`,j(`The character within text_to_search at which to start the search.`))],compute:function(e,t,n={value:1}){let r=L(e),i=L(t),a=I(n,this.locale);if(i===``)return new N(j(`The text_to_search must be non-empty.`));if(a<1)return new N(j(`The starting_at (%s) must be greater than or equal to 1.`,a));let o=i.indexOf(r,a-1);return o===-1?new N(j(`In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.`,r,i)):o+1},isExported:!0},AQ={description:j(`Apply a large number format`),args:[k(`value (number)`,j(`The number.`)),k(`unit (string, optional)`,j(`The formatting unit. Use 'k', 'm', or 'b' to force the unit`),[{value:`k`,label:j(`Thousand`)},{value:`m`,label:j(`Million`)},{value:`b`,label:j(`Billion`)}])],compute:function(e,t){return{value:I(e,this.locale),format:Xl(e,t,this.locale)}}},jQ={description:j(`Concatenates elements of arrays with delimiter.`),args:[k(`delimiter (string)`,j(`The character or string to place between each concatenated value.`)),k(`value_or_array (string, range<string>, repeating)`,j(`Value to be appended using delimiter.`))],compute:function(e,...t){let n=L(e);return io(t,(e,t)=>(e?e+n:``)+L(t),``)}},MQ={description:j(`Substring from beginning of specified string.`),args:[k(`text (string)`,j(`The string from which the left portion will be returned.`)),k(`number_of_characters (number, optional)`,j(`The number of characters to return from the left side of string.`))],compute:function(e,...t){let n=t.length?I(t[0],this.locale):1;return n<0?new N(j(`The number_of_characters (%s) must be positive or null.`,n)):L(e).substring(0,n)},isExported:!0},NQ={description:j(`Length of a string.`),args:[k(`text (string)`,j(`The string whose length will be returned.`))],compute:function(e){return L(e).length},isExported:!0},PQ={description:j(`Converts a specified string to lowercase.`),args:[k(`text (string)`,j(`The string to convert to lowercase.`))],compute:function(e){return L(e).toLowerCase()},isExported:!0},FQ={description:j(`A segment of a string.`),args:[k(`text (string)`,j(`The string to extract a segment from.`)),k(`starting_at (number)`,j(`The index from the left of string from which to begin extracting. The first character in string has the index 1.`)),k(`extract_length (number)`,j(`The length of the segment to extract.`))],compute:function(e,t,n){let r=L(e),i=I(t,this.locale),a=I(n,this.locale);return i<1?new N(j(`The starting_at argument (%s) must be positive greater than one.`,i.toString())):a<0?new N(j(`The extract_length argument (%s) must be positive or null.`,a)):r.slice(i-1,i+a-1)},isExported:!0},IQ={description:j(`Capitalizes each word in a specified string.`),args:[k(`text_to_capitalize (string)`,j(`The text which will be returned with the first letter of each word in uppercase and all other letters in lowercase.`))],compute:function(e){return L(e).replace(SQ,e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())},isExported:!0},LQ={description:j(`Checks whether a string matches the supplied regular expression.`),args:[k(`text (string)`,j(`The string to test.`)),k(`pattern (string)`,j(`The regular expression pattern to match against the text.`)),k(`case_sensitivity (number, default=0)`,j(`Whether the match is case-sensitive.`),[{value:0,label:j(`Case-sensitive`)},{value:1,label:j(`Case-insensitive`)}])],compute:function(e,t,n={value:0}){let r=L(e),i=L(t),a=I(n,this.locale);if(i===``)return!0;if(r===``)return!1;if(a!==0&&a!==1)return new N(j(`The case_sensitivity (%s) must be 0 or 1.`,a));let o=a===1?`gi`:`g`,s;try{s=new RegExp(i,o)}catch{return new N(j(`Invalid regular expression`))}return s.test(r)},isExported:!0},RQ={description:j(`Extract text from a string based on the supplied regular expression.`),args:[k(`text (string)`,j(`The string on which you want to extract text.`)),k(`pattern (string)`,j(`The regular expression pattern to match against the text.`)),k(`return_mode (number, default=0)`,j(`0 = first match, 1 = all matches as an array, 2 = capturing groups from the first match as an array.`),[{value:0,label:j(`First match`)},{value:1,label:j(`All matches`)},{value:2,label:j(`Capture groups of first match`)}]),k(`case_sensitivity (number, default=0)`,j(`Whether the match is case-sensitive.`),[{value:0,label:j(`Case-sensitive`)},{value:1,label:j(`Case-insensitive`)}])],compute:function(e,t,n={value:0},r={value:0}){let i=L(e),a=L(t),o=I(n,this.locale),s=I(r,this.locale);if(i===``||a===``)return{value:``};if(o<0||o>2)return new N(j(`The return_mode (%s) must be 0, 1 or 2.`,o));if(s!==0&&s!==1)return new N(j(`The case_sensitivity (%s) must be 0 or 1.`,s));let c=s===1?`gi`:`g`,l;try{l=new RegExp(a,c)}catch{return new N(j(`Invalid regular expression`))}let u=[...i.matchAll(l)];return u.length===0?{value:M.NotAvailable,message:j(`No matches found.`)}:o===0?u[0][0]:o===1?u.map(e=>[e[0]]):u[0].length<2?new N(j(`No capturing groups found.`)):u[0].slice(1).map(e=>[e])},isExported:!0},zQ={description:j(`Replace text in a string based on the supplied regular expression.`),args:[k(`text (string)`,j(`The string in which you want to replace text.`)),k(`pattern (string)`,j(`The regular expression pattern to match against the text.`)),k(`replacement (string)`,j(`The text to use as the replacement.`)),k(`occurrence (number, default=0)`,j(`0 = replace all matches. A negative number counts from the end.`)),k(`case_sensitivity (number, default=0)`,j(`Whether the match is case-sensitive.`),[{value:0,label:j(`Case-sensitive`)},{value:1,label:j(`Case-insensitive`)}])],compute:function(e,t,n,r={value:0},i={value:0}){let a=L(e),o=L(t),s=L(n),c=I(r,this.locale),l=I(i,this.locale);if(l!==0&&l!==1)return new N(j(`The case_sensitivity (%s) must be 0 or 1.`,l));let u=l===1?`gi`:`g`,d;try{d=new RegExp(o,u)}catch{return new N(j(`Invalid regular expression`))}if(c!==0){let e=[...a.matchAll(d)];if(e.length===0||Math.abs(c)>e.length)return a;let t=c>0?c-1:e.length+c,n=e[t][0].length,r=e[t].index;return a.substring(0,r)+s+a.substring(r+n)}return a.replace(d,s)},isExported:!0},BQ={description:j(`Replaces part of a text string with different text.`),args:[k(`text (string)`,j(`The text, a part of which will be replaced.`)),k(`position (number)`,j(`The position where the replacement will begin (starting from 1).`)),k(`length (number)`,j(`The number of characters in the text to be replaced.`)),k(`new_text (string)`,j(`The text which will be inserted into the original text.`))],compute:function(e,t,n,r){let i=I(t,this.locale);if(i<1)return new N(j(`The position (%s) must be greater than or equal to 1.`,i));let a=L(e),o=I(n,this.locale),s=L(r);return a.substring(0,i-1)+s+a.substring(i-1+o)},isExported:!0},VQ={description:j(`A substring from the end of a specified string.`),args:[k(`text (string)`,j(`The string from which the right portion will be returned.`)),k(`number_of_characters (number, optional)`,j(`The number of characters to return from the right side of string.`))],compute:function(e,...t){let n=t.length?I(t[0],this.locale):1;if(n<0)return new N(j(`The number_of_characters (%s) must be positive or null.`,n));let r=L(e),i=r.length;return r.substring(i-n,i)},isExported:!0},HQ={description:j(`First position of string found in text, ignoring case.`),args:[k(`search_for (string)`,j(`The string to look for within text_to_search.`)),k(`text_to_search (string)`,j(`The text to search for the first occurrence of search_for.`)),k(`starting_at (number, default=1)`,j(`The character within text_to_search at which to start the search.`))],compute:function(e,t,n={value:1}){let r=L(e).toLowerCase(),i=L(t).toLowerCase(),a=I(n,this.locale);if(i===``)return{value:M.GenericError,message:j(`The text_to_search must be non-empty.`)};if(a<1)return{value:M.GenericError,message:j(`The starting_at (%s) must be greater than or equal to 1.`,a)};let o=i.indexOf(r,a-1);return o===-1?{value:M.GenericError,message:j(`In [[FUNCTION_NAME]] evaluation, cannot find '%s' within '%s'.`,r,i)}:{value:o+1}},isExported:!0},UQ={description:j(`Split text by specific character delimiter(s).`),args:[k(`text (string)`,j(`The text to divide.`)),k(`delimiter (string)`,j(`The character or characters to use to split text.`)),k(`split_by_each (boolean, default=true})`,j(`Whether or not to divide text around each character contained in delimiter.`)),k(`remove_empty_text (boolean, default=true)`,j(`Whether or not to remove empty text messages from the split results. The default behavior is to treat consecutive delimiters as one (if TRUE). If FALSE, empty cells values are added between consecutive delimiters.`))],compute:function(e,t,n={value:!0},r={value:!0}){let i=L(e),a=Ze(L(t)),o=R(n),s=R(r);if(a.length<=0)return new N(j(`The delimiter (%s) must be not be empty.`,a));let c=o?RegExp(`[${a}]`,`g`):new RegExp(a,`g`),l=i.split(c);return s&&(l=l.filter(e=>e!==``)),uo([l])},isExported:!1},WQ={description:j(`Replaces existing text with new text in a string.`),args:[k(`text_to_search (string)`,j(`The text within which to search and replace.`)),k(`search_for (string)`,j(`The string to search for within text_to_search.`)),k(`replace_with (string)`,j(`The string that will replace search_for.`)),k(`occurrence_number (number, optional)`,j(`The instance of search_for within text_to_search to replace with replace_with. By default, all occurrences of search_for are replaced; however, if occurrence_number is specified, only the indicated instance of search_for is replaced.`))],compute:function(e,t,n,r){let i=I(r,this.locale);if(i<0)return new N(j(`The occurrenceNumber (%s) must be positive or null.`,i));let a=L(e),o=L(t);if(o===``)return a;let s=L(n),c=new RegExp(Ze(o),`g`);if(i===0)return a.replace(c,s);let l=0;return a.replace(c,e=>++l===i?s:e)},isExported:!0},GQ={description:j(`Combines text from multiple strings and/or arrays.`),args:[k(`delimiter (string)`,j(`A string, possible empty, or a reference to a valid string. If empty, the text will be simply concatenated.`)),k(`ignore_empty (boolean)`,j(`A boolean; if TRUE, empty cells selected in the text arguments won't be included in the result.`),[{value:!0,label:j(`Ignore empty cells`)},{value:!1,label:j(`Include empty cells (default)`)}]),k(`texts (string, range<string>, repeating)`,j(`Text item to join.`))],compute:function(e,t={value:!0},...n){let r=L(e),i=R(t),a=0;return io(n,(e,t)=>i&&L(t)===``?e:(a++?e+r:``)+L(t),``)},isExported:!0},KQ={description:j(`Splits text into rows or columns using specified column and row delimiters.`),args:[k(`text (string)`,j(`The text to split.`)),k(`col_delimiter (string, range<string>)`,j(`Character or string to split columns by.`)),k(`row_delimiter (string, range<string>, optional)`,j(`Character or string to split rows by.`)),k(`ignore_empty (boolean, default=false)`,j(`Whether to ignore empty cells.`),[{value:!1,label:j(`Include empty cells (default)`)},{value:!0,label:j(`Ignore empty cells`)}]),k(`match_mode (number, default=0)`,j(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),CQ),k(`pad_with (string, default="${M.NotAvailable}")`,j(`The value to use for padding empty cells.`))],compute:function(e,t,n,r={value:!1},i={value:0},a=new Ri){let o=L(e);if(o.length<=0)return new N(j(`No text to split.`));if(t===void 0&&n===void 0)return new N(j(`At least one delimiter must be provided.`));let s=B(t).flat().map(e=>Ze(L(e))),c=B(n).flat().map(e=>Ze(L(e)));if(s.some(e=>e===``)||c.some(e=>e===``))return new N(j(`The delimiters cannot be empty values.`));let l=R(r),u=I(i,this.locale);if(![0,1].includes(u))return new N(j(`match_mode should be a value of 0 or 1.`));let d=[],f=u===1?`gi`:`g`,p=c.filter(e=>!s.includes(e)),m=p.length?o.split(new RegExp(p.join(`|`),f)):[o];l&&(m=m.filter(e=>e!==``));let h=new RegExp(s.join(`|`),f);for(let e of m){let t=s.length?e.split(h):[e];l&&(t=t.filter(e=>e!==``)),d.push(t.map(e=>({value:e})))}let g=Math.max(...d.map(e=>e.length));for(let e of d)for(;e.length<g;)e.push(a);return uo(d)},isExported:!0},qQ={description:j(`Removes space characters.`),args:[k(`text (string)`,j(`The text or reference to a cell containing text to be trimmed.`))],compute:function(e){return Rt(L(e))},isExported:!0},JQ={description:j(`Converts a specified string to uppercase.`),args:[k(`text (string)`,j(`The string to convert to uppercase.`))],compute:function(e){return L(e).toUpperCase()},isExported:!0},YQ={description:j(`Converts a number to text according to a specified format.`),args:[k(`number (number)`,j(`The number, date or time to format.`)),k(`format (string)`,j(`The case-sensitive format of the result, enclosed in quotation marks. Examples: "0.00" rounded to 2 decimal places, "hh:mm:ss" for hour:minutes:seconds.`))],compute:function(e,t){return H(I(e,this.locale),{format:L(t),locale:this.locale})},isExported:!0},XQ={description:j(`Converts a string to a numeric value.`),args:[k(`value (number)`,j(`the string to be converted`))],compute:function(e){return I(e,this.locale)},isExported:!0},ZQ={description:j(`Returns text that occurs after a given substring or delimiter.`),args:[k(`text (string)`,j(`The source text.`)),k(`delimiter (string)`,j(`The substring after which text will be returned.`)),k(`instance_num (number, default=1)`,j(`The desired instance of the delimiter after which we extract the text. A negative number searches from the end.`)),k(`match_mode (number, default=0)`,j(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),CQ),k(`match_end (number, default=0))`,j(`Whether to treat the end of text as a delimiter.`),wQ),k(`if_not_found (string, default="${M.NotAvailable}")`,j(`Value to return if the delimiter is not found.`))],compute:function(e,t,n={value:1},r={value:0},i={value:0},a=new Ri){let o=L(e),s=I(n,this.locale),c=I(r,this.locale),l=I(i,this.locale);if(s===0)return new N(j(`The instance_num (%s) must not be zero.`,s));if(c!==0&&c!==1)return new N(j(`match_mode should have a value of 0 or 1.`));if(l!==0&&l!==1)return new N(j(`match_end should have a value of 0 or 1.`));let u=L(t);if(u===``)return Math.sign(s)>0?{value:o}:{value:``};let d=c===1?`gi`:`g`,f=Ze(u),p=new RegExp(f,d),m=[...o.matchAll(p)].map(e=>e.index+f.length);if(s<0&&(m=m.reverse()),l&&Math.abs(s)===m.length+1)return Math.sign(s)>0?{value:``}:{value:o};let h=m[Math.abs(s)-1];return h===void 0?a:{value:o.substring(h)}},isExported:!0},QQ={description:j(`Returns text that occurs before a given substring or delimiter.`),args:[k(`text (string)`,j(`The source text.`)),k(`delimiter (string)`,j(`The substring after which text will be returned.`)),k(`instance_num (number, default=1)`,j(`The desired instance of the delimiter before which we extract the text. A negative number searches from the end.`)),k(`match_mode (number, default=0)`,j(`Searches the text for a delimiter match. By default, a case-sensitive match is done.`),CQ),k(`match_end (number, default=0))`,j(`Whether to match a delimiter against the end of the text.`),wQ),k(`if_not_found (string, default="${M.NotAvailable}")`,j(`Value to return if the delimiter is not found.`))],compute:function(e,t,n={value:1},r={value:0},i={value:0},a=new Ri){let o=L(e),s=I(n,this.locale),c=I(r,this.locale),l=I(i,this.locale);if(s===0)return new N(j(`The instance_num (%s) must not be zero.`,s));if(c!==0&&c!==1)return new N(j(`match_mode should have a value of 0 or 1.`));if(l!==0&&l!==1)return new N(j(`match_end should have a value of 0 or 1.`));let u=L(t);if(u===``)return Math.sign(s)>0?{value:``}:{value:o};let d=c===1?`gi`:`g`,f=Ze(u),p=new RegExp(f,d),m=[...o.matchAll(p)].map(e=>e.index+f.length);if(s<0&&(m=m.reverse()),l&&Math.abs(s)===m.length+1)return Math.sign(s)>0?{value:o}:{value:``};let h=m[Math.abs(s)-1];return h===void 0?a:{value:o.substring(0,h-u.length)}},isExported:!0};var $Q=l({HYPERLINK:()=>e$});let e$={description:j(`Creates a hyperlink in a cell.`),args:[k(`url (string)`,j(`The full URL of the link enclosed in quotation marks.`)),k(`link_label (string, optional)`,j(`The text to display in the cell, enclosed in quotation marks.`))],compute:function(e,t){let n=L(e).trim(),r=L(t)||n;return n===``?r:ut(r,n)},isExported:!0},t$=[{name:j(`Array`),functions:_W},{name:j(`Database`),functions:Sq},{name:j(`Date`),functions:RJ},{name:j(`Filter`),functions:SY},{name:j(`Financial`),functions:OY},{name:j(`Info`),functions:LX},{name:j(`Lookup`),functions:fZ},{name:j(`Logical`),functions:XX},{name:j(`Math`),functions:qW},{name:j(`Operator`),functions:IZ},{name:j(`Statistical`),functions:lK},{name:j(`Text`),functions:xQ},{name:j(`Engineering`),functions:bY},{name:j(`Web`),functions:$Q},{name:j(`Parser`),functions:yQ}];for(let e of t$){let t=e.functions;for(let n in t){let r=t[n];r.category=r.category||e.name,n=n.replace(/_/g,`.`),Fo.add(n,{isExported:!1,...r})}}let n$={},r$={MIN_ROW_HEIGHT:10,MIN_COL_WIDTH:5,HEADER_HEIGHT:26,HEADER_WIDTH:48,DESKTOP_BOTTOMBAR_HEIGHT:36,DEFAULT_CELL_WIDTH:96,DEFAULT_CELL_HEIGHT:23,SCROLLBAR_WIDTH:15},i$={autoCompleteProviders:oT,autofillModifiersRegistry:JL,autofillRulesRegistry:YL,cellMenuRegistry:kP,colMenuRegistry:HP,errorTypes:Pi,functionRegistry:Fo,featurePluginRegistry:Bz,iconsOnCellRegistry:CL,statefulUIPluginRegistry:Vz,coreViewsPluginRegistry:Hz,corePluginRegistry:zz,rowMenuRegistry:YP,sidePanelRegistry:ZM,figureRegistry:Ay,chartSidePanelComponentRegistry:rk,chartDataSourceSidePanelComponentRegistry:JD,chartComponentRegistry:sy,chartTypeRegistry:sS,chartSubtypeRegistry:Hv,chartDataSourceRegistry:oS,topbarMenuRegistry:AB,topbarComponentRegistry:XB,clickableCellRegistry:Yz,otRegistry:vR,inverseCommandRegistry:Qz,urlRegistry:Au,cellPopoverRegistry:_w,numberFormatMenuRegistry:gB,repeatLocalCommandTransformRegistry:uz,repeatCommandTransformRegistry:lz,clipboardHandlersRegistries:zF,pivotRegistry:Uj,pivotTimeAdapterRegistry:$h,pivotSidePanelRegistry:iM,pivotNormalizationValueRegistry:jg,supportedPivotPositionalFormulaRegistry:_I,pivotToFunctionValueRegistry:Mg,migrationStepRegistry:UC,chartJsExtensionRegistry:zd},a$={arg:k,isEvaluationError:F,toBoolean:R,toJsDate:z,toNumber:I,toString:L,toNormalizedPivotValue:Dg,toFunctionPivotValue:kg,toXC:E,toZone:yn,toUnboundedZone:vn,toCartesian:sn,numberToLetters:Zt,lettersToNumber:Qt,UuidGenerator:Rd,formatValue:H,createCurrencyFormat:Ul,ColorGenerator:ui,computeTextWidth:bd,createEmptyWorkbookData:lw,createEmptySheet:cw,createEmptyExcelSheet:uw,rgbaToHex:Br,colorToRGBA:Vr,positionToZone:D,isDefined:w,isMatrix:Je,lazy:xt,genericRepeat:YB,createAction:h,createActions:p,transformRangeData:cr,deepEquals:T,overlap:Nn,union:kn,isInside:Fn,deepCopy:x,expandZoneOnInsertion:Tn,reduceZoneOnDeletion:On,unquote:et,getMaxObjectId:yg,getFirstPivotFunction:Jj,getNumberOfPivotFunctions:Xj,parseDimension:Sg,isDateOrDatetimeField:Cg,makeFieldProposal:Zj,periodYearToComparable:Qh,insertTokenAfterArgSeparator:$j,insertTokenAfterLeftParenthesis:eM,mergeContiguousZones:ar,getPivotHighlights:XA,pivotTimeAdapter:eg,UNDO_REDO_PIVOT_COMMANDS:BL,createPivotFormula:Eg,areDomainArgsFieldsValid:Tg,splitReference:Yo,sanitizeSheetName:nt,getUniqueText:Kt,isNumber:Pa,isDateTime:na,createCustomFields:Rg,schemeToColorScale:Bh,isDateTimeFormat:Il,jsDateToNumber:ga,numberToJsDate:ma,DateTime:P,parseFormat:ol,isFormula:qt,domainToColRowDomain:mj,collapseHierarchicalDisplayName:Wg,PositionMap:tN},o$={isMarkdownLink:ct,parseMarkdownLink:dt,markdownLink:ut,openLink:Fu,urlRepresentation:Pu},s$={Checkbox:IT,Section:Z,Select:Ty,RoundColorPicker:ST,ChartDataSeries:XD,ChartErrorSection:eO,ChartLabelRange:ZD,ChartRangeDataSourceComponent:vO,ChartTitle:oO,ChartPanel:sk,ChartFigure:Oy,ChartJsComponent:Gp,ClickableCellSortIcon:vI,ZoomableChartJsComponent:$v,Grid:gI,GridOverlay:GF,ScorecardChart:Rm,GaugeChartComponent:ay,LineConfigPanel:HO,BarConfigPanel:nO,PieChartDesignPanel:GO,GenericChartConfigPanel:tO,ChartWithAxisDesignPanel:hO,GenericZoomableChartDesignPanel:gO,LineChartDesignPanel:UO,GaugeChartConfigPanel:IO,GaugeChartDesignPanel:LO,ScorecardChartConfigPanel:JO,ScorecardChartDesignPanel:YO,GeoChartDesignPanel:BO,RadarChartDesignPanel:KO,WaterfallChartDesignPanel:nk,ComboChartDesignPanel:NO,FunnelChartDesignPanel:FO,SunburstChartDesignPanel:XO,TreeMapChartDesignPanel:tk,ChartTypePicker:ak,FigureComponent:jy,MenuPopover:wy,Popover:by,SelectionInput:jT,ValidationMessages:$D,AddDimensionButton:tj,PivotDimensionGranularity:rj,PivotDimensionOrder:ij,PivotDimension:nj,PivotLayoutConfigurator:cj,PivotHTMLRenderer:bI,PivotDeferUpdate:QA,PivotTitleSection:lj,CogWheelMenu:KD,TextInput:BD,SidePanelCollapsible:ww,RadioSelection:cO,GeoChartRegionSelectSection:RO,ChartDashboardMenu:Ey,FullScreenFigure:yI,NumberInput:rO,TopBar:HV,Composer:Jw},c$={useDragAndDropListItems:wT,useHighlights:dk,useHighlightsOnHover:uk},l$={useStoreProvider:mr,DependencyContainer:ur,CellPopoverStore:vw,ComposerFocusStore:Er,CellComposerStore:TF,FindAndReplaceStore:jk,HighlightStore:cT,DelayedHoveredCellStore:My,HoveredTableStore:HF,ModelStore:yr,NotificationStore:lT,RendererStore:Cr,SelectionInputStore:AT,SpreadsheetStore:wr,useStore:O,useLocalStore:hr,SidePanelStore:$M,PivotSidePanelStore:nM,PivotMeasureDisplayPanelStore:JA,ClientFocusStore:ZP,GridRenderer:$F};function u$(e,t){return Fo.add(e,t),{addFunction:(e,t)=>u$(e,t)}}let d$={DEFAULT_LOCALE:V,HIGHLIGHT_COLOR:ee,PIVOT_STATIC_TABLE_CONFIG:Be,PIVOT_INSERT_TABLE_STYLE_ID:Ve,ChartTerms:Py,FIGURE_ID_SPLITTER:`??`,GRID_ICON_EDGE_LENGTH:17,GRID_ICON_MARGIN:2,CHART_TYPES:zh},f$={...jv,...gv};e.AbstractCellClipboardHandler=WL,e.AbstractChart=Kp,e.AbstractFigureClipboardHandler=sW,e.CellErrorType=M,e.ClientDisconnectedError=ez,e.CommandResult=Ou,e.CompiledFormula=Rc,e.CorePlugin=SI,e.CoreViewPlugin=XI,e.DEFAULT_LOCALE=V,e.DEFAULT_LOCALES=Io,e.DispatchResult=Eu,e.EvaluationError=N,e.LocalTransportService=ZB,e.Model=JU,e.PivotRuntimeDefinition=uj,e.Registry=A,e.Revision=$R,e.SPREADSHEET_DIMENSIONS=r$,e.Spreadsheet=GV,e.SpreadsheetPivotTable=jj,e.UIPlugin=KL,e.__info__=n$,e.addFunction=u$,e.addRenderingLayer=Sr,e.astToFormula=xF,e.canExecuteInReadonly=Tu,e.categories=t$,e.chartHelpers=f$,e.components=s$,e.constants=d$,e.convertAstNodes=Ws,e.coreTypes=Cu,e.createAutocompleteArgumentsProvider=Uz,e.findCellInNewZone=Kn,e.functionCache=Ic,e.getCaretDownSvg=xb,e.getCaretUpSvg=Sb,e.helpers=a$,e.hooks=c$,e.invalidateCFEvaluationCommands=vu,e.invalidateChartEvaluationCommands=gu,e.invalidateDependenciesCommands=_u,e.invalidateEvaluationCommands=hu,e.isCoreCommand=wu,e.isSheetDependent=lu,e.iterateAstNodes=Gs,e.links=o$,e.load=JC,e.lockedSheetAllowedCommands=Su,e.parse=Hs,e.parseTokens=Us,e.readonlyAllowedCommands=xu,e.registries=i$,e.setDefaultSheetViewSize=Re,e.setTranslationMethod=ji,e.stores=l$,e.tokenColors=Ke,e.tokenize=ss,n$.version=`19.3.13`,n$.date=`2026-07-23T07:41:06.182Z`,n$.hash=`2059bd0`})(this.o_spreadsheet=this.o_spreadsheet||{},owl);